twiml

package module
v1.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 14, 2019 License: MIT Imports: 7 Imported by: 3

README

TwiML

Go Doc CircleCI

A library for producing TwiML XML markup for use with the Twilio API. This library can generate TwiML responses and provides helpers for processing callbacks and requests from Twilio.

This library does not yet cover the entire TwiML API, but pull requests are welcome if you find something missing.

Processing a request from Twilio

The library contains helpers to bind incoming Twilio requests to a struct that includes all of the available info from the request. Most initial requests from Twilio are of type twiml.VoiceRequest. Other request types are possible as a result of callbacks you register in your response. See the GoDoc for details.

func(w http.ResponseWriter, r *http.Request) {
    var vr twiml.VoiceRequest
    if err := twiml.Bind(&vr, r); err != nil {
        http.Error(w, http.StatusText(400), 400)
        return
    }
    fmt.Printf("Incoming call from %s", vr.From)
}

Constructing a response using TwiML

Once you receive a request from the Twilio API, you construct a TwiML response to provide directions for how to deal with the call. This library includes (most of) the allowable verbs and rules to validate that your response is constructed properly.

// CallRequest will return XML to connect to the forwarding number
func CallRequest(cfg Config) func(http.ResponseWriter, *http.Request) {
    return func(w http.ResponseWriter, r *http.Request) {

        // Bind the request
        var cr twiml.VoiceRequest
        if err := twiml.Bind(&cr, r); err != nil {
            http.Error(w, http.StatusText(400), 400)
            return
        }

        // Create a new response container
        res := twiml.NewResponse()

        switch status := cr.CallStatus; status {

        // Call is already in progress, tell Twilio to continue
        case twiml.InProgress:
            w.WriteHeader(200)
            return

        // Call is ringing but has not been connected yet, respond with
        // a forwarding number
        case twiml.Ringing, twiml.Queued:
            // Create a new Dial verb
            d := twiml.Dial{
                Number:   cfg.ForwardingNumber,
                Action:   "action/",
                Timeout:  15,
                CallerID: cr.To,
            }

            // Add the verb to the response
            res.Add(&d)
            
            // Validate and encode the response.  Validation is done
            // automatically before the response is encoded.
            b, err := res.Encode()
            if err != nil {
                http.Error(w, http.StatusText(502), 502)
                return
            }

            // Write the XML response to the http.ReponseWriter
            if _, err := w.Write(b); err != nil {
                http.Error(w, http.StatusText(502), 502)
                return
            }
            w.Header().Set("Content-Type", "application/xml")
            w.WriteHeader(200)
            return

        // Call is over, hang up
        default:
            res.Add(&twiml.Hangup{})
            b, err := res.Encode()
            if err != nil {
                http.Error(w, http.StatusText(502), 502)
                return
            }
            if _, err := w.Write(b); err != nil {
                http.Error(w, http.StatusText(502), 502)
                return
            }
            w.Header().Set("Content-Type", "application/xml")
            w.WriteHeader(200)
            return
        }
    }
}

The example above shows the general flow of constructing a response. Start with creating a new response container, then use the Add() method to add a TwiML verb with its appropriate configuration. Verbs that allow other verbs to be nested within them expose their own Add() method. On the call to Encode() the complete response is validated to ensure that the response is properly configured.

More examples

For a more detailed example of constructing a small TwiML response server, see my Twilio Voice project which is a Google-voice clone that forwards calls to your number and handles transcribing voicemails.

Documentation

Overview

Package twiml provides Twilio Markup Language support for building web services with instructions for twilio how to handle incoming call or message.

Index

Constants

