Documentation ¶
Overview ¶
Package twilio simplifies interaction with the Twilio API.
The twilio-go library should be your first choice for interacting with the Twilio API; it offers forward compatibility, very fine-grained control of API access, best-in-class control over how long to wait for requests to complete, and great debuggability when things go wrong. Get started by creating a Client:
client := twilio.NewClient("AC123", "123", nil)
All of the Twilio resources are available as properties on the Client. Let's walk through some of the example use cases.
Creating a Resource ¶
Resources that can create new methods take a url.Values as an argument, and pass all arguments to the Twilio API. This method ensures forward compatibility; any new arguments that get invented can be added in client-side code.
data := url.Values{"To": []string{"+1foo"}, "From": []string{"+1foo"}, "Body": []string{"+1foo"}} msg, err := client.Messages.Create(context.TODO(), data)
Getting an Instance Resource ¶
Call Get() with a particular sid.
number, err := client.IncomingNumbers.Get(context.TODO(), "PN123") fmt.Println(number.PhoneNumber)
Updating an Instance Resource ¶
Call Update() with a particular sid and a url.Values.
data := url.Values{} data.Set("Status", string(twilio.StatusCompleted)) call, err := client.Calls.Update("CA123", data)
Getting a List Resource ¶
There are two flavors of interaction. First, if all you want is a single Page of resources, optionally with filters:
page, err := client.Recordings.GetPage(context.TODO(), url.Values{})
To control the page size, set "PageSize": "N" in the url.Values{} field. Twilio defaults to returning 50 results per page if this is not set.
Alternatively you can get a PageIterator and call Next() to repeatedly retrieve pages.
iterator := client.Calls.GetPageIterator(url.Values{"From": []string{"+1foo"}}) for { page, err := iterator.Next(context.TODO()) // NoMoreResults means you've reached the end. if err == twilio.NoMoreResults { break } fmt.Println("start", page.Start) }
Twilio Monitor ¶
Twilio Monitor subresources are available on the Client under the Monitor field, e.g.
alert, err := client.Monitor.Alerts.Get(context.TODO(), "NO123")
Custom Types ¶
There are several custom types and helper functions designed to make your job easier. Where possible, we try to parse values from the Twilio API into a datatype that makes more sense. For example, we try to parse timestamps into Time values, durations into time.Duration, integer values into uints, even if the API returns them as strings, e.g. "3".
All phone numbers have type PhoneNumber. By default these are E.164, but can be printed in Friendly()/Local() variations as well.
num, _ := twilio.NewPhoneNumber("+1 (415) 555-1234") fmt.Println(num.Friendly()) // "+1 415 555 1234"
Any times returned from the Twilio API are of type TwilioTime, which has two properties - Valid (a bool), and Time (a time.Time). Check Valid before using the related Time.
if msg.DateSent.Valid { fmt.Println(msg.DateSent.Time.Format(time.Kitchen) }
There are constants for every Status in the API, for example StatusQueued, which has the value "queued". You can call Friendly() on any Status to get an uppercase version of the status, e.g.
twilio.StatusInProgress.Friendly() // "In Progress"
Example ¶
package main import ( "fmt" "net/url" "time" twilio "github.com/DispatchMe/twilio-go" "github.com/kevinburke/rest" "golang.org/x/net/context" ) var callURL, _ = url.Parse("https://kev.inburke.com/zombo/zombocom.mp3") func main() { client := twilio.NewClient("AC123", "123", nil) // Send a SMS msg, _ := client.Messages.SendMessage("+14105551234", "+14105556789", "Sent via go :) ✓", nil) fmt.Println(msg.Sid, msg.FriendlyPrice()) // Make a call call, _ := client.Calls.MakeCall("+14105551234", "+14105556789", callURL) fmt.Println(call.Sid, call.FriendlyPrice()) _, err := client.IncomingNumbers.BuyNumber("+1badnumber") // Twilio API errors are converted to rest.Error types if err != nil { restErr, ok := err.(*rest.Error) if ok { fmt.Println(restErr.Title) fmt.Println(restErr.Type) } } // Find all calls from a number data := url.Values{"From": []string{"+14105551234"}} iterator := client.Calls.GetPageIterator(data) ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute) defer cancel() for { page, err := iterator.Next(ctx) if err == twilio.NoMoreResults { break } for _, call := range page.Calls { fmt.Println(call.Sid, call.To) } } }
Output:
Index ¶
- Constants
- Variables
- func GetExpectedTwilioSignature(host string, authToken string, URL string, postForm url.Values) (expectedTwilioSignature string)
- func ValidateIncomingRequest(host string, authToken string, req *http.Request) (err error)
- type Account
- type AccountPage
- type AccountPageIterator
- type AccountService
- func (a *AccountService) Create(ctx context.Context, data url.Values) (*Account, error)
- func (a *AccountService) Get(ctx context.Context, sid string) (*Account, error)
- func (a *AccountService) GetPage(ctx context.Context, data url.Values) (*AccountPage, error)
- func (c *AccountService) GetPageIterator(data url.Values) *AccountPageIterator
- func (a *AccountService) Update(ctx context.Context, sid string, data url.Values) (*Account, error)
- type Alert
- type AlertPage
- type AlertPageIterator
- type AlertService
- func (a *AlertService) Get(ctx context.Context, sid string) (*Alert, error)
- func (a *AlertService) GetAlertsInRange(start time.Time, end time.Time, data url.Values) AlertPageIterator
- func (a *AlertService) GetNextAlertsInRange(start time.Time, end time.Time, nextPageURI string) AlertPageIterator
- func (a *AlertService) GetPage(ctx context.Context, data url.Values) (*AlertPage, error)
- func (a *AlertService) GetPageIterator(data url.Values) AlertPageIterator
- type AnsweredBy
- type Application
- type ApplicationPage
- type ApplicationPageIterator
- type ApplicationService
- func (c *ApplicationService) Create(ctx context.Context, data url.Values) (*Application, error)
- func (r *ApplicationService) Delete(ctx context.Context, sid string) error
- func (c *ApplicationService) Get(ctx context.Context, sid string) (*Application, error)
- func (c *ApplicationService) GetPage(ctx context.Context, data url.Values) (*ApplicationPage, error)
- func (c *ApplicationService) GetPageIterator(data url.Values) *ApplicationPageIterator
- func (a *ApplicationService) Update(ctx context.Context, sid string, data url.Values) (*Application, error)
- type Call
- type CallPage
- type CallPageIterator
- type CallService
- func (c *CallService) Cancel(sid string) (*Call, error)
- func (c *CallService) Create(ctx context.Context, data url.Values) (*Call, error)
- func (c *CallService) Get(ctx context.Context, sid string) (*Call, error)
- func (c *CallService) GetCallsInRange(start time.Time, end time.Time, data url.Values) CallPageIterator
- func (c *CallService) GetNextCallsInRange(start time.Time, end time.Time, nextPageURI string) CallPageIterator
- func (c *CallService) GetPage(ctx context.Context, data url.Values) (*CallPage, error)
- func (c *CallService) GetPageIterator(data url.Values) CallPageIterator
- func (c *CallService) GetRecordings(ctx context.Context, callSid string, data url.Values) (*RecordingPage, error)
- func (c *CallService) GetRecordingsIterator(callSid string, data url.Values) *RecordingPageIterator
- func (c *CallService) Hangup(sid string) (*Call, error)
- func (c *CallService) MakeCall(from string, to string, u *url.URL) (*Call, error)
- func (c *CallService) Redirect(sid string, u *url.URL) (*Call, error)
- func (c *CallService) Update(ctx context.Context, sid string, data url.Values) (*Call, error)
- type CallerIDRequest
- type Client
- func (c *Client) CreateResource(ctx context.Context, pathPart string, data url.Values, v interface{}) error
- func (c *Client) DeleteResource(ctx context.Context, pathPart string, sid string) error
- func (c *Client) GetNextPage(ctx context.Context, fullUri string, v interface{}) error
- func (c *Client) GetResource(ctx context.Context, pathPart string, sid string, v interface{}) error
- func (c *Client) ListResource(ctx context.Context, pathPart string, data url.Values, v interface{}) error
- func (c *Client) MakeRequest(ctx context.Context, method string, pathPart string, data url.Values, ...) error
- func (c *Client) RequestOnBehalfOf(subaccountSid string)
- func (c *Client) UpdateResource(ctx context.Context, pathPart string, sid string, data url.Values, ...) error
- type Code
- type Conference
- type ConferencePage
- type ConferencePageIterator
- type ConferenceService
- func (c *ConferenceService) Get(ctx context.Context, sid string) (*Conference, error)
- func (c *ConferenceService) GetConferencesInRange(start time.Time, end time.Time, data url.Values) ConferencePageIterator
- func (c *ConferenceService) GetNextConferencesInRange(start time.Time, end time.Time, nextPageURI string) ConferencePageIterator
- func (c *ConferenceService) GetPage(ctx context.Context, data url.Values) (*ConferencePage, error)
- func (c *ConferenceService) GetPageIterator(data url.Values) ConferencePageIterator
- type CountriesPricePage
- type CountryMessagingPriceService
- func (cmps *CountryMessagingPriceService) Get(ctx context.Context, isoCountry string) (*MessagePrice, error)
- func (cmps *CountryMessagingPriceService) GetPage(ctx context.Context, data url.Values) (*CountriesPricePage, error)
- func (cmps *CountryMessagingPriceService) GetPageIterator(data url.Values) *CountryPricePageIterator
- type CountryPhoneNumberPriceService
- func (cpnps *CountryPhoneNumberPriceService) Get(ctx context.Context, isoCountry string) (*NumberPrice, error)
- func (cpnps *CountryPhoneNumberPriceService) GetPage(ctx context.Context, data url.Values) (*CountriesPricePage, error)
- func (cpnps *CountryPhoneNumberPriceService) GetPageIterator(data url.Values) *CountryPricePageIterator
- type CountryPricePageIterator
- type CountryVoicePriceService
- func (cvps *CountryVoicePriceService) Get(ctx context.Context, isoCountry string) (*VoicePrice, error)
- func (cvps *CountryVoicePriceService) GetPage(ctx context.Context, data url.Values) (*CountriesPricePage, error)
- func (cvps *CountryVoicePriceService) GetPageIterator(data url.Values) *CountryPricePageIterator
- type Direction
- type InboundPrice
- type IncomingNumberService
- func (ipn *IncomingNumberService) BuyNumber(phoneNumber string) (*IncomingPhoneNumber, error)
- func (ipn *IncomingNumberService) Get(ctx context.Context, sid string) (*IncomingPhoneNumber, error)
- func (ins *IncomingNumberService) GetPage(ctx context.Context, data url.Values) (*IncomingPhoneNumberPage, error)
- func (c *IncomingNumberService) GetPageIterator(data url.Values) *IncomingPhoneNumberPageIterator
- func (ipn *IncomingNumberService) Release(ctx context.Context, sid string) error
- type IncomingPhoneNumber
- type IncomingPhoneNumberPage
- type IncomingPhoneNumberPageIterator
- type Key
- type KeyPage
- type KeyPageIterator
- type KeyService
- func (c *KeyService) Create(ctx context.Context, data url.Values) (*Key, error)
- func (r *KeyService) Delete(ctx context.Context, sid string) error
- func (c *KeyService) Get(ctx context.Context, sid string) (*Key, error)
- func (c *KeyService) GetPage(ctx context.Context, data url.Values) (*KeyPage, error)
- func (c *KeyService) GetPageIterator(data url.Values) *KeyPageIterator
- func (a *KeyService) Update(ctx context.Context, sid string, data url.Values) (*Key, error)
- type LogLevel
- type Media
- type MediaPage
- type MediaService
- func (m *MediaService) Get(ctx context.Context, messageSid string, sid string) (*Media, error)
- func (m *MediaService) GetImage(ctx context.Context, messageSid string, sid string) (image.Image, error)
- func (m *MediaService) GetPage(ctx context.Context, messageSid string, data url.Values) (*MediaPage, error)
- func (m *MediaService) GetURL(ctx context.Context, messageSid string, sid string) (*url.URL, error)
- type Message
- type MessagePage
- type MessagePageIterator
- type MessagePrice
- type MessageService
- func (m *MessageService) Create(ctx context.Context, data url.Values) (*Message, error)
- func (m *MessageService) Get(ctx context.Context, sid string) (*Message, error)
- func (m *MessageService) GetMediaURLs(ctx context.Context, sid string, data url.Values) ([]*url.URL, error)
- func (c *MessageService) GetMessagesInRange(start time.Time, end time.Time, data url.Values) MessagePageIterator
- func (c *MessageService) GetNextMessagesInRange(start time.Time, end time.Time, nextPageURI string) MessagePageIterator
- func (m *MessageService) GetPage(ctx context.Context, data url.Values) (*MessagePage, error)
- func (m *MessageService) GetPageIterator(data url.Values) MessagePageIterator
- func (m *MessageService) SendMessage(from string, to string, body string, mediaURLs []*url.URL) (*Message, error)
- type MessagingPriceService
- type Meta
- type NullAnsweredBy
- type NumMedia
- type NumberCapability
- type NumberPrice
- type NumberPurchasingService
- type NumberVoicePriceService
- type OutboundCallPrice
- type OutboundSMSPrice
- type OutgoingCallerID
- type OutgoingCallerIDPage
- type OutgoingCallerIDPageIterator
- type OutgoingCallerIDService
- func (c *OutgoingCallerIDService) Create(ctx context.Context, data url.Values) (*CallerIDRequest, error)
- func (o *OutgoingCallerIDService) Delete(ctx context.Context, sid string) error
- func (o *OutgoingCallerIDService) Get(ctx context.Context, sid string) (*OutgoingCallerID, error)
- func (o *OutgoingCallerIDService) GetPage(ctx context.Context, data url.Values) (*OutgoingCallerIDPage, error)
- func (o *OutgoingCallerIDService) GetPageIterator(data url.Values) *OutgoingCallerIDPageIterator
- func (o *OutgoingCallerIDService) Update(ctx context.Context, sid string, data url.Values) (*OutgoingCallerID, error)
- type Page
- type PageIterator
- type Participant
- type ParticipantService
- type PhoneNumber
- type PhoneNumberPrice
- type PhoneNumberPriceService
- type PrefixPrice
- type PriceCountry
- type Queue
- type QueuePage
- type QueuePageIterator
- type QueueService
- func (c *QueueService) Create(ctx context.Context, data url.Values) (*Queue, error)
- func (c *QueueService) Delete(ctx context.Context, sid string) error
- func (c *QueueService) Get(ctx context.Context, sid string) (*Queue, error)
- func (c *QueueService) GetPage(ctx context.Context, data url.Values) (*QueuePage, error)
- func (c *QueueService) GetPageIterator(data url.Values) *QueuePageIterator
- type Recording
- type RecordingPage
- type RecordingPageIterator
- type RecordingService
- func (r *RecordingService) Delete(ctx context.Context, sid string) error
- func (r *RecordingService) Get(ctx context.Context, sid string) (*Recording, error)
- func (r *RecordingService) GetPage(ctx context.Context, data url.Values) (*RecordingPage, error)
- func (r *RecordingService) GetPageIterator(data url.Values) *RecordingPageIterator
- func (r *RecordingService) GetTranscriptions(ctx context.Context, recordingSid string, data url.Values) (*TranscriptionPage, error)
- type Segments
- type Status
- type Transcription
- type TranscriptionPage
- type TranscriptionPageIterator
- type TranscriptionService
- func (c *TranscriptionService) Delete(ctx context.Context, sid string) error
- func (c *TranscriptionService) Get(ctx context.Context, sid string) (*Transcription, error)
- func (c *TranscriptionService) GetPage(ctx context.Context, data url.Values) (*TranscriptionPage, error)
- func (c *TranscriptionService) GetPageIterator(data url.Values) *TranscriptionPageIterator
- type TwilioDuration
- type TwilioTime
- type Values
- type VoiceNumberPrice
- type VoicePrice
- type VoicePriceService
Examples ¶
Constants ¶
const APISearchLayout = "2006-01-02"
Format expected by Twilio for searching date ranges. Monitor and other API's offer better date search filters
const APIVersion = "2010-04-01"
The APIVersion to use. Your mileage may vary using other values for the APIVersion; the resource representations may not match.
const AnsweredByHuman = AnsweredBy("human")
const AnsweredByMachine = AnsweredBy("machine")
const CodeAccountSuspended = 30002
const CodeCarrierViolation = 30007
const CodeDocumentParseFailure = 12100
const CodeForbiddenPhoneNumber = 13225
const CodeHTTPConnectionFailure = 11205
const CodeHTTPProtocolViolation = 11206
const CodeHTTPRetrievalFailure = 11200
const CodeLandline = 30006
const CodeMessageBlocked = 30004
const CodeMessagePriceExceedsMaxPrice = 30010
const CodeMissingSegment = 30009
const CodeNoInternationalAuthorization = 13227
const CodeQueueOverflow = 30001
const CodeReplyLimitExceeded = 14107
const CodeSayInvalidText = 13520
const CodeUnknownDestination = 30005
const CodeUnknownError = 30008
const CodeUnreachable = 30003
const DirectionInbound = Direction("inbound")
const DirectionOutboundAPI = Direction("outbound-api")
const DirectionOutboundCall = Direction("outbound-call")
const DirectionOutboundDial = Direction("outbound-dial")
const DirectionOutboundReply = Direction("outbound-reply")
const DirectionTrunkingOriginating = Direction("trunking-originating")
const DirectionTrunkingTerminating = Direction("trunking-terminating")
const LogLevelDebug = LogLevel("debug")
const LogLevelError = LogLevel("error")
const LogLevelNotice = LogLevel("notice")
const LogLevelWarning = LogLevel("warning")
const MonitorVersion = "v1"
Version of the Twilio Monitor API.
const PricingVersion = "v1"
Version of the Twilio Pricing API.
const StatusAccepted = Status("accepted")
const StatusActive = Status("active")
const StatusBusy = Status("busy")
const StatusCanceled = Status("canceled")
const StatusClosed = Status("closed")
const StatusCompleted = Status("completed")
const StatusDelivered = Status("delivered")
const StatusFailed = Status("failed")
Shared
const StatusInProgress = Status("in-progress")
const StatusNoAnswer = Status("no-answer")
const StatusQueued = Status("queued")
const StatusReceived = Status("received")
const StatusReceiving = Status("receiving")
const StatusRinging = Status("ringing")
const StatusSending = Status("sending")
const StatusSent = Status("sent")
const StatusSuspended = Status("suspended")
const StatusUndelivered = Status("undelivered")
const TimeLayout = "Mon, 2 Jan 2006 15:04:05 -0700"
The reference time, as it appears in the Twilio API.
const Version = "0.55"
The twilio-go version. Run "make release" to bump this number.
Variables ¶
var BaseURL = "https://api.twilio.com"
The base URL serving the API. Override this for testing.
var Epoch = time.Date(2005, 1, 1, 0, 0, 0, 0, time.UTC)
Epoch is a time that predates the formation of the company (January 1, 2005). Use this for start filters when you don't want to filter old results.
var ErrEmptyNumber = errors.New("twilio: The provided phone number was empty")
var HeatDeath = time.Date(6000, 1, 1, 0, 0, 0, 0, time.UTC)
HeatDeath is a sentinel time that should outdate the extinction of the company. Use this with GetXInRange calls when you don't want to specify an end date. Feel free to adjust this number in the year 5960 or so.
var MediaClient = http.Client{ Timeout: defaultTimeout, CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }, }
MediaClient is used for fetching images and does not follow redirects.
var MonitorBaseURL = "https://monitor.twilio.com"
The base URL for Twilio Monitor.
var NoMoreResults = errors.New("twilio: No more results")
NoMoreResults is returned if you reach the end of the result set while paging through resources.
var PricingBaseURL = "https://pricing.twilio.com"
The base URL for Twilio Pricing.
Functions ¶
func ValidateIncomingRequest ¶
ValidateIncomingRequest returns an error if the incoming req could not be validated as coming from Twilio.
This process is frequently error prone, especially if you are running behind a proxy, or Twilio is making requests with a port in the URL. See https://www.twilio.com/docs/security#validating-requests for more information
Types ¶
type Account ¶
type Account struct { Sid string `json:"sid"` FriendlyName string `json:"friendly_name"` Type string `json:"type"` AuthToken string `json:"auth_token"` OwnerAccountSid string `json:"owner_account_sid"` DateCreated TwilioTime `json:"date_created"` DateUpdated TwilioTime `json:"date_updated"` Status Status `json:"status"` SubresourceURIs map[string]string `json:"subresource_uris"` URI string `json:"uri"` }
type AccountPage ¶
type AccountPageIterator ¶
type AccountPageIterator struct {
// contains filtered or unexported fields
}
AccountPageIterator lets you retrieve consecutive AccountPages.
func (*AccountPageIterator) Next ¶
func (c *AccountPageIterator) Next(ctx context.Context) (*AccountPage, error)
Next returns the next page of resources. If there are no more resources, NoMoreResults is returned.
type AccountService ¶
type AccountService struct {
// contains filtered or unexported fields
}
func (*AccountService) Create ¶
Create a new Account with the specified values.
https://www.twilio.com/docs/api/rest/subaccounts#creating-subaccounts
func (*AccountService) GetPage ¶
func (a *AccountService) GetPage(ctx context.Context, data url.Values) (*AccountPage, error)
func (*AccountService) GetPageIterator ¶
func (c *AccountService) GetPageIterator(data url.Values) *AccountPageIterator
GetPageIterator returns a AccountPageIterator with the given page filters. Call iterator.Next() to get the first page of resources (and again to retrieve subsequent pages).
type Alert ¶
type Alert struct { Sid string `json:"sid"` AccountSid string `json:"account_sid"` // For Calls, AlertText is a series of key=value pairs separated by // ampersands AlertText string `json:"alert_text"` APIVersion string `json:"api_version"` DateCreated TwilioTime `json:"date_created"` DateGenerated TwilioTime `json:"date_generated"` DateUpdated TwilioTime `json:"date_updated"` ErrorCode Code `json:"error_code"` LogLevel LogLevel `json:"log_level"` MoreInfo string `json:"more_info"` RequestMethod string `json:"request_method"` RequestURL string `json:"request_url"` RequestVariables Values `json:"request_variables"` ResponseBody string `json:"response_body"` ResponseHeaders Values `json:"response_headers"` ResourceSid string `json:"resource_sid"` ServiceSid json.RawMessage `json:"service_sid"` URL string `json:"url"` }
func (*Alert) Description ¶
Description tries as hard as possible to give you a one sentence description of this Alert, based on its contents. Description does not include a trailing period.
func (*Alert) StatusCode ¶
StatusCode attempts to return a HTTP status code for this Alert. Returns 0 if the status code cannot be found.
type AlertPageIterator ¶
type AlertPageIterator interface { // Next returns the next page of resources. If there are no more resources, // NoMoreResults is returned. Next(context.Context) (*AlertPage, error) }
AlertPageIterator lets you retrieve consecutive pages of resources.
type AlertService ¶
type AlertService struct {
// contains filtered or unexported fields
}
func (*AlertService) GetAlertsInRange ¶
func (a *AlertService) GetAlertsInRange(start time.Time, end time.Time, data url.Values) AlertPageIterator
GetAlertsInRange gets an Iterator containing conferences in the range [start, end), optionally further filtered by data. GetAlertsInRange panics if start is not before end. Any date filters provided in data will be ignored. If you have an end, but don't want to specify a start, use twilio.Epoch for start. If you have a start, but don't want to specify an end, use twilio.HeatDeath for end.
Assumes that Twilio returns resources in chronological order, latest first. If this assumption is incorrect, your results will not be correct.
Returned AlertPages will have at most PageSize results, but may have fewer, based on filtering.
func (*AlertService) GetNextAlertsInRange ¶
func (a *AlertService) GetNextAlertsInRange(start time.Time, end time.Time, nextPageURI string) AlertPageIterator
GetNextAlertsInRange retrieves the page at the nextPageURI and continues retrieving pages until any results are found in the range given by start or end, or we determine there are no more records to be found in that range.
If AlertPage is non-nil, it will have at least one result.
func (*AlertService) GetPage ¶
GetPage returns a single Page of resources, filtered by data.
See https://www.twilio.com/docs/api/monitor/alerts#list-get-filters.
Example ¶
package main import ( "fmt" "log" "net/url" twilio "github.com/DispatchMe/twilio-go" "golang.org/x/net/context" ) func main() { client := twilio.NewClient("AC123", "123", nil) data := url.Values{} data.Set("ResourceSid", "SM123") page, err := client.Monitor.Alerts.GetPage(context.TODO(), data) if err != nil { log.Fatal(err) } for _, alert := range page.Alerts { fmt.Println(alert.Sid) } }
Output:
func (*AlertService) GetPageIterator ¶
func (a *AlertService) GetPageIterator(data url.Values) AlertPageIterator
GetPageIterator returns a AlertPageIterator with the given page filters. Call iterator.Next() to get the first page of resources (and again to retrieve subsequent pages).
type AnsweredBy ¶
type AnsweredBy string
type Application ¶
type Application struct { AccountSid string `json:"account_sid"` APIVersion string `json:"api_version"` DateCreated TwilioTime `json:"date_created"` DateUpdated TwilioTime `json:"date_updated"` FriendlyName string `json:"friendly_name"` MessageStatusCallback string `json:"message_status_callback"` Sid string `json:"sid"` SMSFallbackMethod string `json:"sms_fallback_method"` SMSFallbackURL string `json:"sms_fallback_url"` SMSURL string `json:"sms_url"` StatusCallback string `json:"status_callback"` StatusCallbackMethod string `json:"status_callback_method"` URI string `json:"uri"` VoiceCallerIDLookup bool `json:"voice_caller_id_lookup"` VoiceFallbackMethod string `json:"voice_fallback_method"` VoiceFallbackURL string `json:"voice_fallback_url"` VoiceMethod string `json:"voice_method"` VoiceURL string `json:"voice_url"` }
A Twilio Application. For more documentation, see https://www.twilio.com/docs/api/rest/applications#instance
type ApplicationPage ¶
type ApplicationPage struct { Page Applications []*Application `json:"applications"` }
type ApplicationPageIterator ¶
type ApplicationPageIterator struct {
// contains filtered or unexported fields
}
ApplicationPageIterator lets you retrieve consecutive pages of resources.
func (*ApplicationPageIterator) Next ¶
func (c *ApplicationPageIterator) Next(ctx context.Context) (*ApplicationPage, error)
Next returns the next page of resources. If there are no more resources, NoMoreResults is returned.
type ApplicationService ¶
type ApplicationService struct {
// contains filtered or unexported fields
}
func (*ApplicationService) Create ¶
func (c *ApplicationService) Create(ctx context.Context, data url.Values) (*Application, error)
Create a new Application. This request must include a FriendlyName, and can include these values: https://www.twilio.com/docs/api/rest/applications#list-post-optional-parameters
func (*ApplicationService) Delete ¶
func (r *ApplicationService) Delete(ctx context.Context, sid string) error
Delete the Application with the given sid. If the Application has already been deleted, or does not exist, Delete returns nil. If another error or a timeout occurs, the error is returned.
func (*ApplicationService) Get ¶
func (c *ApplicationService) Get(ctx context.Context, sid string) (*Application, error)
func (*ApplicationService) GetPage ¶
func (c *ApplicationService) GetPage(ctx context.Context, data url.Values) (*ApplicationPage, error)
func (*ApplicationService) GetPageIterator ¶
func (c *ApplicationService) GetPageIterator(data url.Values) *ApplicationPageIterator
GetPageIterator returns a ApplicationPageIterator with the given page filters. Call iterator.Next() to get the first page of resources (and again to retrieve subsequent pages).
func (*ApplicationService) Update ¶
func (a *ApplicationService) Update(ctx context.Context, sid string, data url.Values) (*Application, error)
Update the application with the given data. Valid parameters may be found here: https://www.twilio.com/docs/api/rest/applications#instance-post
type Call ¶
type Call struct { Sid string `json:"sid"` From PhoneNumber `json:"from"` To PhoneNumber `json:"to"` Status Status `json:"status"` StartTime TwilioTime `json:"start_time"` EndTime TwilioTime `json:"end_time"` Duration TwilioDuration `json:"duration"` AccountSid string `json:"account_sid"` Annotation json.RawMessage `json:"annotation"` AnsweredBy NullAnsweredBy `json:"answered_by"` CallerName types.NullString `json:"caller_name"` DateCreated TwilioTime `json:"date_created"` DateUpdated TwilioTime `json:"date_updated"` Direction Direction `json:"direction"` ForwardedFrom PhoneNumber `json:"forwarded_from"` GroupSid string `json:"group_sid"` ParentCallSid string `json:"parent_call_sid"` PhoneNumberSid string `json:"phone_number_sid"` Price string `json:"price"` PriceUnit string `json:"price_unit"` APIVersion string `json:"api_version"` URI string `json:"uri"` }
func (*Call) Ended ¶
Ended returns true if the Call has reached a terminal state, and false otherwise, or if the state can't be determined.
func (*Call) EndedUnsuccessfully ¶
EndedUnsuccessfully returns true if the Call has reached a terminal state and that state isn't "completed".
func (*Call) FriendlyPrice ¶
FriendlyPrice flips the sign of the Price (which is usually reported from the API as a negative number) and adds an appropriate currency symbol in front of it. For example, a PriceUnit of "USD" and a Price of "-1.25" is reported as "$1.25".
type CallPageIterator ¶
type CallPageIterator interface { // Next returns the next page of resources. If there are no more resources, // NoMoreResults is returned. Next(context.Context) (*CallPage, error) }
CallPageIterator lets you retrieve consecutive pages of resources.
type CallService ¶
type CallService struct {
// contains filtered or unexported fields
}
func (*CallService) Cancel ¶
func (c *CallService) Cancel(sid string) (*Call, error)
Cancel an in-progress Call with the given sid. Cancel will not affect in-progress Calls, only those in queued or ringing.
func (*CallService) GetCallsInRange ¶
func (c *CallService) GetCallsInRange(start time.Time, end time.Time, data url.Values) CallPageIterator
GetCallsInRange gets an Iterator containing calls in the range [start, end), optionally further filtered by data. GetCallsInRange panics if start is not before end. Any date filters provided in data will be ignored. If you have an end, but don't want to specify a start, use twilio.Epoch for start. If you have a start, but don't want to specify an end, use twilio.HeatDeath for end.
Assumes that Twilio returns resources in chronological order, latest first. If this assumption is incorrect, your results will not be correct.
Returned CallPages will have at most PageSize results, but may have fewer, based on filtering.
Example ¶
package main import ( "fmt" "log" "net/url" "time" twilio "github.com/DispatchMe/twilio-go" "golang.org/x/net/context" ) func main() { // Get all calls between 10:34:00 Oct 26 and 19:25:59 Oct 27, NYC time. nyc, _ := time.LoadLocation("America/New_York") start := time.Date(2016, 10, 26, 22, 34, 00, 00, nyc) end := time.Date(2016, 10, 27, 19, 25, 59, 00, nyc) client := twilio.NewClient("AC123", "123", nil) iter := client.Calls.GetCallsInRange(start, end, url.Values{}) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() for { page, err := iter.Next(ctx) if err == twilio.NoMoreResults { break } if err != nil { log.Fatal(err) } for i, call := range page.Calls { fmt.Printf("%d: %s (%s)", i, call.Sid, call.DateCreated.Time) } } }
Output:
func (*CallService) GetNextCallsInRange ¶
func (c *CallService) GetNextCallsInRange(start time.Time, end time.Time, nextPageURI string) CallPageIterator
GetNextCallsInRange retrieves the page at the nextPageURI and continues retrieving pages until any results are found in the range given by start or end, or we determine there are no more records to be found in that range.
If CallPage is non-nil, it will have at least one result.
func (*CallService) GetPageIterator ¶
func (c *CallService) GetPageIterator(data url.Values) CallPageIterator
GetPageIterator returns an iterator which can be used to retrieve pages.
func (*CallService) GetRecordings ¶
func (c *CallService) GetRecordings(ctx context.Context, callSid string, data url.Values) (*RecordingPage, error)
GetRecordings returns an array of recordings for this Call. Note there may be more than one Page of results.
func (*CallService) GetRecordingsIterator ¶
func (c *CallService) GetRecordingsIterator(callSid string, data url.Values) *RecordingPageIterator
GetRecordings returns an iterator of recording pages for this Call. Note there may be more than one Page of results.
func (*CallService) Hangup ¶
func (c *CallService) Hangup(sid string) (*Call, error)
Hang up an in-progress call.
func (*CallService) MakeCall ¶
MakeCall starts a new Call from the given phone number to the given phone number, dialing the url when the call connects. MakeCall is a wrapper around Create; if you need more configuration, call that function directly.
type CallerIDRequest ¶
type CallerIDRequest struct { AccountSid string `json:"account_sid"` PhoneNumber PhoneNumber `json:"phone_number"` FriendlyName string `json:"friendly_name"` // Usually six digits, but a string to avoid stripping leading 0's ValidationCode string `json:"validation_code"` CallSid string `json:"call_sid"` }
type Client ¶
type Client struct { *rest.Client Monitor *Client Pricing *Client // FullPath takes a path part (e.g. "Messages") and // returns the full API path, including the version (e.g. // "/2010-04-01/Accounts/AC123/Messages"). FullPath func(pathPart string) string // The API version. APIVersion string AccountSid string AuthToken string // The API Client uses these resources Accounts *AccountService Applications *ApplicationService Calls *CallService Conferences *ConferenceService IncomingNumbers *IncomingNumberService Keys *KeyService Media *MediaService Messages *MessageService OutgoingCallerIDs *OutgoingCallerIDService Queues *QueueService Recordings *RecordingService Transcriptions *TranscriptionService // NewMonitorClient initializes these services Alerts *AlertService // NewPricingClient initializes these services Voice *VoicePriceService Messaging *MessagingPriceService PhoneNumbers *PhoneNumberPriceService }
func NewClient ¶
NewClient creates a Client for interacting with the Twilio API. This is the main entrypoint for API interactions; view the methods on the subresources for more information.
func NewMonitorClient ¶
func NewPricingClient ¶
returns a new Client to use the pricing API
func (*Client) CreateResource ¶
func (c *Client) CreateResource(ctx context.Context, pathPart string, data url.Values, v interface{}) error
CreateResource makes a POST request to the given resource.
func (*Client) DeleteResource ¶
func (*Client) GetNextPage ¶
GetNextPage fetches the Page at fullUri and decodes it into v. fullUri should be a next_page_uri returned in the response to a paging request, and should be the full path, eg "/2010-04-01/.../Messages?Page=1&PageToken=..."
func (*Client) GetResource ¶
GetResource retrieves an instance resource with the given path part (e.g. "/Messages") and sid (e.g. "MM123").
func (*Client) ListResource ¶
func (*Client) MakeRequest ¶
func (c *Client) MakeRequest(ctx context.Context, method string, pathPart string, data url.Values, v interface{}) error
Make a request to the Twilio API.
func (*Client) RequestOnBehalfOf ¶
RequestOnBehalfOf will make all future client requests using the same Account Sid and Auth Token for Basic Auth, but will use the provided subaccountSid in the URL. Use this to make requests on behalf of a subaccount, using the parent account's credentials.
RequestOnBehalfOf is *not* thread safe, and modifies the Client's behavior for all requests going forward.
RequestOnBehalfOf should only be used with api.twilio.com, not (for example) Twilio Monitor.
To authenticate using a subaccount sid / auth token, create a new Client using that account's credentials.
type Code ¶
type Code int
A Twilio error code. A full list can be found here: https://www.twilio.com/docs/api/errors/reference
func (*Code) UnmarshalJSON ¶
type Conference ¶
type Conference struct { Sid string `json:"sid"` // Call status, StatusInProgress or StatusCompleted Status Status `json:"status"` FriendlyName string `json:"friendly_name"` // The conference region, probably "us1" Region string `json:"region"` DateCreated TwilioTime `json:"date_created"` AccountSid string `json:"account_sid"` APIVersion string `json:"api_version"` DateUpdated TwilioTime `json:"date_updated"` URI string `json:"uri"` }
type ConferencePage ¶
type ConferencePage struct { Page Conferences []*Conference }
type ConferencePageIterator ¶
type ConferencePageIterator interface { // Next returns the next page of resources. If there are no more resources, // NoMoreResults is returned. Next(context.Context) (*ConferencePage, error) }
type ConferenceService ¶
type ConferenceService struct {
// contains filtered or unexported fields
}
func (*ConferenceService) Get ¶
func (c *ConferenceService) Get(ctx context.Context, sid string) (*Conference, error)
func (*ConferenceService) GetConferencesInRange ¶
func (c *ConferenceService) GetConferencesInRange(start time.Time, end time.Time, data url.Values) ConferencePageIterator
GetConferencesInRange gets an Iterator containing conferences in the range [start, end), optionally further filtered by data. GetConferencesInRange panics if start is not before end. Any date filters provided in data will be ignored. If you have an end, but don't want to specify a start, use twilio.Epoch for start. If you have a start, but don't want to specify an end, use twilio.HeatDeath for end.
Assumes that Twilio returns resources in chronological order, latest first. If this assumption is incorrect, your results will not be correct.
Returned ConferencePages will have at most PageSize results, but may have fewer, based on filtering.
func (*ConferenceService) GetNextConferencesInRange ¶
func (c *ConferenceService) GetNextConferencesInRange(start time.Time, end time.Time, nextPageURI string) ConferencePageIterator
GetNextConferencesInRange retrieves the page at the nextPageURI and continues retrieving pages until any results are found in the range given by start or end, or we determine there are no more records to be found in that range.
If ConferencePage is non-nil, it will have at least one result.
func (*ConferenceService) GetPage ¶
func (c *ConferenceService) GetPage(ctx context.Context, data url.Values) (*ConferencePage, error)
func (*ConferenceService) GetPageIterator ¶
func (c *ConferenceService) GetPageIterator(data url.Values) ConferencePageIterator
GetPageIterator returns a ConferencePageIterator with the given page filters. Call iterator.Next() to get the first page of resources (and again to retrieve subsequent pages).
type CountriesPricePage ¶
type CountriesPricePage struct { Meta Meta `json:"meta"` Countries []*PriceCountry `json:"countries"` }
type CountryMessagingPriceService ¶
type CountryMessagingPriceService struct {
// contains filtered or unexported fields
}
func (*CountryMessagingPriceService) Get ¶
func (cmps *CountryMessagingPriceService) Get(ctx context.Context, isoCountry string) (*MessagePrice, error)
returns the message price by country
func (*CountryMessagingPriceService) GetPage ¶
func (cmps *CountryMessagingPriceService) GetPage(ctx context.Context, data url.Values) (*CountriesPricePage, error)
returns a list of countries where Twilio messaging services are available and the corresponding URL for retrieving the country specific messaging prices.
func (*CountryMessagingPriceService) GetPageIterator ¶
func (cmps *CountryMessagingPriceService) GetPageIterator(data url.Values) *CountryPricePageIterator
GetPageIterator returns an iterator which can be used to retrieve pages.
type CountryPhoneNumberPriceService ¶
type CountryPhoneNumberPriceService struct {
// contains filtered or unexported fields
}
func (*CountryPhoneNumberPriceService) Get ¶
func (cpnps *CountryPhoneNumberPriceService) Get(ctx context.Context, isoCountry string) (*NumberPrice, error)
returns the phone number price by country
func (*CountryPhoneNumberPriceService) GetPage ¶
func (cpnps *CountryPhoneNumberPriceService) GetPage(ctx context.Context, data url.Values) (*CountriesPricePage, error)
returns a list of countries where Twilio phone numbers are supported
func (*CountryPhoneNumberPriceService) GetPageIterator ¶
func (cpnps *CountryPhoneNumberPriceService) GetPageIterator(data url.Values) *CountryPricePageIterator
GetPageIterator returns an iterator which can be used to retrieve pages.
type CountryPricePageIterator ¶
type CountryPricePageIterator struct {
// contains filtered or unexported fields
}
func (*CountryPricePageIterator) Next ¶
func (c *CountryPricePageIterator) Next(ctx context.Context) (*CountriesPricePage, error)
Next returns the next page of resources. If there are no more resources, NoMoreResults is returned.
type CountryVoicePriceService ¶
type CountryVoicePriceService struct {
// contains filtered or unexported fields
}
func (*CountryVoicePriceService) Get ¶
func (cvps *CountryVoicePriceService) Get(ctx context.Context, isoCountry string) (*VoicePrice, error)
returns the call price by country
func (*CountryVoicePriceService) GetPage ¶
func (cvps *CountryVoicePriceService) GetPage(ctx context.Context, data url.Values) (*CountriesPricePage, error)
returns a list of countries where Twilio voice services are available and the corresponding URL for retrieving the country specific voice prices.
func (*CountryVoicePriceService) GetPageIterator ¶
func (cvps *CountryVoicePriceService) GetPageIterator(data url.Values) *CountryPricePageIterator
GetPageIterator returns an iterator which can be used to retrieve pages.
type InboundPrice ¶
type IncomingNumberService ¶
type IncomingNumberService struct { *NumberPurchasingService Local *NumberPurchasingService TollFree *NumberPurchasingService // contains filtered or unexported fields }
func (*IncomingNumberService) BuyNumber ¶
func (ipn *IncomingNumberService) BuyNumber(phoneNumber string) (*IncomingPhoneNumber, error)
BuyNumber attempts to buy the provided phoneNumber and returns it if successful.
func (*IncomingNumberService) Get ¶
func (ipn *IncomingNumberService) Get(ctx context.Context, sid string) (*IncomingPhoneNumber, error)
Get retrieves a single IncomingPhoneNumber.
func (*IncomingNumberService) GetPage ¶
func (ins *IncomingNumberService) GetPage(ctx context.Context, data url.Values) (*IncomingPhoneNumberPage, error)
GetPage retrieves an IncomingPhoneNumberPage, filtered by the given data.
func (*IncomingNumberService) GetPageIterator ¶
func (c *IncomingNumberService) GetPageIterator(data url.Values) *IncomingPhoneNumberPageIterator
GetPageIterator returns an iterator which can be used to retrieve pages.
type IncomingPhoneNumber ¶
type IncomingPhoneNumber struct { Sid string `json:"sid"` PhoneNumber PhoneNumber `json:"phone_number"` FriendlyName string `json:"friendly_name"` DateCreated TwilioTime `json:"date_created"` AccountSid string `json:"account_sid"` AddressRequirements string `json:"address_requirements"` APIVersion string `json:"api_version"` Beta bool `json:"beta"` Capabilities *NumberCapability `json:"capabilities"` DateUpdated TwilioTime `json:"date_updated"` EmergencyAddressSid types.NullString `json:"emergency_address_sid"` EmergencyStatus string `json:"emergency_status"` SMSApplicationSid string `json:"sms_application_sid"` SMSFallbackMethod string `json:"sms_fallback_method"` SMSFallbackURL string `json:"sms_fallback_url"` SMSMethod string `json:"sms_method"` SMSURL string `json:"sms_url"` StatusCallback string `json:"status_callback"` StatusCallbackMethod string `json:"status_callback_method"` TrunkSid types.NullString `json:"trunk_sid"` URI string `json:"uri"` VoiceApplicationSid string `json:"voice_application_sid"` VoiceCallerIDLookup bool `json:"voice_caller_id_lookup"` VoiceFallbackMethod string `json:"voice_fallback_method"` VoiceFallbackURL string `json:"voice_fallback_url"` VoiceMethod string `json:"voice_method"` VoiceURL string `json:"voice_url"` }
type IncomingPhoneNumberPage ¶
type IncomingPhoneNumberPage struct { Page IncomingPhoneNumbers []*IncomingPhoneNumber `json:"incoming_phone_numbers"` }
type IncomingPhoneNumberPageIterator ¶
type IncomingPhoneNumberPageIterator struct {
// contains filtered or unexported fields
}
func (*IncomingPhoneNumberPageIterator) Next ¶
func (c *IncomingPhoneNumberPageIterator) Next(ctx context.Context) (*IncomingPhoneNumberPage, error)
Next returns the next page of resources. If there are no more resources, NoMoreResults is returned.
type Key ¶
type Key struct { DateCreated TwilioTime `json:"date_created"` DateUpdated TwilioTime `json:"date_updated"` Sid string `json:"sid"` FriendlyName string `json:"friendly_name"` Secret string `json:"secret"` }
A Twilio Key. For more documentation, see https://www.twilio.com/docs/api/rest/keys#instance
type KeyPageIterator ¶
type KeyPageIterator struct {
// contains filtered or unexported fields
}
KeyPageIterator lets you retrieve consecutive pages of resources.
type KeyService ¶
type KeyService struct {
// contains filtered or unexported fields
}
func (*KeyService) Create ¶
Create a new Key. Note the Secret is only returned in response to a Create, you can't retrieve it later.
func (*KeyService) Delete ¶
func (r *KeyService) Delete(ctx context.Context, sid string) error
Delete the Key with the given sid. If the Key has already been deleted, or does not exist, Delete returns nil. If another error or a timeout occurs, the error is returned.
func (*KeyService) GetPageIterator ¶
func (c *KeyService) GetPageIterator(data url.Values) *KeyPageIterator
GetPageIterator returns a KeyPageIterator with the given page filters. Call iterator.Next() to get the first page of resources (and again to retrieve subsequent pages).
type Media ¶
type Media struct { Sid string `json:"sid"` ContentType string `json:"content_type"` AccountSid string `json:"account_sid"` DateCreated TwilioTime `json:"date_created"` DateUpdated TwilioTime `json:"date_updated"` ParentSid string `json:"parent_sid"` URI string `json:"uri"` }
type MediaService ¶
type MediaService struct {
// contains filtered or unexported fields
}
A MediaService lets you retrieve a message's associated Media.
func (*MediaService) GetImage ¶
func (m *MediaService) GetImage(ctx context.Context, messageSid string, sid string) (image.Image, error)
GetImage downloads a Media object and returns an image.Image. The documentation isn't great on what happens - as of October 2016, we make a request to the Twilio API, then to media.twiliocdn.com, then to a S3 URL. We then download that image and decode it based on the provided content-type.
type Message ¶
type Message struct { Sid string `json:"sid"` Body string `json:"body"` From PhoneNumber `json:"from"` To PhoneNumber `json:"to"` Price string `json:"price"` Status Status `json:"status"` AccountSid string `json:"account_sid"` MessagingServiceSid types.NullString `json:"messaging_service_sid"` DateCreated TwilioTime `json:"date_created"` DateUpdated TwilioTime `json:"date_updated"` DateSent TwilioTime `json:"date_sent"` NumSegments Segments `json:"num_segments"` NumMedia NumMedia `json:"num_media"` PriceUnit string `json:"price_unit"` Direction Direction `json:"direction"` SubresourceURIs map[string]string `json:"subresource_uris"` URI string `json:"uri"` APIVersion string `json:"api_version"` ErrorCode Code `json:"error_code"` ErrorMessage string `json:"error_message"` }
func (*Message) FriendlyPrice ¶
FriendlyPrice flips the sign of the Price (which is usually reported from the API as a negative number) and adds an appropriate currency symbol in front of it. For example, a PriceUnit of "USD" and a Price of "-1.25" is reported as "$1.25".
type MessagePage ¶
A MessagePage contains a Page of messages.
type MessagePageIterator ¶
type MessagePageIterator interface { // Next returns the next page of resources. If there are no more resources, // NoMoreResults is returned. Next(context.Context) (*MessagePage, error) }
MessagePageIterator lets you retrieve consecutive pages of resources.
type MessagePrice ¶
type MessagePrice struct { Country string `json:"country"` IsoCountry string `json:"iso_country"` OutboundSMSPrices []OutboundSMSPrice `json:"outbound_sms_prices"` InboundSmsPrices []InboundPrice `json:"inbound_sms_prices"` PriceUnit string `json:"price_unit"` URL string `json:"url"` }
type MessageService ¶
type MessageService struct {
// contains filtered or unexported fields
}
func (*MessageService) Create ¶
Create a message with the given url.Values. For more information on valid values, see https://www.twilio.com/docs/api/rest/sending-messages or use the SendMessage helper.
func (*MessageService) GetMediaURLs ¶
func (m *MessageService) GetMediaURLs(ctx context.Context, sid string, data url.Values) ([]*url.URL, error)
GetMediaURLs gets the URLs of any media for this message. This uses threads to retrieve all URLs simultaneously; if retrieving any URL fails, we return an error for the entire request.
The data can be used to filter the list of returned Media as described here: https://www.twilio.com/docs/api/rest/media#list-get-filters
As of October 2016, only 10 MediaURLs are permitted per message. No attempt is made to page through media resources; omit the PageSize parameter in data, or set it to a value greater than 10, to retrieve all resources.
func (*MessageService) GetMessagesInRange ¶
func (c *MessageService) GetMessagesInRange(start time.Time, end time.Time, data url.Values) MessagePageIterator
GetMessagesInRange gets an Iterator containing calls in the range [start, end), optionally further filtered by data. GetMessagesInRange panics if start is not before end. Any date filters provided in data will be ignored. If you have an end, but don't want to specify a start, use twilio.Epoch for start. If you have a start, but don't want to specify an end, use twilio.HeatDeath for end.
Assumes that Twilio returns resources in chronological order, latest first. If this assumption is incorrect, your results will not be correct.
Returned MessagePages will have at most PageSize results, but may have fewer, based on filtering.
Example ¶
package main import ( "fmt" "log" "net/url" "time" twilio "github.com/DispatchMe/twilio-go" "golang.org/x/net/context" ) func main() { // Get all messages between 10:34:00 Oct 26 and 19:25:59 Oct 27, NYC time. nyc, _ := time.LoadLocation("America/New_York") start := time.Date(2016, 10, 26, 22, 34, 00, 00, nyc) end := time.Date(2016, 10, 27, 19, 25, 59, 00, nyc) client := twilio.NewClient("AC123", "123", nil) iter := client.Messages.GetMessagesInRange(start, end, url.Values{}) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() for { page, err := iter.Next(ctx) if err == twilio.NoMoreResults { break } if err != nil { log.Fatal(err) } for i, message := range page.Messages { fmt.Printf("%d: %s (%s)", i, message.Sid, message.DateCreated.Time) } } }
Output:
func (*MessageService) GetNextMessagesInRange ¶
func (c *MessageService) GetNextMessagesInRange(start time.Time, end time.Time, nextPageURI string) MessagePageIterator
GetNextMessagesInRange retrieves the page at the nextPageURI and continues retrieving pages until any results are found in the range given by start or end, or we determine there are no more records to be found in that range.
If MessagePage is non-nil, it will have at least one result.
func (*MessageService) GetPage ¶
func (m *MessageService) GetPage(ctx context.Context, data url.Values) (*MessagePage, error)
GetPage returns a single page of resources. To retrieve multiple pages, use GetPageIterator.
func (*MessageService) GetPageIterator ¶
func (m *MessageService) GetPageIterator(data url.Values) MessagePageIterator
GetPageIterator returns an iterator which can be used to retrieve pages.
func (*MessageService) SendMessage ¶
func (m *MessageService) SendMessage(from string, to string, body string, mediaURLs []*url.URL) (*Message, error)
SendMessage is a convenience wrapper around Create.
type MessagingPriceService ¶
type MessagingPriceService struct {
Countries *CountryMessagingPriceService
}
type Meta ¶
type Meta struct { FirstPageURL string `json:"first_page_url"` NextPageURL types.NullString `json:"next_page_url"` PreviousPageURL types.NullString `json:"previous_page_url"` Key string `json:"key"` Page uint `json:"page"` PageSize uint `json:"page_size"` }
type NullAnsweredBy ¶
type NullAnsweredBy struct { Valid bool AnsweredBy AnsweredBy }
type NumberCapability ¶
type NumberPrice ¶
type NumberPrice struct { Country string `json:"country"` IsoCountry string `json:"iso_country"` PhoneNumberPrices []PhoneNumberPrice `json:"phone_number_prices"` PriceUnit string `json:"price_unit"` URL string `json:"url"` }
type NumberPurchasingService ¶
type NumberPurchasingService struct {
// contains filtered or unexported fields
}
func (*NumberPurchasingService) Create ¶
func (n *NumberPurchasingService) Create(ctx context.Context, data url.Values) (*IncomingPhoneNumber, error)
Create a phone number (buy a number) with the given values.
type NumberVoicePriceService ¶
type NumberVoicePriceService struct {
// contains filtered or unexported fields
}
func (*NumberVoicePriceService) Get ¶
func (nvps *NumberVoicePriceService) Get(ctx context.Context, number string) (*VoiceNumberPrice, error)
returns the call price by number
type OutboundCallPrice ¶
type OutboundSMSPrice ¶
type OutboundSMSPrice struct { Carrier string `json:"carrier"` MCC string `json:"mcc"` MNC string `json:"mnc"` Prices []InboundPrice `json:"prices"` }
type OutgoingCallerID ¶
type OutgoingCallerID struct { Sid string `json:"sid"` FriendlyName string `json:"friendly_name"` PhoneNumber PhoneNumber `json:"phone_number"` AccountSid string `json:"account_sid"` DateCreated TwilioTime `json:"date_created"` DateUpdated TwilioTime `json:"date_updated"` URI string `json:"uri"` }
type OutgoingCallerIDPage ¶
type OutgoingCallerIDPage struct { Page OutgoingCallerIDs []*OutgoingCallerID `json:"outgoing_caller_ids"` }
type OutgoingCallerIDPageIterator ¶
type OutgoingCallerIDPageIterator struct {
// contains filtered or unexported fields
}
OutgoingCallerIDPageIterator lets you retrieve consecutive pages of resources.
func (*OutgoingCallerIDPageIterator) Next ¶
func (o *OutgoingCallerIDPageIterator) Next(ctx context.Context) (*OutgoingCallerIDPage, error)
Next returns the next page of resources. If there are no more resources, NoMoreResults is returned.
type OutgoingCallerIDService ¶
type OutgoingCallerIDService struct {
// contains filtered or unexported fields
}
func (*OutgoingCallerIDService) Create ¶
func (c *OutgoingCallerIDService) Create(ctx context.Context, data url.Values) (*CallerIDRequest, error)
Create a new OutgoingCallerID. Note the ValidationCode is only returned in response to a Create, you can't retrieve it later.
https://www.twilio.com/docs/api/rest/outgoing-caller-ids#list-post
func (*OutgoingCallerIDService) Delete ¶
func (o *OutgoingCallerIDService) Delete(ctx context.Context, sid string) error
Delete the Caller ID with the given sid. If the ID has already been deleted, or does not exist, Delete returns nil. If another error or a timeout occurs, the error is returned.
func (*OutgoingCallerIDService) Get ¶
func (o *OutgoingCallerIDService) Get(ctx context.Context, sid string) (*OutgoingCallerID, error)
func (*OutgoingCallerIDService) GetPage ¶
func (o *OutgoingCallerIDService) GetPage(ctx context.Context, data url.Values) (*OutgoingCallerIDPage, error)
func (*OutgoingCallerIDService) GetPageIterator ¶
func (o *OutgoingCallerIDService) GetPageIterator(data url.Values) *OutgoingCallerIDPageIterator
GetPageIterator returns a OutgoingCallerIDPageIterator with the given page filters. Call iterator.Next() to get the first page of resources (and again to retrieve subsequent pages).
func (*OutgoingCallerIDService) Update ¶
func (o *OutgoingCallerIDService) Update(ctx context.Context, sid string, data url.Values) (*OutgoingCallerID, error)
Update the caller ID with the given data. Valid parameters may be found here: https://www.twilio.com/docs/api/rest/outgoing-caller-ids#list
type Page ¶
type Page struct { FirstPageURI string `json:"first_page_uri"` Start uint `json:"start"` End uint `json:"end"` NumPages uint `json:"num_pages"` Total uint `json:"total"` NextPageURI types.NullString `json:"next_page_uri"` PreviousPageURI types.NullString `json:"previous_page_uri"` PageSize uint `json:"page_size"` }
type PageIterator ¶
type PageIterator struct {
// contains filtered or unexported fields
}
func NewNextPageIterator ¶
func NewNextPageIterator(client *Client, nextPageURI string) *PageIterator
NewNextPageIterator returns a PageIterator based on the provided nextPageURI, and is designed for iterating if you have a nextPageURI and not a list of query values.
NewNextPageIterator panics if nextPageURI is empty.
func NewPageIterator ¶
func NewPageIterator(client *Client, data url.Values, pathPart string) *PageIterator
NewPageIterator returns a PageIterator that can be used to iterate through values. Call Next() to get the first page of values (and again to get subsequent pages). If there are no more results, NoMoreResults is returned.
func (*PageIterator) Next ¶
func (p *PageIterator) Next(ctx context.Context, v interface{}) error
Next asks for the next page of resources and decodes the results into v.
func (*PageIterator) SetNextPageURI ¶
func (p *PageIterator) SetNextPageURI(npuri types.NullString)
type Participant ¶
type Participant struct { AccountSid string `json:"account_sid"` CallSid string `json:"call_sid"` ConferenceSid string `json:"conference_sid"` DateCreated TwilioTime `json:"date_created"` DateUpdated TwilioTime `json:"date_updated"` EndConferenceOnExit bool `json:"end_conference_on_exit"` Hold bool `json:"hold"` Muted bool `json:"muted"` StartConferenceOnEnter bool `json:"start_conference_on_enter"` URI string `json:"uri"` }
type ParticipantService ¶
type ParticipantService struct {
// contains filtered or unexported fields
}
type PhoneNumber ¶
type PhoneNumber string
func NewPhoneNumber ¶
func NewPhoneNumber(pn string) (PhoneNumber, error)
NewPhoneNumber parses the given value as a phone number or returns an error if it cannot be parsed as one. If a phone number does not begin with a plus sign, we assume it's a US national number. Numbers are stored in E.164 format.
func (PhoneNumber) Friendly ¶
func (pn PhoneNumber) Friendly() string
Friendly returns a friendly international representation of the phone number, for example, "+14105554092" is returned as "+1 410-555-4092". If the phone number is not in E.164 format, we try to parse it as a US number. If we cannot parse it as a US number, it is returned as is.
func (PhoneNumber) Local ¶
func (pn PhoneNumber) Local() string
Local returns a friendly national representation of the phone number, for example, "+14105554092" is returned as "(410) 555-4092". If the phone number is not in E.164 format, we try to parse it as a US number. If we cannot parse it as a US number, it is returned as is.
type PhoneNumberPrice ¶
type PhoneNumberPriceService ¶
type PhoneNumberPriceService struct {
Countries *CountryPhoneNumberPriceService
}
type PrefixPrice ¶
type PriceCountry ¶
type Queue ¶
type Queue struct { Sid string `json:"sid"` AverageWaitTime uint `json:"average_wait_time"` CurrentSize uint `json:"current_size"` FriendlyName string `json:"friendly_name"` MaxSize uint `json:"max_size"` DateCreated TwilioTime `json:"date_created"` DateUpdated TwilioTime `json:"date_updated"` AccountSid string `json:"account_sid"` URI string `json:"uri"` }
type QueuePageIterator ¶
type QueuePageIterator struct {
// contains filtered or unexported fields
}
type QueueService ¶
type QueueService struct {
// contains filtered or unexported fields
}
func (*QueueService) Delete ¶
func (c *QueueService) Delete(ctx context.Context, sid string) error
Delete the Queue with the given sid. If the Queue has already been deleted, or does not exist, Delete returns nil. If another error or a timeout occurs, the error is returned.
func (*QueueService) GetPageIterator ¶
func (c *QueueService) GetPageIterator(data url.Values) *QueuePageIterator
GetPageIterator returns a QueuePageIterator with the given page filters. Call iterator.Next() to get the first page of resources (and again to retrieve subsequent pages).
type Recording ¶
type Recording struct { Sid string `json:"sid"` Duration TwilioDuration `json:"duration"` CallSid string `json:"call_sid"` Status Status `json:"status"` Price string `json:"price"` PriceUnit string `json:"price_unit"` DateCreated TwilioTime `json:"date_created"` AccountSid string `json:"account_sid"` APIVersion string `json:"api_version"` Channels uint `json:"channels"` DateUpdated TwilioTime `json:"date_updated"` URI string `json:"uri"` }
func (*Recording) FriendlyPrice ¶
FriendlyPrice flips the sign of the Price (which is usually reported from the API as a negative number) and adds an appropriate currency symbol in front of it. For example, a PriceUnit of "USD" and a Price of "-1.25" is reported as "$1.25".
type RecordingPage ¶
type RecordingPageIterator ¶
type RecordingPageIterator struct {
// contains filtered or unexported fields
}
func (*RecordingPageIterator) Next ¶
func (r *RecordingPageIterator) Next(ctx context.Context) (*RecordingPage, error)
Next returns the next page of resources. If there are no more resources, NoMoreResults is returned.
type RecordingService ¶
type RecordingService struct {
// contains filtered or unexported fields
}
func (*RecordingService) Delete ¶
func (r *RecordingService) Delete(ctx context.Context, sid string) error
Delete the Recording with the given sid. If the Recording has already been deleted, or does not exist, Delete returns nil. If another error or a timeout occurs, the error is returned.
func (*RecordingService) GetPage ¶
func (r *RecordingService) GetPage(ctx context.Context, data url.Values) (*RecordingPage, error)
func (*RecordingService) GetPageIterator ¶
func (r *RecordingService) GetPageIterator(data url.Values) *RecordingPageIterator
GetPageIterator returns an iterator which can be used to retrieve pages.
func (*RecordingService) GetTranscriptions ¶
func (r *RecordingService) GetTranscriptions(ctx context.Context, recordingSid string, data url.Values) (*TranscriptionPage, error)
type Status ¶
type Status string
The status of the message (accepted, queued, etc). For more information , see https://www.twilio.com/docs/api/rest/message
type Transcription ¶
type Transcription struct { Sid string `json:"sid"` TranscriptionText string `json:"transcription_text"` DateCreated TwilioTime `json:"date_created"` DateUpdated TwilioTime `json:"date_updated"` Duration TwilioDuration `json:"duration"` Price string `json:"price"` PriceUnit string `json:"price_unit"` RecordingSid string `json:"recording_sid"` Status Status `json:"status"` Type string `json:"type"` AccountSid string `json:"account_sid"` APIVersion string `json:"api_version"` URI string `json:"uri"` }
func (*Transcription) FriendlyPrice ¶
func (t *Transcription) FriendlyPrice() string
FriendlyPrice flips the sign of the Price (which is usually reported from the API as a negative number) and adds an appropriate currency symbol in front of it. For example, a PriceUnit of "USD" and a Price of "-1.25" is reported as "$1.25".
type TranscriptionPage ¶
type TranscriptionPage struct { Page Transcriptions []*Transcription }
type TranscriptionPageIterator ¶
type TranscriptionPageIterator struct {
// contains filtered or unexported fields
}
func (*TranscriptionPageIterator) Next ¶
func (c *TranscriptionPageIterator) Next(ctx context.Context) (*TranscriptionPage, error)
Next returns the next page of resources. If there are no more resources, NoMoreResults is returned.
type TranscriptionService ¶
type TranscriptionService struct {
// contains filtered or unexported fields
}
func (*TranscriptionService) Delete ¶
func (c *TranscriptionService) Delete(ctx context.Context, sid string) error
Delete the Transcription with the given sid. If the Transcription has already been deleted, or does not exist, Delete returns nil. If another error or a timeout occurs, the error is returned.
func (*TranscriptionService) Get ¶
func (c *TranscriptionService) Get(ctx context.Context, sid string) (*Transcription, error)
Get returns a single Transcription or an error.
func (*TranscriptionService) GetPage ¶
func (c *TranscriptionService) GetPage(ctx context.Context, data url.Values) (*TranscriptionPage, error)
func (*TranscriptionService) GetPageIterator ¶
func (c *TranscriptionService) GetPageIterator(data url.Values) *TranscriptionPageIterator
GetPageIterator returns a TranscriptionPageIterator with the given page filters. Call iterator.Next() to get the first page of resources (and again to retrieve subsequent pages).
type TwilioDuration ¶
func (TwilioDuration) String ¶
func (td TwilioDuration) String() string
func (*TwilioDuration) UnmarshalJSON ¶
func (td *TwilioDuration) UnmarshalJSON(b []byte) error
type TwilioTime ¶
TwilioTime can parse a timestamp returned in the Twilio API and turn it into a valid Go Time struct.
func NewTwilioTime ¶
func NewTwilioTime(val string) *TwilioTime
NewTwilioTime returns a TwilioTime instance. val should be formatted using the TimeLayout.
func (*TwilioTime) MarshalJSON ¶
func (tt *TwilioTime) MarshalJSON() ([]byte, error)
func (*TwilioTime) UnmarshalJSON ¶
func (t *TwilioTime) UnmarshalJSON(b []byte) error
type Values ¶
Values has the methods of url.Values, but can decode JSON from the response_headers field of an Alert.
func (*Values) UnmarshalJSON ¶
type VoiceNumberPrice ¶
type VoiceNumberPrice struct { Country string `json:"country"` IsoCountry string `json:"iso_country"` Number string `json:"number"` InboundCallPrice InboundPrice `json:"inbound_call_price"` OutboundCallPrice OutboundCallPrice `json:"outbound_call_price"` PriceUnit string `json:"price_unit"` URL string `json:"url"` }
type VoicePrice ¶
type VoicePrice struct { Country string `json:"country"` IsoCountry string `json:"iso_country"` OutboundPrefixPrices []PrefixPrice `json:"outbound_prefix_prices"` InboundCallPrices []InboundPrice `json:"inbound_call_prices"` PriceUnit string `json:"price_unit"` URL string `json:"url"` }
type VoicePriceService ¶
type VoicePriceService struct { Countries *CountryVoicePriceService Numbers *NumberVoicePriceService }
Source Files ¶
- accounts.go
- alert_descriptions.go
- alerts.go
- applications.go
- calls.go
- codes.go
- conferences.go
- doc.go
- http.go
- http_ctx.go
- keys.go
- media.go
- media_go17.go
- messages.go
- outgoingcallerids.go
- page.go
- participants.go
- phonenumbers.go
- prices_messaging.go
- prices_number.go
- prices_voice.go
- queue.go
- recording.go
- transcription.go
- types.go
- validation.go
Directories ¶
Path | Synopsis |
---|---|
Create them on your server and pass them to a client to help verify a client's identity, and to grant access to features in client API's.
|
Create them on your server and pass them to a client to help verify a client's identity, and to grant access to features in client API's. |