twilio

package module
v0.0.0-...-56d30ef Latest Latest
Warning

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

Go to latest
Published: Dec 19, 2020 License: MIT Imports: 28 Imported by: 0

README

twilio-go

A client for accessing the Twilio API with several nice features:

  • Easy-to-use helpers for purchasing phone numbers and sending MMS messages

  • E.164 support, times that are parsed into a time.Time, and other smart types.

  • Finer grained control over timeouts with a Context, and the library uses wall-clock HTTP timeouts, not socket timeouts.

  • Easy debugging network traffic by setting DEBUG_HTTP_TRAFFIC=true in your environment.

  • Easily find calls and messages that occurred between a particular set of time.Times, down to the nanosecond, with GetCallsInRange / GetMessagesInRange.

  • It's clear when the library will make a network request, there are no unexpected latency spikes when paging from one resource to the next.

  • Uses threads to fetch resources concurrently; for example, has methods to fetch all Media for a Message concurrently.

  • Usable, one sentence descriptions of Alerts.

Here are some example use cases:

const sid = "AC123"
const token = "456bef"

client := twilio.NewClient(sid, token, nil)

// Send a message
msg, err := client.Messages.SendMessage("+14105551234", "+14105556789", "Sent via go :) ✓", nil)

// Start a phone call
call, err := client.Calls.MakeCall("+14105551234", "+14105556789",
        "https://kev.inburke.com/zombo/zombocom.mp3")

// Buy a number
number, err := client.IncomingNumbers.BuyNumber("+14105551234")

// Get all calls from a number
data := url.Values{}
data.Set("From", "+14105551234")
callPage, err := client.Calls.GetPage(context.TODO(), data)

// Iterate over calls
iterator := client.Calls.GetPageIterator(url.Values{})
for {
    page, err := iterator.Next(context.TODO())
    if err == twilio.NoMoreResults {
        break
    }
    fmt.Println("start", page.Start)
}

A complete documentation reference can be found at godoc.org.

The API is open to, but unlikely to change, and currently only covers these resources:

  • Alerts
  • Applications
  • Calls
  • Conferences
  • Incoming Phone Numbers
  • Keys
  • Messages
  • Media
  • Outgoing Caller ID's
  • Queues
  • Recordings
  • Transcriptions
  • Access Tokens for IPMessaging, Video and Programmable Voice SDK
  • Pricing
Error Parsing

If the twilio-go client gets an error from the Twilio API, we attempt to convert it to a rest.Error before returning. Here's an example 404.

&rest.Error{
    Title: "The requested resource ... was not found",
    ID: "20404",
    Detail: "",
    Instance: "",
    Type: "https://www.twilio.com/docs/errors/20404",
    StatusCode: 404
}

Not all errors will be a rest.Error however - HTTP timeouts, canceled context.Contexts, and JSON parse errors (HTML error pages, bad gateway responses from proxies) may also be returned as plain Go errors.

Twiml Generation

There are no plans to support Twiml generation in this library. It may be more readable and maintainable to manually write the XML involved in a Twiml response.

API Problems this Library Solves For You
  • Media URL's are returned over HTTP. twilio-go rewrites these URL's to be HTTPS before returning them to you.

  • A subset of Notifications returned code 4107, which doesn't exist. These notifications should have error code 14107. We rewrite the error code internally before returning it to you.

  • The only provided API for filtering calls or messages by date grabs all messages for an entire day, and the day ranges are only available for UTC. Use GetCallsInRange or GetMessagesInRange to do timezone-aware, finer-grained date filtering.

Errata

You can get Alerts for a given Call or MMS by passing ResourceSid=CA123 as a filter to Alerts.GetPage. This functionality is not documented in the API.

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"

	"github.com/kevinburke/rest"
	twilio "github.com/saintpete/twilio-go"
	"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

Examples

Constants

View Source
const APISearchLayout = "2006-01-02"

Format expected by Twilio for searching date ranges. Monitor and other API's offer better date search filters

View Source
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.