View Source
const (
	Man                = "man"
	Woman              = "woman"
	Alice              = "alice"
	English            = "en"
	French             = "fr"
	Spanish            = "es"
	German             = "de"
	DanishDenmark      = "da-DK"
	GermanGermany      = "de-DE"
	EnglishAustralia   = "en-AU"
	EnglishCanada      = "en-CA"
	EnglishUK          = "en-UK"
	EnglishIndia       = "en-IN"
	EnglishUSA         = "en-US"
	SpanishCatalan     = "ca-ES"
	SpanishSpain       = "es-ES"
	SpanishMexico      = "es-MX"
	FinishFinland      = "fi-FI"
	FrenchCanada       = "fr-CA"
	FrenchFrance       = "fr-FR"
	ItalianItaly       = "it-IT"
	JapaneseJapan      = "ja-JP"
	KoreanKorea        = "ko-KR"
	NorwegianNorway    = "nb-NO"
	DutchNetherlands   = "nl-NL"
	PolishPoland       = "pl-PL"
	PortugueseBrazil   = "pt-BR"
	PortuguesePortugal = "pt-PT"
	RussianRussia      = "ru-RU"
	SwedishSweden      = "sv-SE"
	ChineseMandarin    = "zh-CH"
	ChineseCantonese   = "zh-HK"
	ChineseTaiwanese   = "zh-TW"
)

Language and speaker options

View Source
const (
	Queued     = "queued"
	Ringing    = "ringing"
	InProgress = "in-progress"
	Completed  = "completed"
	Busy       = "busy"
	Failed     = "failed"
	NoAnswer   = "no-answer"
	Canceled   = "canceled"
)

Call status

View Source
const (
	OutboundAPI  = "outbound-api"
	Inbound      = "inbound"
	OutboundDial = "outbound-dial"
)

Call directions

View Source
const (
	TrimSilence = "trim-silence"
	DoNotTrim   = "do-not-trim"
)

Trim options

Variables

View Source
var (
	// callback events valid for Sip TwiML block
	SipCallbackEvents = constructCallbackEventValidator([]string{"initiated", "ringing", "answered", "completed"})

	// callback events valid for Conference TwiML block
	ConferenceCallbackEvents = constructCallbackEventValidator([]string{"start", "end", "join", "leave", "mute", "hold", "speaker"})
)

Functions

func AllowedCallbackEvent

func AllowedCallbackEvent(events string, callbackValidator *regexp.Regexp) bool

AllowedCallbackEvent validates that the CallbackEvent is one of the allowed options

func AllowedLanguage

func AllowedLanguage(speaker string, language string) bool

AllowedLanguage validates that the combination of speaker and language is allowable

func AllowedMethod

func AllowedMethod(field string) bool

AllowedMethod validates that a method is either of type GET or POST (or empty string to default)

func Bind

func Bind(cbRequest interface{}, r *http.Request) error

Bind will marshal a callback request from the Twilio API into the cbRequest struct provided

func IntBetween

func IntBetween(field int, high int, low int) bool

IntBetween validates that a field is an integer between high and low

func Numeric

func Numeric(field string) bool

Numeric validates that a string contains only digits 0-9

func NumericOpt

func NumericOpt(field string) bool

NumericOpt validates that the field is numeric or empty string (for optional fields)

func NumericOrWait

func NumericOrWait(field string) bool

NumericOrWait validates that a string contains only digits 0-9 or the wait key 'w'

func OneOf

func OneOf(field string, options ...string) bool

OneOf validates that a field is one of the options provided

func OneOfOpt

func OneOfOpt(field string, options ...string) bool

OneOfOpt validates that a field is one of the options provided or the empty string (for optional fields)

func Required

func Required(field string) bool

Required validates that a field is not the empty string

func Validate

func Validate(vf ...bool) bool

Validate aggregates the results of individual validation functions and returns true when all validation functions pass

Types

type Client

type Client struct {
	XMLName xml.Name `xml:"Client"`
	Method  string   `xml:"method,attr,omitempty"`
	URL     string   `xml:"URL,omitempty"`
	Name    string   `xml:",chardata"`
}

Client TwiML

func (*Client) Type

func (c *Client) Type() string

Type returns the XML name of the verb

