README
¶
TwiML
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
- func AllowedCallbackEvent(events string) bool
- func AllowedLanguage(speaker string, language string) bool
- func AllowedMethod(field string) bool
- func Bind(cbRequest interface{}, r *http.Request) error
- func IntBetween(field int, high int, low int) bool
- func Numeric(field string) bool
- func NumericOpt(field string) bool
- func NumericOrWait(field string) bool
- func OneOf(field string, options ...string) bool
- func OneOfOpt(field string, options ...string) bool
- func Required(field string) bool
- func Validate(vf ...bool) bool
- type Client
- type Conference
- type Dial
- type DialActionRequest
- type Enqueue
- type Gather
- type Hangup
- type Leave
- type Markup
- type Number
- type Pause
- type Play
- type Queue
- type Record
- type RecordActionRequest
- type RecordingStatusCallbackRequest
- type Redirect
- type Reject
- type Response
- type Say
- type Sip
- type Sms
- type TranscribeCallbackRequest
- type ValidationError
- type VoiceRequest
Constants ¶
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
const ( Queued = "queued" Ringing = "ringing" InProgress = "in-progress" Completed = "completed" Busy = "busy" Failed = "failed" NoAnswer = "no-answer" Canceled = "canceled" )
Call status
const ( OutboundAPI = "outbound-api" Inbound = "inbound" OutboundDial = "outbound-dial" )
Call directions
const ( TrimSilence = "trim-silence" DoNotTrim = "do-not-trim" )
Trim options
Variables ¶
This section is empty.
Functions ¶
func AllowedCallbackEvent ¶
AllowedCallbackEvent validates that the CallbackEvent is one of the allowed options
func AllowedLanguage ¶
AllowedLanguage validates that the combination of speaker and language is allowable
func AllowedMethod ¶
AllowedMethod validates that a method is either of type GET or POST (or empty string to default)
func Bind ¶
Bind will marshal a callback request from the Twilio API into the cbRequest struct provided
func IntBetween ¶
IntBetween validates that a field is an integer between high and low
func NumericOpt ¶
NumericOpt validates that the field is numeric or empty string (for optional fields)
func NumericOrWait ¶
NumericOrWait validates that a string contains only digits 0-9 or the wait key 'w'
func OneOfOpt ¶
OneOfOpt validates that a field is one of the options provided or the empty string (for optional fields)
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
type Conference ¶
type Conference struct { XMLName xml.Name `xml:"Conference"` 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) 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
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:"waiUrlMethod,attr,omitempty"` WorkflowSid string `xml:"workflowSid,attr,omitempty"` QueueName string `xml:",chardata"` }
Enqueue TwiML
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"` Children []Markup `valid:"-"` }
Gather TwiML
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
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
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
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
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
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 ¶
Add appends TwiML verb structs to response. Valid verbs: Enqueue, Say, Leave, Message, Pause, Play, Record, Redirect, Reject, Hangup
func (*Response) Encode ¶
Encode returns an XML encoded response or a ValidationError if any markup fails validation.
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
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
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.
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.