View Source
const AnsweredByHuman = AnsweredBy("human")
View Source
const AnsweredByMachine = AnsweredBy("machine")
View Source
const CodeAccountSuspended = 30002
View Source
const CodeCarrierViolation = 30007
View Source
const CodeDocumentParseFailure = 12100
View Source
const CodeForbiddenPhoneNumber = 13225
View Source
const CodeHTTPConnectionFailure = 11205
View Source
const CodeHTTPProtocolViolation = 11206
View Source
const CodeHTTPRetrievalFailure = 11200
View Source
const CodeLandline = 30006
View Source
const CodeMessageBlocked = 30004
View Source
const CodeMessagePriceExceedsMaxPrice = 30010
View Source
const CodeMissingSegment = 30009
View Source
const CodeNoInternationalAuthorization = 13227
View Source
const CodeQueueOverflow = 30001
View Source
const CodeReplyLimitExceeded = 14107
View Source
const CodeSayInvalidText = 13520
View Source
const CodeUnknownDestination = 30005
View Source
const CodeUnknownError = 30008
View Source
const CodeUnreachable = 30003
View Source
const DirectionInbound = Direction("inbound")
View Source
const DirectionOutboundAPI = Direction("outbound-api")
View Source
const DirectionOutboundCall = Direction("outbound-call")
View Source
const DirectionOutboundDial = Direction("outbound-dial")
View Source
const DirectionOutboundReply = Direction("outbound-reply")
View Source
const DirectionTrunkingOriginating = Direction("trunking-originating")
View Source
const DirectionTrunkingTerminating = Direction("trunking-terminating")
View Source
const LogLevelDebug = LogLevel("debug")
View Source
const LogLevelError = LogLevel("error")
View Source
const LogLevelNotice = LogLevel("notice")
View Source
const LogLevelWarning = LogLevel("warning")
View Source
const MonitorVersion = "v1"

Version of the Twilio Monitor API.

View Source
const PricingVersion = "v1"

Version of the Twilio Pricing API.

View Source
const StatusAccepted = Status("accepted")
View Source
const StatusActive = Status("active")
View Source
const StatusBusy = Status("busy")
View Source
const StatusCanceled = Status("canceled")
View Source
const StatusClosed = Status("closed")
View Source
const StatusCompleted = Status("completed")
View Source
const StatusDelivered = Status("delivered")
View Source
const StatusFailed = Status("failed")

Shared

View Source
const StatusInProgress = Status("in-progress")
View Source
const StatusNoAnswer = Status("no-answer")
View Source
const StatusQueued = Status("queued")
View Source
const StatusReceived = Status("received")
View Source
const StatusReceiving = Status("receiving")
View Source
const StatusRinging = Status("ringing")
View Source
const StatusSending = Status("sending")
View Source
const StatusSent = Status("sent")
View Source
const StatusSuspended = Status("suspended")
View Source
const StatusUndelivered = Status("undelivered")
View Source
const TimeLayout = "Mon, 2 Jan 2006 15:04:05 -0700"

The reference time, as it appears in the Twilio API.

View Source
const Version = "0.55"

The twilio-go version. Run "make release" to bump this number.

Variables

View Source
var BaseURL = "https://api.twilio.com"

The base URL serving the API. Override this for testing.

View Source
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.

View Source
var ErrEmptyNumber = errors.New("twilio: The provided phone number was empty")
View Source
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.

View Source
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.

View Source
var MonitorBaseURL = "https://monitor.twilio.com"

The base URL for Twilio Monitor.

View Source
var NoMoreResults = errors.New("twilio: No more results")

NoMoreResults is returned if you reach the end of the result set while paging through resources.

View Source
var PricingBaseURL = "https://pricing.twilio.com"

The base URL for Twilio Pricing.

Functions

func GetExpectedTwilioSignature

func GetExpectedTwilioSignature(host string, authToken string, URL string, postForm url.Values) (expectedTwilioSignature string)

func ValidateIncomingRequest

func ValidateIncomingRequest(host string, authToken string, req *http.Request) (err error)

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 AccountPage struct {
	Page
	Accounts []*Account `json:"accounts"`
}

type AccountPageIterator

type AccountPageIterator struct {
	// contains filtered or unexported fields
}

AccountPageIterator lets you retrieve consecutive AccountPages.

func (*AccountPageIterator) Next

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

func (a *AccountService) Create(ctx context.Context, data url.Values) (*Account, error)

Create a new Account with the specified values.

https://www.twilio.com/docs/api/rest/subaccounts#creating-subaccounts

func (*AccountService) Get

func (a *AccountService) Get(ctx context.Context, sid string) (*Account, error)

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).

func (*AccountService) Update

func (a *AccountService) Update(ctx context.Context, sid string, data url.Values) (*Account, error)

Update the key with the given data. Valid parameters may be found here: https://www.twilio.com/docs/api/rest/keys#instance-post

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

func (a *Alert) Description() string

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

func (a *Alert) StatusCode() int

StatusCode attempts to return a HTTP status code for this Alert. Returns 0 if the status code cannot be found.

type AlertPage

type AlertPage struct {
	Meta   Meta     `json:"meta"`
	Alerts []*Alert `json:"alerts"`
}

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) Get

func (a *AlertService) Get(ctx context.Context, sid string) (*Alert, error)

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

func (a *AlertService) GetPage(ctx context.Context, data url.Values) (*AlertPage, error)

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/saintpete/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

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 (*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

func (c *Call) Ended() bool

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

func (c *Call) EndedUnsuccessfully() bool

EndedUnsuccessfully returns true if the Call has reached a terminal state and that state isn't "completed".

func (*Call) FriendlyPrice

func (c *Call) 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 CallPage

type CallPage struct {
	Page
	Calls []*Call `json:"calls"`
}

A CallPage contains a Page of calls.

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) Create