func (*Client) Validate

func (c *Client) Validate() error

Validate returns an error if the TwiML is constructed improperly

type Conference

type Conference struct {
	XMLName                       xml.Name `xml:"Conference"`
	ConferenceName                string   `xml:",chardata"`
	Muted                         bool     `xml:"muted,attr,omitempty"`
	Beep                          string   `xml:"beep,attr,omitempty"`
	StartConferenceOnEnter        bool     `xml:"startConferenceOnEnter,attr,omitempty"`
	EndConferenceOnExit           bool     `xml:"endConferenceOnExit,attr,omitempty"`
	WaitURL                       string   `xml:"waitUrl,attr,omitempty"`
	WaitMethod                    string   `xml:"waitMethod,attr,omitempty"`
	MaxParticipants               int      `xml:"maxParticipants,attr,omitempty"`
	Record                        string   `xml:"record,attr,omitempty"`
	Trim                          string   `xml:"trim,attr,omitempty"`
	StatusCallbackEvent           string   `xml:"statusCallbackEvent,attr,omitempty"`
	StatusCallback                string   `xml:"statusCallback,attr,omitempty"`
	StatusCallbackMethod          string   `xml:"statusCallbackMethod,attr,omitempty"`
	RecordingStatusCallback       string   `xml:"recordingStatusCallback,attr,omitempty"`
	RecordingStatusCallbackMethod string   `xml:"recordingStatusCallbackMethod,attr,omitempty"`
	EventCallbackURL              string   `xml:"eventCallbackUrl,attr,omitempty"`
}

Conference TwiML

func (*Conference) Type

func (c *Conference) Type() string

Type returns the XML name of the verb

func (*Conference) Validate

func (c *Conference) Validate() error

Validate returns an error if the TwiML is constructed improperly

type Dial

type Dial struct {
	XMLName      xml.Name `xml:"Dial"`
	Action       string   `xml:"action,attr,omitempty"`
	Method       string   `xml:"method,attr,omitempty"`
	Timeout      int      `xml:"timeout,attr,omitempty"`
	HangupOnStar bool     `xml:"hangupOnStar,attr,omitempty"`
	TimeLimit    int      `xml:"timeLimit,attr,omitempty"`
	CallerID     string   `xml:"callerId,attr,omitempty"`
	Record       bool     `xml:"record,attr,omitempty"`
	Number       string   `xml:",chardata"`
	Children     []Markup `xml:",omitempty"`
}

Dial TwiML

func (*Dial) Add

func (d *Dial) Add(ml ...Markup)

Add adds noun structs to a Dial response as children

func (*Dial) Type

func (d *Dial) Type() string

Type returns the XML name of the verb

func (*Dial) Validate

func (d *Dial) Validate() error

Validate returns an error if the TwiML is constructed improperly

type DialActionRequest

type DialActionRequest struct {
	VoiceRequest
	DialCallStatus        string
	DialCallSid           string
	DialCallDuration      int
	RecordingURL          string `schema:"RecordingUrl"`
	QueueSid              string
	DequeueResult         string
	DequeuedCallSid       string
	DequeuedCallQueueTime int
	DequeuedCallDuration  int
}

DialActionRequest represents a request as a result of declaring an `action` URL on the Dial verb

type Enqueue

type Enqueue struct {
	XMLName       xml.Name `xml:"Enqueue"`
	Action        string   `xml:"action,attr,omitempty"`
	Method        string   `xml:"method,attr,omitempty"`
	WaitURL       string   `xml:"waitUrl,attr,omitempty"`
	WaitURLMethod string   `xml:"waitUrlMethod,attr,omitempty"`
	WorkflowSid   string   `xml:"workflowSid,attr,omitempty"`
	QueueName     string   `xml:",chardata"`
}

Enqueue TwiML

func (*Enqueue) Type

func (e *Enqueue) Type() string

Type returns the XML name of the verb

func (*Enqueue) Validate

func (e *Enqueue) Validate() error

Validate returns an error if the TwiML is constructed improperly

type Gather

type Gather struct {
	XMLName               xml.Name `xml:"Gather"`
	Action                string   `xml:"action,attr,omitempty"`
	Method                string   `xml:"method,attr,omitempty"`
	Timeout               int      `xml:"timeout,attr,omitempty"`
	FinishOnKey           string   `xml:"finishOnKey,attr,omitempty"`
	NumDigits             int      `xml:"numDigits,attr,omitempty"`
	Input                 string   `xml:"input,attr,omitempty"`
	Hints                 string   `xml:"hints,attr,omitempty"`
	PartialResultCallback string   `xml:"partialResultCallback,attr,omitempty"`
	Language              string   `xml:"language,attr,omitempty"`
	ProfanityFilter       bool     `xml:"profanityFilter,attr,omitempty"`
	SpeechTimeout         int      `xml:"speechTimeout,attr,omitempty"`
	Children              []Markup `valid:"-"`
}

Gather TwiML

func (*Gather) Add

func (g *Gather) Add(ml ...Markup)

Add collects digits a caller enter by pressing the keypad to an existing Gather verb. Valid nested verbs: Say, Pause, Play

func (*Gather) Type

func (g *Gather) Type() string

Type returns the XML name of the verb

func (*Gather) Validate

func (g *Gather) Validate() error

Validate returns an error if the TwiML is constructed improperly

type Hangup

type Hangup struct {
	XMLName xml.Name `xml:"Hangup"`
}

Hangup TwiML

func (*Hangup) Type

func (h *Hangup) Type() string

Type returns the XML name of the verb

func (*Hangup) Validate

func (h *Hangup) Validate() error

Validate returns an error if the TwiML is constructed improperly

type Leave

type Leave struct {
	XMLName xml.Name `xml:"Leave"`
}

Leave TwiML

func (*Leave) Type

func (l *Leave) Type() string

Type returns the XML name of the verb

func (*Leave) Validate

func (l *Leave) Validate() error

Validate returns an error if the TwiML is constructed improperly

type Markup

type Markup interface {
	// Type returns the TwiML verb name for use in pattern-matching
	Type() string
	// Validate will verify that TwiML responses are properly constructed of allowed options for all fields
	Validate() error
}

Markup interface is satisfied by valid TwiML verbs.

type Number

type Number struct {
	XMLName    xml.Name `xml:"Number"`
	SendDigits string   `xml:"sendDigits,attr,omitempty"`
	URL        string   `xml:"url,attr,omitempty"`
	Method     string   `xml:"method,attr,omitempty"`
	Number     string   `xml:",chardata"`
}

Number TwiML

func (*Number) Type

func (n *Number) Type() string

Type returns the XML name of the verb

func (*Number) Validate

func (n *Number) Validate() error

Validate returns an error if the TwiML is constructed improperly

type Pause

type Pause struct {
	XMLName xml.Name `xml:"Pause"`
	Length  int      `xml:"length,attr,omitempty"`
}

Pause TwiML

func (*Pause) Type

func (p *Pause) Type() string

Type returns the XML name of the verb

func (*Pause) Validate

func (p *Pause) Validate() error

Validate returns an error if the TwiML is constructed improperly

type Play

type Play struct {
	XMLName xml.Name `xml:"Play"`
	Loop    int      `xml:"loop,attr,omitempty"`
	Digits  string   `xml:"digits,attr,omitempty"`
	URL     string   `xml:",chardata"`
}

Play TwiML

func (*Play) Type

func (p *Play) Type() string

Type returns the XML name of the verb

func (*Play) Validate

func (p *Play) Validate() error

Validate returns an error if the TwiML is constructed improperly

type Queue