func (c *CallService) Create(ctx context.Context, data url.Values) (*Call, error)

Initiate a new Call.

func (*CallService) Get

func (c *CallService) Get(ctx context.Context, sid string) (*Call, error)

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/saintpete/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) GetPage

func (c *CallService) GetPage(ctx context.Context, data url.Values) (*CallPage, error)

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

func (c *CallService) MakeCall(from string, to string, u *url.URL) (*Call, error)

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.

func (*CallService) Redirect

func (c *CallService) Redirect(sid string, u *url.URL) (*Call, error)

Redirect the given call to the given URL.

func (*CallService) Update

func (c *CallService) Update(ctx context.Context, sid string, data url.Values) (*Call, error)

Update the call with the given data. Valid parameters may be found here: https://www.twilio.com/docs/api/rest/change-call-state#post-parameters

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

func NewClient(accountSid string, authToken string, httpClient *http.Client) *Client

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 NewMonitorClient(accountSid string, authToken string, httpClient *http.Client) *Client

func NewPricingClient

func NewPricingClient(accountSid string, authToken string, httpClient *http.Client) *Client

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 (c *Client) DeleteResource(ctx context.Context, pathPart string, sid string) error

func (*Client) GetNextPage

func (c *Client) GetNextPage(ctx context.Context, fullUri string, v interface{}) error

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

func (c *Client) GetResource(ctx context.Context, pathPart string, sid string, v interface{}) error

GetResource retrieves an instance resource with the given path part (e.g. "/Messages") and sid (e.g. "MM123").

func (*Client) ListResource

func (c *Client) ListResource(ctx context.Context, pathPart string, data url.Values, v interface{}) error

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

func (c *Client) RequestOnBehalfOf(subaccountSid string)

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.

func (*Client) UpdateResource

func (c *Client) UpdateResource(ctx context.Context, pathPart string, sid string, data url.Values, v interface{}) error

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

func (c *Code) UnmarshalJSON(b []byte) error

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

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

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

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

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 Direction

type Direction string

The direction of the message.

func (Direction) Friendly

func (d Direction) Friendly() string

Friendly prints out a friendly version of the Direction, following the example shown in the Twilio Dashboard.

type InboundPrice

type InboundPrice struct {
	BasePrice    string `json:"base_price"`
	CurrentPrice string `json:"current_price"`
	NumberType   string `json:"number_type"`
}

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

Get retrieves a single IncomingPhoneNumber.

func (*IncomingNumberService) GetPage

GetPage retrieves an IncomingPhoneNumberPage, filtered by the given data.

func (*IncomingNumberService) GetPageIterator

GetPageIterator returns an iterator which can be used to retrieve pages.

func (*IncomingNumberService) Release

func (ipn *IncomingNumberService) Release(ctx context.Context, sid string) error

Release removes an IncomingPhoneNumber from your account.

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

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 KeyPage

type KeyPage struct {
	Page
	Keys []*Key `json:"keys"`
}

type KeyPageIterator

type KeyPageIterator struct {
	// contains filtered or unexported fields
}

KeyPageIterator lets you retrieve consecutive pages of resources.

func (*KeyPageIterator) Next

func (c *KeyPageIterator) Next(ctx context.Context) (*KeyPage, error)

Next returns the next page of resources. If there are no more resources, NoMoreResults is returned.

type KeyService

type KeyService struct {
	// contains filtered or unexported fields
}

func (*KeyService) Create

func (c *KeyService) Create(ctx context.Context, data url.Values) (*Key, error)

Create a new Key. Note the Secret is only returned in response to a Create, you can't retrieve it later.

https://www.twilio.com/docs/api/rest/keys#list-post

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) Get

func (c *KeyService) Get(ctx context.Context, sid string) (*Key, error)

func (*KeyService) GetPage

func (c *KeyService) GetPage(ctx context.Context, data url.Values) (*KeyPage, error)

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).

func (*KeyService) Update

func (a *KeyService) Update(ctx context.Context, sid string, data url.Values) (*Key, error)

Update the key with the given data. Valid parameters may be found here: https://www.twilio.com/docs/api/rest/keys#instance-post

type LogLevel

type LogLevel string

A log level returned for an Alert.

func (LogLevel) Friendly

func (l LogLevel) Friendly() string

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 MediaPage

type MediaPage struct {
	Page
	MediaList []*Media `json:"media_list"`
}

type MediaService

type MediaService struct {
	// contains filtered or unexported fields
}

A MediaService lets you retrieve a message's associated Media.

func (*MediaService) Get

func (m *MediaService) Get(ctx context.Context, messageSid string, sid string) (*Media, error)

Get returns a Media struct representing a Media instance, or an error.

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.

func (*MediaService) GetPage

func (m *MediaService) GetPage(ctx context.Context, messageSid string, data url.Values) (*MediaPage, error)

func (*MediaService) GetURL

func (m *MediaService) GetURL(ctx context.Context, messageSid string, sid string) (*url.URL, error)

GetURL returns a URL that can be retrieved to download the given image.

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

func (m *Message) 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 MessagePage

type MessagePage struct {
	Page
	Messages []*Message `json:"messages"`
}

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

func (m *MessageService) Create(ctx context.Context, data url.Values) (*Message, error)

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) Get

func (m *MessageService) Get(ctx context.Context, sid string) (*Message, error)

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/saintpete/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 NumMedia

type NumMedia uintStr

func (*NumMedia) UnmarshalJSON

func (n *NumMedia) UnmarshalJSON(b []byte) (err error)

type NumberCapability

type NumberCapability struct {
	MMS   bool `json:"mms"`
	SMS   bool `json:"sms"`
	Voice bool `json:"voice"`
}

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

Create a phone number (buy a number) with the given values.

https://www.twilio.com/docs/api/rest/incoming-phone-numbers#toll-free-incomingphonenumber-factory-resource

type NumberVoicePriceService

type NumberVoicePriceService struct {
	// contains filtered or unexported fields
}

func (*NumberVoicePriceService) Get

returns the call price by number

type OutboundCallPrice

type OutboundCallPrice struct {
	BasePrice    string `json:"base_price"`
	CurrentPrice string `json:"current_price"`
}

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

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

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 (*OutgoingCallerIDService) GetPage

func (*OutgoingCallerIDService) GetPageIterator

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

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 PhoneNumberPrice struct {
	BasePrice    string `json:"base_price"`
	CurrentPrice string `json:"current_price"`
	NumberType   string `json:"number_type"`
}

type PhoneNumberPriceService

type PhoneNumberPriceService struct {
	Countries *CountryPhoneNumberPriceService
}

type PrefixPrice

type PrefixPrice struct {
	BasePrice    string   `json:"base_price"`
	CurrentPrice string   `json:"current_price"`
	FriendlyName string   `json:"friendly_name"`
	Prefixes     []string `json:"prefixes"`
}

type PriceCountry

type PriceCountry struct {
	Country    string `json:"country"`
	IsoCountry string `json:"iso_country"`
	URL        string `json:"url"`
}

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 QueuePage

type QueuePage struct {
	Page
	Queues []*Queue
}

type QueuePageIterator

type QueuePageIterator struct {
	// contains filtered or unexported fields
}

func (*QueuePageIterator) Next

func (c *QueuePageIterator) Next(ctx context.Context) (*QueuePage, error)

Next returns the next page of resources. If there are no more resources, NoMoreResults is returned.

type QueueService

type QueueService struct {
	// contains filtered or unexported fields
}

func (*QueueService) Create

func (c *QueueService) Create(ctx context.Context, data url.Values) (*Queue, error)

Create a new Queue.

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) Get

func (c *QueueService) Get(ctx context.Context, sid string) (*Queue, error)

Get returns a single Queue or an error.

func (*QueueService) GetPage

func (c *QueueService) GetPage(ctx context.Context, data url.Values) (*QueuePage, error)

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

func (r *Recording) 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".

func (*Recording) URL

func (r *Recording) URL(extension string) string

URL returns the URL that can be used to play this recording, based on the extension. No error is returned if you provide an invalid extension. As of October 2016, the valid values are ".wav" and ".mp3".

type RecordingPage

type RecordingPage struct {
	Page
	Recordings []*Recording
}

type RecordingPageIterator

type RecordingPageIterator struct {
	// contains filtered or unexported fields
}

func (*RecordingPageIterator) Next

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) Get

func (r *RecordingService) Get(ctx context.Context, sid string) (*Recording, error)

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 Segments

type Segments uintStr

func (*Segments) UnmarshalJSON

func (seg *Segments) UnmarshalJSON(b []byte) (err 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

func (Status) Friendly

func (s Status) Friendly() string

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

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

Get returns a single Transcription or an error.

func (*TranscriptionService) GetPage

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

type TwilioDuration time.Duration

func (TwilioDuration) String

func (td TwilioDuration) String() string

func (*TwilioDuration) UnmarshalJSON

func (td *TwilioDuration) UnmarshalJSON(b []byte) error

type TwilioTime

type TwilioTime struct {
	Time  time.Time
	Valid bool
}

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

type Values struct {
	url.Values
}

Values has the methods of url.Values, but can decode JSON from the response_headers field of an Alert.

func (*Values) UnmarshalJSON

func (h *Values) UnmarshalJSON(b []byte) error

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
}

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.

Jump to

Keyboard shortcuts

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