type Queue struct {
	XMLName             xml.Name `xml:"Queue"`
	URL                 string   `xml:"url,attr,omitempty"`
	Method              string   `xml:"method,attr,omitempty"`
	ReservationSid      string   `xml:"reservationSid,attr,omitempty"`
	PostWorkActivitySid string   `xml:"postWorkActivitySid,attr,omitempty"`
	Name                string   `xml:",chardata"`
}

Queue TwiML

func (*Queue) Type

func (q *Queue) Type() string

Type returns the XML name of the verb

func (*Queue) Validate

func (q *Queue) Validate() error

Validate returns an error if the TwiML is constructed improperly

type Record

type Record struct {
	XMLName                       xml.Name `xml:"Record"`
	Action                        string   `xml:"action,attr,omitempty"`
	Method                        string   `xml:"method,attr,omitempty"`
	Timeout                       int      `xml:"timeout,attr,omitempty"`
	FinishOnKey                   string   `xml:"finishOnKey,attr,omitempty"`
	MaxLength                     int      `xml:"maxLength,attr,omitempty"`
	PlayBeep                      bool     `xml:"playBeep,attr,omitempty"`
	Trim                          string   `xml:"trim,attr,omitempty"`
	RecordingStatusCallback       string   `xml:"recordingStatusCallback,attr,omitempty"`
	RecordingStatusCallbackMethod string   `xml:"recordingStatusCallbackMethod,attr,omitempty"`
	Transcribe                    bool     `xml:"transcribe,attr,omitempty"`
	TranscribeCallback            string   `xml:"transcribeCallback,attr,omitempty"`
}

Record TwiML

func (*Record) Type

func (r *Record) Type() string

Type returns the XML name of the verb

func (*Record) Validate

func (r *Record) Validate() error

Validate returns an error if the TwiML is constructed improperly

type RecordActionRequest

type RecordActionRequest struct {
	VoiceRequest
	RecordingURL      string `schema:"RecordingUrl"`
	RecordingDuration int
	Digits            string
}

RecordActionRequest represents a request as a result of declaring an `action` URL on a Record verb

type RecordingStatusCallbackRequest

type RecordingStatusCallbackRequest struct {
	AccountSid        string
	CallSid           string
	RecordingSid      string
	RecordingURL      string `schema:"RecordingUrl"`
	RecordingStatus   string
	RecordingDuration int
	RecordingChannels int
	RecordingSource   string
}

RecordingStatusCallbackRequest represents a request as a result of declaring a `recordingStatusCallback` on a Record verb

type Redirect

type Redirect struct {
	XMLName xml.Name `xml:"Redirect"`
	Method  string   `xml:"method,attr,omitempty"`
	URL     string   `xml:",chardata"`
}

Redirect TwiML

func (*Redirect) Type

func (r *Redirect) Type() string

Type returns the XML name of the verb

func (*Redirect) Validate

func (r *Redirect) Validate() error

Validate returns an error if the TwiML is constructed improperly

type Reject

type Reject struct {
	XMLName xml.Name `xml:"Reject"`
	Reason  string   `xml:"reason,attr,omitempty"`
}

Reject TwiML

func (*Reject) Type

func (r *Reject) Type() string

Type returns the XML name of the verb

func (*Reject) Validate

func (r *Reject) Validate() error

Validate returns an error if the TwiML is constructed improperly

type Response

type Response struct {
	XMLName                xml.Name `xml:"Response"`
	IgnoreValidationErrors bool     `xml:"-"`
	Children               []Markup
}

Response container for other TwiML verbs

func NewResponse

func NewResponse() *Response

NewResponse creates new response container. Use Add() to chain together the response from allowed verbs.

func (*Response) Add

func (r *Response) Add(ml ...Markup)

Add appends TwiML verb structs to response. Valid verbs: Enqueue, Say, Leave, Message, Pause, Play, Record, Redirect, Reject, Hangup

func (*Response) Encode

func (r *Response) Encode() ([]byte, error)

Encode returns an XML encoded response or a ValidationError if any markup fails validation.

func (*Response) String

func (r *Response) String() (string, error)

String returns a formatted XML response

func (*Response) Type

func (r *Response) Type() string

Type returns the XML name of the verb

func (*Response) Validate

func (r *Response) Validate() error

Validate recursively validates all nested verbs within the response, returning a ValidationError if any are constructed improperly

type Say

type Say struct {
	XMLName  xml.Name `xml:"Say"`
	Voice    string   `xml:"voice,attr,omitempty"`
	Language string   `xml:"language,attr,omitempty"`
	Loop     int      `xml:"loop,attr,omitempty"`
	Text     string   `xml:",chardata"`
}

Say TwiML

func (*Say) Type

func (s *Say) Type() string

Type returns the XML name of the verb

func (*Say) Validate

func (s *Say) Validate() error

Validate returns an error if the TwiML is constructed improperly

type Sip

type Sip struct {
	XMLName              xml.Name `xml:"Sip"`
	Username             string   `xml:"username,attr,omitempty"`
	Password             string   `xml:"password,attr,omitempty"`
	URL                  string   `xml:"url,attr,omitempty"`
	Method               string   `xml:"method,attr,omitempty"`
	StatusCallbackEvent  string   `xml:"statusCallbackEvent,attr,omitempty"`
	StatusCallback       string   `xml:"statusCallback,attr,omitempty"`
	StatusCallbackMethod string   `xml:"statusCallbackMethod,attr,omitempty"`
	Address              string   `xml:",chardata"`
}

Sip TwiML

func (*Sip) Type

func (s *Sip) Type() string

Type returns the XML name of the verb

func (*Sip) Validate

func (s *Sip) Validate() error

Validate returns an error if the TwiML is constructed improperly

type Sms

type Sms struct {
	XMLName        xml.Name `xml:"Message"`
	To             string   `xml:"to,attr,omitempty"`
	From           string   `xml:"from,attr,omitempty"`
	Action         string   `xml:"action,attr,omitempty"`
	Method         string   `xml:"method,attr,omitempty"`
	StatusCallback string   `xml:"statusCallback,attr,omitempty"`
	Text           string   `xml:",chardata"`
}

Sms TwiML sends an SMS message. Text is required. See the Twilio docs for an explanation of the default values of to and from.

func (*Sms) Type

func (s *Sms) Type() string

Type returns the XML name of the verb

func (*Sms) Validate

func (s *Sms) Validate() error

Validate returns an error if the TwiML is constructed improperly

type TranscribeCallbackRequest

type TranscribeCallbackRequest struct {
	TranscriptionSid    string
	TranscriptionText   string
	TranscriptionStatus string
	TranscriptionURL    string `schema:"TranscriptionUrl"`
	RecordingSid        string
	RecordingURL        string `schema:"RecordingUrl"`
	CallSid             string
	AccountSid          string
	From                string
	To                  string
	CallStatus          string
	APIVersion          string `schema:"ApiVersion"`
	Direction           string
	ForwardedFrom       string
}

TranscribeCallbackRequest represents a request as a result of declaring a `transcribeCallback` on a Record verb

type ValidationError

type ValidationError struct {
	Errors []error
}

ValidationError will return one or more errors encountered during validation

func (ValidationError) Error

func (v ValidationError) Error() string

Error() returns a custom string representation of all errors encountered during validation

type VoiceRequest

type VoiceRequest struct {
	CallSid       string
	AccountSid    string
	From          string
	To            string
	CallStatus    string
	APIVersion    string `schema:"ApiVersion"`
	Direction     string
	ForwardedFrom string
	CallerName    string
	FromCity      string
	FromState     string
	FromZip       string
	FromCountry   string
	ToCity        string
	ToState       string
	ToZip         string
	ToCountry     string
}

VoiceRequest represents the standard request format for callbacks received from the Twilio API. This struct is embedded in other callback requests that return this common data format.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL