twilio

package module
v0.0.0-...-b43e6c2 Latest Latest
Warning

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

Go to latest
Published: Jul 8, 2021 License: MIT Imports: 29 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
var callURL, _ = url.Parse("https://kev.inburke.com/zombo/zombocom.mp3")
call, err := client.Calls.MakeCall("+14105551234", "+14105556789", callURL)

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

In Production

twilio-go is being used by the following applications:

  • Logrole, an open source Twilio log viewer that's faster than the API.

Using twilio-go in production? Let me know!

Supported API's

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

  • Alerts
  • Applications
  • Calls
  • Conferences
  • Faxes
  • Incoming Phone Numbers
  • Available Phone Numbers
  • Keys
  • Messages
  • Media
  • Monitor
  • Outgoing Caller ID's
  • Pricing
  • Queues
  • Recordings
  • Task Router
    • Activities
    • TaskQueues
    • Workers
    • Workflows
  • Transcriptions
  • Wireless
  • Voice Insights
  • Access Tokens for IPMessaging, Video and Programmable Voice SDK
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.

Errata
  • Media URL's used to be 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.

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

Consulting

I'm available for hire, for Twilio work or general-purpose engineering. For more on what I can do for your company, see here: https://burke.services/twilio.html. Contact me: kevin@burke.services

Donating

Donations free up time to review pull requests, respond to bug reports, and add new features. In the absence of donations there are no guarantees about timeliness for reviewing or responding to proposed changes; I don't get paid by anyone else to work on this. You can send donations via Github's "Sponsor" mechanism or Paypal's "Send Money" feature to kev@inburke.com. Donations are not tax deductible in the USA.

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 (
	"context"
	"fmt"
	"net/url"
	"time"

	"github.com/kevinburke/rest/resterror"
	twilio "github.com/kevinburke/twilio-go"
)

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 resterror.Error types
	if err != nil {
		restErr, ok := err.(*resterror.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.TODO(), 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:

Example (BuyNumber)
package main

import (
	"context"
	"fmt"
	"net/url"

	twilio "github.com/kevinburke/twilio-go"
)

func main() {
	client := twilio.NewClient("AC123", "123", nil)
	ctx := context.TODO()

	// Find a number in the 925 area code
	var data url.Values
	data.Set("AreaCode", "925")
	numbers, _ := client.AvailableNumbers.Local.GetPage(ctx, "US", data)

	// Buy the first one (if there's at least one to buy)
	if len(numbers.Numbers) == 0 {
		fmt.Println("No phone numbers available")
		return
	}
	number := numbers.Numbers[0]
	var buyData url.Values
	buyData.Set("PhoneNumber", string(number.PhoneNumber))
	boughtNumber, _ := client.IncomingNumbers.Create(ctx, buyData)
	fmt.Println("bought number!", boughtNumber.PhoneNumber)
}
Output:

Example (Wireless)
package main

import (
	"context"
	"fmt"

	twilio "github.com/kevinburke/twilio-go"
)

func main() {
	client := twilio.NewClient("AC123", "123", nil)
	sim, _ := client.Wireless.Sims.Get(context.TODO(), "DE123")
	fmt.Println(sim.Status)
}
Output:

Index

Examples

Constants

View Source
const (
	TypeGCM = CredentialType("gcm")
	TypeFCM = CredentialType("fcm")
	TypeAPN = CredentialType("apn")
)

Credential type. Currently APNS, FCM and GCM types are supported. https://www.twilio.com/docs/api/notify/rest/credentials

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 EventsPathPart = "Events"
View Source
const FaxVersion = "v1"
View Source
const InsightsVersion = "v1"
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 LookupBaseURL = "https://lookups.twilio.com"

Lookup service

View Source
const LookupVersion = "v1"
View Source
const MetricsPathPart = "Metrics"
View Source
const MonitorVersion = "v1"

Version of the Twilio Monitor API.

View Source
const NotifyBaseURL = "https://notify.twilio.com"
View Source
const NotifyVersion = "v1"
View Source
const PricingVersion = "v2"

Version of the Twilio Pricing API.

View Source
const RoomType = "group"

types of video room

View Source
const RoomTypePeerToPeer = "peer-to-peer"
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")
View Source
const StatusInProgress = Status("in-progress")
View Source
const StatusNoAnswer = Status("no-answer")
View Source
const StatusProcessing = Status("processing")
View Source
const StatusQueued = Status("queued")
View Source
const StatusRead = Status("read")
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 SummaryPathPart = "Summary"
View Source
const TaskQueuePathPart = "TaskQueues"
View Source
const TaskRouterVersion = "v1"
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 VerifyBaseURL = "https://verify.twilio.com"

Verify service

View Source
const VerifyVersion = "v2"
View Source
const Version = "2.5"

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

View Source
const VideoVersion = "v1"
View Source
const WirelessVersion = "v1"

Version of the Twilio Wireless API.

View Source
const WorkersPathPart = "Workers"
View Source
const WorkflowPathPart = "Workflows"

Variables

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

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

View Source
var DefaultRegion = "US"

DefaultRegion is the region used to parse phone numbers without a leading international prefix.

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 FaxBaseURL = "https://fax.twilio.com"
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 InsightsBaseUrl = "https://insights.twilio.com"

Voice Insights service

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.

View Source
var TaskRouterBaseUrl = "https://taskrouter.twilio.com"
View Source
var VideoBaseUrl = "https://video.twilio.com"

Video service

View Source
var WirelessBaseURL = "https://wireless.twilio.com"

The base URL for Twilio Wireless.

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 Activity

type Activity struct {
	Sid          string     `json:"sid"`
	AccountSid   string     `json:"account_sid"`
	FriendlyName string     `json:"friendly_name"`
	Available    bool       `json:"available"`
	DateCreated  TwilioTime `json:"date_created"`
	DateUpdated  TwilioTime `json:"date_updated"`
	URL          string     `json:"url"`
	WorkspaceSid string     `json:"workspace_sid"`
}

type ActivityPage

type ActivityPage struct {
	Page
	Activities []*Activity `json:"activities"`
}

type ActivityPageIterator

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

func (*ActivityPageIterator) Next

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

type ActivityService

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

func (*ActivityService) Create

func (r *ActivityService) Create(ctx context.Context, data url.Values) (*Activity, error)

Create creates a new Activity.

For a list of valid parameters see https://www.twilio.com/docs/taskrouter/api/activities#action-create.

func (*ActivityService) Delete

func (r *ActivityService) Delete(ctx context.Context, sid string) error

Delete deletes an Activity.

See https://www.twilio.com/docs/taskrouter/api/activities#action-delete for more.

func (*ActivityService) Get

func (r *ActivityService) Get(ctx context.Context, sid string) (*Activity, error)

Get retrieves an Activity by its sid.

See https://www.twilio.com/docs/taskrouter/api/activities#action-get for more.

func (*ActivityService) GetPage

func (ins *ActivityService) GetPage(ctx context.Context, data url.Values) (*ActivityPage, error)

GetPage retrieves an ActivityPage, filtered by the given data.

func (*ActivityService) GetPageIterator

func (c *ActivityService) GetPageIterator(data url.Values) *ActivityPageIterator

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

func (*ActivityService) Update

func (ipn *ActivityService) Update(ctx context.Context, sid string, data url.Values) (*Activity, error)

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"`
}

Alert represents a single Twilio Alert.

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"`
}

AlertPage represents a page of 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)

Get finds a single Alert resource by its sid, or returns an 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 (
	"context"
	"fmt"
	"log"
	"net/url"

	twilio "github.com/kevinburke/twilio-go"
)

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 AllDataUsage

type AllDataUsage struct {
	// TODO: ugh, naming
	DataUsage
	Home                 *DataUsage   `json:"home"`
	InternationalRoaming []*DataUsage `json:"international_roaming"`
	NationalRoaming      *DataUsage   `json:"national_roaming"`
}

func (*AllDataUsage) UnmarshalJSON

func (d *AllDataUsage) UnmarshalJSON(data []byte) error

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 AvailableNumber

type AvailableNumber struct {
	FriendlyName        string            `json:"friendly_name"`
	PhoneNumber         PhoneNumber       `json:"phone_number"`
	Lata                string            `json:"lata"`
	RateCenter          string            `json:"rate_center"`
	Latitude            string            `json:"latitude"`
	Longitude           string            `json:"longitude"`
	Region              string            `json:"region"`
	PostalCode          string            `json:"postal_code"`
	ISOCountry          string            `json:"iso_country"`
	Capabilities        *NumberCapability `json:"capabilities"`
	AddressRequirements string            `json:"address_requirements"`
	Beta                bool              `json:"beta"`
}

The subresources of the AvailableNumbers resource let you search for local, toll-free and mobile phone numbers that are available for you to purchase. See https://www.twilio.com/docs/api/rest/available-phone-numbers for details

type AvailableNumberBase

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

func (*AvailableNumberBase) GetPage

func (s *AvailableNumberBase) GetPage(ctx context.Context, isoCountry string, filters url.Values) (*AvailableNumberPage, error)

GetPage returns a page of available phone numbers.

For more information, see the Twilio documentation: https://www.twilio.com/docs/api/rest/available-phone-numbers#local https://www.twilio.com/docs/api/rest/available-phone-numbers#toll-free https://www.twilio.com/docs/api/rest/available-phone-numbers#mobile

type AvailableNumberPage

type AvailableNumberPage struct {
	URI     string             `json:"uri"`
	Numbers []*AvailableNumber `json:"available_phone_numbers"`
}

type AvailableNumberService

type AvailableNumberService struct {
	Local              *AvailableNumberBase
	Mobile             *AvailableNumberBase
	TollFree           *AvailableNumberBase
	SupportedCountries *SupportedCountriesService
}

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"`
	QueueTime      TwilioDurationMs `json:"queue_time"`
	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 CallEvent

type CallEvent struct {
	AccountSid string     `json:"account_sid"`
	CallSid    string     `json:"call_sid"`
	Edge       string     `json:"edge"`
	Group      string     `json:"group"`
	Level      string     `json:"level"`
	Name       string     `json:"name"`
	Timestamp  TwilioTime `json:"timestamp"`
}

type CallEventsPage

type CallEventsPage struct {
	Meta   Meta        `json:"meta"`
	Events []CallEvent `json:"events"`
}

type CallEventsPageIterator

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

func (*CallEventsPageIterator) Next

type CallEventsService

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

func (*CallEventsService) GetPage

func (s *CallEventsService) GetPage(ctx context.Context, data url.Values) (*CallEventsPage, error)

Returns a list of events for a call. For more information on valid values, See https://www.twilio.com/docs/voice/insights/api/call-events-resource#get-call-events

func (*CallEventsService) GetPageIterator

func (s *CallEventsService) GetPageIterator(data url.Values) *CallEventsPageIterator

type CallMetric

type CallMetric struct {
	AccountSid  string       `json:"account_sid"`
	CallSid     string       `json:"call_sid"`
	CarrierEdge *EdgeMetrics `json:"carrier_edge,omitempty"`
	ClientEdge  *EdgeMetrics `json:"client_edge,omitempty"`
	Direction   string       `json:"direction"`
	Edge        string       `json:"edge"`
	SDKEdge     *EdgeMetrics `json:"sdk_edge,omitempty"`
	SIPEdge     *EdgeMetrics `json:"sip_edge,omitempty"`
	Timestamp   TwilioTime   `json:"timestamp"`
}

type CallMetricsPage

type CallMetricsPage struct {
	Metrics []CallMetric `json:"metrics"`
	Meta    Meta         `json:"meta"`
}

type CallMetricsPageIterator

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

func (*CallMetricsPageIterator) Next

type CallMetricsService

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

func (*CallMetricsService) GetPage

func (s *CallMetricsService) GetPage(ctx context.Context, data url.Values) (*CallMetricsPage, error)

Returns a list of metrics for a call. For more information on valid values, See https://www.twilio.com/docs/voice/insights/api/call-metrics-resource#get-call-metrics

func (*CallMetricsService) GetPageIterator

func (s *CallMetricsService) GetPageIterator(data url.Values) *CallMetricsPageIterator

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 CallParty

type CallParty struct {
	Callee             string `json:"callee"`
	Caller             string `json:"caller"`
	Carrier            string `json:"carrier"`
	Connection         string `json:"connection"`
	CountryCode        string `json:"country_code"`
	CountrySubdivision string `json:"country_subdivision"`
	City               string `json:"city"`
	Location           struct {
		Lat float64 `json:"lat"`
		Lon float64 `json:"lon"`
	} `json:"location"`
	IPAddress    string `json:"ip_address"`
	NumberPrefix string `json:"number_prefix"`
}

type CallProperties

type CallProperties struct {
	Direction          Direction `json:"direction"`
	DisconnectedBy     string    `json:"disconnected_by"`
	PostDialDelayMs    int       `json:"pdd_ms"`
	LastSIPResponseNum int       `json:"last_sip_response_num"`
}

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 (
	"context"
	"fmt"
	"log"
	"net/url"
	"time"

	twilio "github.com/kevinburke/twilio-go"
)

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.TODO(), 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 CallSummary

type CallSummary struct {
	AccountSid      string                `json:"account_sid"`
	Attributes      CallSummaryAttributes `json:"attributes"`
	CallSid         string                `json:"call_sid"`
	CallState       Status                `json:"call_state"`
	CallType        string                `json:"call_type"`
	CarrierEdge     *Edge                 `json:"carrier_edge,omitempty"`
	ClientEdge      *Edge                 `json:"client_edge,omitempty"`
	ConnectDuration int                   `json:"connect_duration"`
	Duration        int                   `json:"duration"`
	EndTime         TwilioTime            `json:"end_time"`
	From            CallParty             `json:"from"`
	ProcessingState string                `json:"processing_state"`
	Properties      CallProperties        `json:"properties"`
	SDKEdge         *SDKEdge              `json:"sdk_edge,omitempty"`
	SIPEdge         *Edge                 `json:"sip_edge,omitempty"`
	StartTime       TwilioTime            `json:"start_time"`
	Tags            []string              `json:"tags"`
	To              CallParty             `json:"to"`
	URL             string                `json:"url"`
}

type CallSummaryAttributes

type CallSummaryAttributes struct {
	ConferenceParticipant bool `json:"conference_participant"`
}

type CallSummaryService

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

func (*CallSummaryService) Get

Gets a call summary resource from the Voice Insights API. See https://www.twilio.com/docs/voice/insights/api/call-summary-resource#get-call-summary

func (*CallSummaryService) GetPartial

func (s *CallSummaryService) GetPartial(ctx context.Context) (*CallSummary, error)

Gets a partial call summary resource from the Voice Insights API. A completed call summary may take up to a half hour to generate, but a partial summary record will be available within ten minutes of a call ending. See https://www.twilio.com/docs/voice/insights/api/call-summary-resource#get-call-summary

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 CallerLookup

type CallerLookup struct {
	CallerName string `json:"caller_name"`
	CallerType string `json:"caller_type"`
	ErrorCode  int    `json:"error_code"`
}

type CarrierLookup

type CarrierLookup struct {
	Type              string `json:"type"`
	ErrorCode         int    `json:"error_code"`
	MobileNetworkCode string `json:"mobile_network_code"`
	MobileCountryCode string `json:"mobile_country_code"`
	Name              string `json:"name"`
}

type CheckPhoneNumber

type CheckPhoneNumber struct {
	Sid         string           `json:"sid"`
	ServiceSid  string           `json:"service_sid"`
	AccountSid  string           `json:"account_sid"`
	To          string           `json:"to"`
	Channel     string           `json:"channel"`
	Status      string           `json:"status"`
	Valid       bool             `json:"valid"`
	Amount      types.NullString `json:"amount"`
	Payee       types.NullString `json:"payee"`
	DateCreated TwilioTime       `json:"date_created"`
	DateUpdated TwilioTime       `json:"date_updated"`
}

type Client

type Client struct {
	*restclient.Client
	Monitor    *Client
	Pricing    *Client
	Fax        *Client
	Wireless   *Client
	Notify     *Client
	Lookup     *Client
	Verify     *Client
	Video      *Client
	TaskRouter *Client
	Insights   *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
	AvailableNumbers  *AvailableNumberService

	// NewMonitorClient initializes these services
	Alerts *AlertService

	// NewPricingClient initializes these services
	Voice        *VoicePriceService
	Messaging    *MessagingPriceService
	PhoneNumbers *PhoneNumberPriceService

	// NewFaxClient initializes these services
	Faxes *FaxService

	// NewWirelessClient initializes these services
	Sims     *SimService
	Commands *CommandService

	// NewNotifyClient initializes these services
	Credentials *NotifyCredentialsService

	// NewLookupClient initializes these services
	LookupPhoneNumbers *LookupPhoneNumbersService

	// NewVerifyClient initializes these services
	Verifications *VerifyPhoneNumberService

	// NewVideoClient initializes these services
	Rooms           *RoomService
	VideoRecordings *VideoRecordingService

	// NewTaskRouterClient initializes these services
	Workspace func(sid string) *WorkspaceService

	// NewInsightsClient initializes these services
	VoiceInsights func(sid string) *VoiceInsightsService
}

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 NewFaxClient

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

NewFaxClient returns a Client for use with the Twilio Fax API.

func NewInsightsClient

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

func NewLookupClient

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

NewLookupClient returns a new Client to use the lookups API

func NewMonitorClient

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

NewMonitorClient returns a Client for use with the Twilio Monitor API.

func NewNotifyClient

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

func NewPricingClient

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

NewPricingClient returns a new Client to use the pricing API

func NewTaskRouterClient

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

NewTaskRouterClient returns a Client for use with the Twilio TaskRouter API.

Example
package main

import (
	"context"
	"net/url"

	twilio "github.com/kevinburke/twilio-go"
)

func main() {
	client := twilio.NewTaskRouterClient("AC123", "123", nil)
	data := url.Values{"FriendlyName": []string{"On Call"}}
	client.Workspace("WS123").Activities.Create(context.TODO(), data)
}
Output:

func NewVerifyClient

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

NewVerifyClient returns a new Client to use the verify API

func NewVideoClient

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

NewVideoClient returns a new Client to use the video API

func NewWirelessClient

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

NewWirelessClient returns a Client for use with the Twilio Wireless 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 - the newer API's do not include the account sid in the URI.

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

func (*Client) UseSecretKey

func (c *Client) UseSecretKey(key string)

UseSecretKey will use the provided secret key to authenticate to the API (instead of the AccountSid).

For more information about secret keys, see https://www.twilio.com/docs/api/rest/keys.

Example
package main

import (
	twilio "github.com/kevinburke/twilio-go"
)

func main() {
	client := twilio.NewClient("AC123", "123", nil)
	client.UseSecretKey("SK123")
	client.Messages.SendMessage("123", "456", "Sending with secret key...", nil)
}
Output:

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 Command

type Command struct {
	Sid       string    `json:"sid"`
	SimSid    string    `json:"sim_sid"`
	Command   string    `json:"command"`
	Direction Direction `json:"direction"`
	// A string representing which mode to send the SMS message using.
	// May be "text" or "binary". If omitted, the default SMS mode is text.
	CommandMode string `json:"command_mode"`
	Status      Status `json:"status"`

	DateCreated TwilioTime `json:"date_created"`
	DateUpdated TwilioTime `json:"date_updated"`
	AccountSid  string     `json:"account_sid"`
	URL         string     `json:"url"`
}

Command represents a Command resource.

type CommandPage

type CommandPage struct {
	Meta     Meta       `json:"meta"`
	Commands []*Command `json:"commands"`
}

CommandPage represents a page of Commands.

type CommandPageIterator

type CommandPageIterator interface {
	// Next returns the next page of resources. If there are no more resources,
	// NoMoreResults is returned.
	Next(context.Context) (*CommandPage, error)
}

type CommandService

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

func (*CommandService) Create

func (c *CommandService) Create(ctx context.Context, data url.Values) (*Command, error)

Create a new command. Command creation is asynchronous.

func (*CommandService) Get

func (c *CommandService) Get(ctx context.Context, sid string) (*Command, error)

func (*CommandService) GetPage

func (f *CommandService) GetPage(ctx context.Context, data url.Values) (*CommandPage, error)

GetPage returns a single Page of resources, filtered by data.

See https://www.twilio.com/docs/api/wireless/rest-api/command#list-get

func (*CommandService) GetPageIterator

func (f *CommandService) GetPageIterator(data url.Values) CommandPageIterator

GetPageIterator returns a CommandPageIterator with the given page filters. Call iterator.Next() to get the first page of resources (and again to retrieve subsequent pages).

func (*CommandService) Send

func (c *CommandService) Send(ctx context.Context, sid string, text string) (*Command, error)

Send a command to a device identified by sid. This is a wrapper around Create(); to provide optional parameters, use Create directly.

type CommandUsage

type CommandUsage struct {
	FromSim uint64 `json:"from_sim"`
	ToSim   uint64 `json:"to_sim"`
	Total   uint64 `json:"total"`
}

type CommandsUsage

type CommandsUsage struct {
	CommandUsage
	Home                 *CommandUsage   `json:"home"`
	InternationalRoaming []*CommandUsage `json:"international_roaming"`
	NationalRoaming      *CommandUsage   `json:"national_roaming"`
}

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"`
	SubresourceURIs         map[string]string `json:"subresource_uris"`
	CallSidEndingConference types.NullString  `json:"call_sid_ending_conference"`
}

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, data url.Values) (*MessagePrices, 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, data url.Values) (*NumberPrices, 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, data url.Values) (*VoicePrices, error)

https://www.twilio.com/docs/voice/pricing#pricing-voice-country-instance-resource 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 CredentialType

type CredentialType string

type CumulativeMetrics

type CumulativeMetrics struct {
	Jitter          MetricsSummary `json:"jitter"`
	PacketsReceived int            `json:"packets_received"`
	PacketsLost     int            `json:"packets_lost"`
}

type DataUsage

type DataUsage struct {
	Download types.Bits `json:"download"`
	Total    types.Bits `json:"total"`
	Upload   types.Bits `json:"upload"`
	Units    string     `json:"units"`
}

func (*DataUsage) UnmarshalJSON

func (d *DataUsage) UnmarshalJSON(data []byte) error

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 Edge

type Edge struct {
	Metrics struct {
		Inbound  EdgeSummary `json:"inbound"`
		Outbound EdgeSummary `json:"outbound"`
	} `json:"metrics"`
	Properties EdgeProperties `json:"properties"`
}

type EdgeMetadata

type EdgeMetadata struct {
	Region     string `json:"region"`
	ExternalIP string `json:"external_ip"`
	TwilioIP   string `json:"twilio_ip"`
}

type EdgeMetrics

type EdgeMetrics struct {
	Codec      int               `json:"codec"`
	CodecName  string            `json:"codec_name"`
	Cumulative CumulativeMetrics `json:"cumulative"`
	Interval   *IntervalMetrics  `json:"interval,omitempty"`
	Metadata   EdgeMetadata      `json:"metadata"`
}

type EdgeProperties

type EdgeProperties struct {
	Direction           string `json:"direction"`
	MediaRegion         string `json:"media_region"`
	SignalingRegion     string `json:"signaling_region"`
	TwilioMediaIP       string `json:"twilio_media_ip"`
	TwilioSignalingIP   string `json:"twilio_signaling_ip"`
	ExternalMediaIP     string `json:"external_media_ip"`
	ExternalSignalingIP string `json:"external_signaling_ip"`
	SIPCallID           string `json:"sip_call_id"`
	UserAgent           string `json:"user_agent"`
	SelectedRegion      string `json:"selected_region"`
	Region              string `json:"region"`
	DisconnectedBy      string `json:"disconnected_by"`
	TrunkSID            string `json:"trunk_sid"`
}

type EdgeSummary

type EdgeSummary struct {
	Codec                 int            `json:"codec"`
	CodecName             string         `json:"codec_name"`
	PacketsReceived       int            `json:"packets_received"`
	PacketsSent           int            `json:"packets_sent"`
	PacketsLost           int            `json:"packets_lost"`
	PacketsLossPercentage float64        `json:"packets_loss_percentage"`
	Jitter                MetricsSummary `json:"jitter"`
	Latency               MetricsSummary `json:"latency"`
	PacketDelayVariation  map[string]int `json:"packet_delay_variation"`
}

type Fax

type Fax struct {
	Sid         string      `json:"sid"`
	AccountSid  string      `json:"account_sid"`
	From        PhoneNumber `json:"from"`
	To          PhoneNumber `json:"to"`
	Direction   Direction   `json:"direction"`
	NumPages    uint        `json:"num_pages"`
	Duration    uint        `json:"duration"`
	MediaURL    string      `json:"media_url"`
	Status      Status      `json:"status"`
	DateCreated TwilioTime  `json:"date_created"`
	DateUpdated TwilioTime  `json:"date_updated"`
	Price       string      `json:"price"`
	PriceUnit   string      `json:"price_unit"`
	Quality     string      `json:"quality"`
	URL         string      `json:"url"`
	APIVersion  string      `json:"api_version"`
}
Example
package main

import (
	"context"
	"fmt"

	twilio "github.com/kevinburke/twilio-go"
)

func main() {
	faxer := twilio.NewFaxClient("AC123", "123", nil)
	fax, _ := faxer.Faxes.Get(context.TODO(), "FX123")
	fmt.Print(fax.Sid)
}
Output:

func (*Fax) FriendlyPrice

func (f *Fax) 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 FaxPage

type FaxPage struct {
	Meta  Meta   `json:"meta"`
	Faxes []*Fax `json:"faxes"`
}

FaxPage represents a page of Faxes.

type FaxPageIterator

type FaxPageIterator interface {
	// Next returns the next page of resources. If there are no more resources,
	// NoMoreResults is returned.
	Next(context.Context) (*FaxPage, error)
}

FaxPageIterator lets you retrieve consecutive pages of resources.

type FaxService

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

func (*FaxService) Cancel

func (f *FaxService) Cancel(sid string) (*Fax, error)

Cancel an in-progress Fax with the given sid. Cancel will not affect in-progress Faxes, only those in queued or in-progress.

Example
package main

import (
	twilio "github.com/kevinburke/twilio-go"
)

func main() {
	faxer := twilio.NewFaxClient("AC123", "123", nil)
	faxer.Faxes.Cancel("FX123")
}
Output:

func (*FaxService) Create

func (f *FaxService) Create(ctx context.Context, data url.Values) (*Fax, error)

Create a fax with the given url.Values. For more information on valid values, see https://www.twilio.com/docs/api/fax/rest/faxes#fax-list-post or use the SendFax helper.

func (*FaxService) Get

func (f *FaxService) Get(ctx context.Context, sid string) (*Fax, error)

Get finds a single Fax resource by its sid, or returns an error.

func (*FaxService) GetPage

func (f *FaxService) GetPage(ctx context.Context, data url.Values) (*FaxPage, error)

GetPage returns a single Page of resources, filtered by data.

See https://www.twilio.com/docs/api/fax/rest/faxes#fax-list-get.

func (*FaxService) GetPageIterator

func (f *FaxService) GetPageIterator(data url.Values) FaxPageIterator

GetPageIterator returns a FaxPageIterator with the given page filters. Call iterator.Next() to get the first page of resources (and again to retrieve subsequent pages).

func (*FaxService) SendFax

func (f *FaxService) SendFax(from string, to string, mediaURL *url.URL) (*Fax, error)

SendFax sends an outbound Fax with the given mediaURL. For more control over the parameters, use FaxService.Create.

Example
package main

import (
	"net/url"

	twilio "github.com/kevinburke/twilio-go"
)

var pdfURL, _ = url.Parse("https://kev.inburke.com/foo.pdf")

func main() {
	faxer := twilio.NewFaxClient("AC123", "123", nil)
	faxer.Faxes.SendFax("123", "456", pdfURL)
}
Output:

func (*FaxService) Update

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

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

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.

func (*IncomingNumberService) Update

Tries to update the incoming phone number's properties, and returns the updated resource representation if successful. https://www.twilio.com/docs/api/rest/incoming-phone-numbers#instance-post

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 IntervalMetrics

type IntervalMetrics struct {
	AudioOut              int     `json:"audio_out"`
	AudioIn               int     `json:"audio_in"`
	Jitter                int     `json:"jitter"`
	RTT                   int     `json:"rtt"`
	PacketsLost           int     `json:"packets_lost"`
	PacketsLossPercentage float64 `json:"packets_loss_percentage"`
}

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 LookupPhoneNumbersService

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

func (*LookupPhoneNumbersService) Get

Get calls the lookups API to retrieve information about a phone number

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 MessagePrices

type MessagePrices 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) Delete

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

Delete the Message with the given sid. If the Message has already been deleted, or does not exist, Delete returns nil. If another error or a timeout occurs, the error is returned.

func (*MessageService) Get

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

import (
	"context"
	"fmt"

	twilio "github.com/kevinburke/twilio-go"
)

func main() {
	client := twilio.NewClient("AC123", "123", nil)
	message, _ := client.Messages.Get(context.TODO(), "SM123")
	fmt.Println(message.Status)
}
Output:

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 (
	"context"
	"fmt"
	"log"
	"net/url"
	"time"

	twilio "github.com/kevinburke/twilio-go"
)

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 sends an outbound Message with the given body or mediaURLs.

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 MetricsSummary

type MetricsSummary struct {
	Max float64 `json:"max"`
	Avg float64 `json:"avg"`
	Min float64 `json:"min"`
}

type NotifyCredential

type NotifyCredential struct {
	Sid          string         `json:"sid"`
	FriendlyName string         `json:"friendly_name"`
	AccountSid   string         `json:"account_sid"`
	Type         CredentialType `json:"type"`
	DateCreated  TwilioTime     `json:"date_created"`
	DateUpdated  TwilioTime     `json:"date_updated"`
	URL          string         `json:"url"`
}

type NotifyCredentialPage

type NotifyCredentialPage struct {
	Page
	Credentials []*NotifyCredential `json:"credentials"`
}

type NotifyCredentialPageIterator

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

func (*NotifyCredentialPageIterator) Next

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

type NotifyCredentialsService

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

func (*NotifyCredentialsService) Create

func (*NotifyCredentialsService) CreateAPN

func (n *NotifyCredentialsService) CreateAPN(ctx context.Context, friendlyName string, cert string, privateKey string, sandbox bool) (*NotifyCredential, error)

func (*NotifyCredentialsService) CreateFCM

func (n *NotifyCredentialsService) CreateFCM(ctx context.Context, friendlyName string, secret string) (*NotifyCredential, error)

To create an FCM credential, use Secret parameter, which can be found in your Firebase console as Server key See https://www.twilio.com/docs/api/notify/rest/credentials#create-a-credential for details

func (*NotifyCredentialsService) CreateGCM

func (n *NotifyCredentialsService) CreateGCM(ctx context.Context, friendlyName string, apiKey string) (*NotifyCredential, error)

func (*NotifyCredentialsService) Delete

func (n *NotifyCredentialsService) Delete(ctx context.Context, sid string) error

func (*NotifyCredentialsService) Get

func (*NotifyCredentialsService) GetPage

func (*NotifyCredentialsService) GetPageIterator

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

func (*NotifyCredentialsService) Update

type NotifyService

type NotifyService struct {
	Credentials *NotifyCredentialsService
}

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 NumberPrices

type NumberPrices 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

func (nvps *NumberVoicePriceService) Get(ctx context.Context, destinationNumber string, data url.Values) (*VoiceNumberPrices, error)

https://www.twilio.com/docs/voice/pricing#list-uri-by-origination-number returns the call price by number or numbers pair

type OutboundCallPrice

type OutboundCallPrice struct {
	BasePrice           string   `json:"base_price"`
	CurrentPrice        string   `json:"current_price"`
	OriginationPrefixes []string `json:"origination_prefixes"`
}

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{}

type PhoneLookup

type PhoneLookup struct {
	CountryCode    string        `json:"country_code"`
	PhoneNumber    string        `json:"phone_number"`
	NationalFormat string        `json:"national_format"`
	URL            string        `json:"url"`
	CallerName     CallerLookup  `json:"caller_name"`
	Carrier        CarrierLookup `json:"carrier"`
}

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 national number in the region specified by DefaultRegion. 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"`
	DestinationPrefixes []string `json:"destination_prefixes"`
	OriginationPrefixes []string `json:"origination_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 Room

type Room struct {
	Sid                         string            `json:"sid"`
	AccountSid                  string            `json:"account_sid"`
	Type                        string            `json:"type"`
	EnableTurn                  bool              `json:"enable_turn"`
	UniqueName                  string            `json:"unique_name"`
	StatusCallback              string            `json:"status_callback"`
	StatusCallbackMethod        string            `json:"status_callback_method"`
	MaxParticipants             uint              `json:"max_participants"`
	RecordParticipantsOnConnect bool              `json:"record_participants_on_connect"`
	Duration                    uint              `json:"duration"`
	MediaRegion                 string            `json:"media_region"`
	Status                      Status            `json:"status"`
	DateCreated                 TwilioTime        `json:"date_created"`
	DateUpdated                 TwilioTime        `json:"date_updated"`
	EndTime                     TwilioTime        `json:"end_time"`
	URL                         string            `json:"url"`
	Links                       map[string]string `json:"links"`
}

type RoomPage

type RoomPage struct {
	Meta  Meta    `json:"meta"`
	Rooms []*Room `json:"rooms"`
}

type RoomPageIterator

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

func (*RoomPageIterator) Next

func (r *RoomPageIterator) Next(ctx context.Context) (*RoomPage, error)

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

type RoomService

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

func (*RoomService) Complete

func (r *RoomService) Complete(sid string) (*Room, error)

Complete an in-progress Room with the given sid. All connected Participants will be immediately disconnected from the Room.

func (*RoomService) Create

func (r *RoomService) Create(ctx context.Context, data url.Values) (*Room, error)

Create a room with the given url.Values. For more information on valid values, see https://www.twilio.com/docs/api/video/rooms-resource#post-parameters or use the

func (*RoomService) Get

func (r *RoomService) Get(ctx context.Context, sidOrUniqueName string) (*Room, error)

Get finds a single Room resource by its sid or unique name, or returns an error.

func (*RoomService) GetPage

func (r *RoomService) GetPage(ctx context.Context, data url.Values) (*RoomPage, error)

Returns a list of rooms. For more information on valid values, see https://www.twilio.com/docs/api/video/rooms-resource#get-list-resource

func (*RoomService) GetPageIterator

func (r *RoomService) GetPageIterator(data url.Values) *RoomPageIterator

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

type SDKEdge

type SDKEdge struct {
	Metrics struct {
		Inbound  SDKEdgeSummary `json:"inbound"`
		Outbound SDKEdgeSummary `json:"outbound"`
	} `json:"metrics"`
	Properties SDKEdgeProperties `json:"properties"`
	Events     SDKEdgeEvents     `json:"events"`
}

type SDKEdgeEvents

type SDKEdgeEvents struct {
	Levels map[string]int `json:"levels"`
	Groups map[string]int `json:"groups"`
	Errors map[string]int `json:"errors"`
}

type SDKEdgeProperties

type SDKEdgeProperties struct {
	Direction string `json:"direction"`
	Settings  struct {
		DSCP              bool     `json:"dscp"`
		ICERestartEnabled bool     `json:"ice_restart_enabled"`
		Edge              string   `json:"edge"`
		SelectedEdges     []string `json:"selected_edges"`
	} `json:"settings"`
}

type SDKEdgeSummary

type SDKEdgeSummary struct {
	EdgeSummary
	MOS      MetricsSummary `json:"mos"`
	RTT      MetricsSummary `json:"rtt"`
	Tags     []string       `json:"tags"`
	AudioOut MetricsSummary `json:"audio_out"`
	AudioIn  MetricsSummary `json:"audio_in"`
}

type Segments

type Segments uintStr

func (*Segments) UnmarshalJSON

func (seg *Segments) UnmarshalJSON(b []byte) (err error)

type Sim

type Sim struct {
	Sid          string           `json:"sid"`
	UniqueName   string           `json:"unique_name"`
	Status       Status           `json:"status"`
	FriendlyName types.NullString `json:"friendly_name"`
	ICCID        string           `json:"iccid"`

	CommandsCallbackMethod string           `json:"commands_callback_method"`
	CommandsCallbackURL    types.NullString `json:"commands_callback_url"`
	DateCreated            TwilioTime       `json:"date_created"`
	DateUpdated            TwilioTime       `json:"date_updated"`
	RatePlanSid            string           `json:"rate_plan_sid"`
	SMSURL                 types.NullString `json:"sms_url"`
	SMSMethod              types.NullString `json:"sms_method"`
	SMSFallbackMethod      types.NullString `json:"sms_fallback_method"`
	SMSFallbackURL         types.NullString `json:"sms_fallback_url"`
	VoiceURL               types.NullString `json:"voice_url"`
	VoiceMethod            types.NullString `json:"voice_method"`
	VoiceFallbackMethod    types.NullString `json:"voice_fallback_method"`
	VoiceFallbackURL       types.NullString `json:"voice_fallback_url"`

	URL        string            `json:"url"`
	AccountSid string            `json:"account_sid"`
	Links      map[string]string `json:"links"`
}

Sim represents a Sim resource.

type SimPage

type SimPage struct {
	Meta Meta   `json:"meta"`
	Sims []*Sim `json:"sims"`
}

SimPage represents a page of Sims.

type SimPageIterator

type SimPageIterator interface {
	// Next returns the next page of resources. If there are no more resources,
	// NoMoreResults is returned.
	Next(context.Context) (*SimPage, error)
}

SimPageIterator lets you retrieve consecutive pages of resources.

type SimService

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

func (*SimService) Get

func (s *SimService) Get(ctx context.Context, sid string) (*Sim, error)

Get finds a single Sim resource by its sid, or returns an error.

func (*SimService) GetPage

func (f *SimService) GetPage(ctx context.Context, data url.Values) (*SimPage, error)

GetPage returns a single Page of resources, filtered by data.

See https://www.twilio.com/docs/api/wireless/rest-api/sim#list-get.

func (*SimService) GetPageIterator

func (f *SimService) GetPageIterator(data url.Values) SimPageIterator

GetPageIterator returns a SimPageIterator with the given page filters. Call iterator.Next() to get the first page of resources (and again to retrieve subsequent pages).

func (*SimService) GetUsageRecords

func (s *SimService) GetUsageRecords(ctx context.Context, simSid string, data url.Values) (*SimUsageRecordPage, error)

GetUsageRecords finds a page of UsageRecord resources.

func (*SimService) GetUsageRecordsIterator

func (s *SimService) GetUsageRecordsIterator(simSid string, data url.Values) SimUsageRecordPageIterator

func (*SimService) Update

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

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

type SimUsageRecord

type SimUsageRecord struct {
	AccountSid string        `json:"account_sid"`
	Commands   CommandsUsage `json:"commands"`
	Data       AllDataUsage  `json:"data"`
	Period     UsagePeriod   `json:"period"`
	SimSid     string        `json:"sim_sid"`
}

type SimUsageRecordPage

type SimUsageRecordPage struct {
	Meta         Meta              `json:"meta"`
	UsageRecords []*SimUsageRecord `json:"usage_records"`
}

type SimUsageRecordPageIterator

type SimUsageRecordPageIterator interface {
	// Next returns the next page of resources. If there are no more resources,
	// NoMoreResults is returned.
	Next(context.Context) (*SimUsageRecordPage, error)
}

type Status

type Status string

The status of a resource ("accepted", "queued", etc). For more information, see

https://www.twilio.com/docs/api/rest/message https://www.twilio.com/docs/api/fax/rest/faxes#fax-status-values

func (Status) Friendly

func (s Status) Friendly() string

type SupportedCountries

type SupportedCountries struct {
	URI       string              `json:"uri"`
	Countries []*SupportedCountry `json:"countries"`
}

type SupportedCountriesService

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

func (*SupportedCountriesService) Get

Get returns supported countries. If beta is true, only include countries where phone numbers new to the Twilio platform are available. If false, do not include new inventory.

See https://www.twilio.com/docs/phone-numbers/api/available-phone-numbers#countries

type SupportedCountry

type SupportedCountry struct {
	// The ISO Country code to lookup phone numbers for.
	CountryCode string `json:"country_code"`
	Country     string `json:"country"`
	URI         string `json:"uri"`

	// If true, all phone numbers available in this country are new to the Twilio platform.
	// If false, all numbers are not in the Twilio Phone Number Beta program.
	Beta            bool              `json:"beta"`
	SubresourceURIs map[string]string `json:"subresource_uris"`
}

type TaskQueue

type TaskQueue struct {
	Sid                     string     `json:"sid"`
	AccountSid              string     `json:"account_sid"`
	FriendlyName            string     `json:"friendly_name"`
	AssignmentActivityName  string     `json:"assignment_activity_name"`
	AssignmentActivitySid   string     `json:"assignment_activity_sid"`
	ReservationActivityName string     `json:"reservation_activity_name"`
	ReservationActivitySid  string     `json:"reservation_activity_sid"`
	TargetWorkers           string     `json:"target_workers"`
	TaskOrder               string     `json:"task_order"`
	DateCreated             TwilioTime `json:"date_created"`
	DateUpdated             TwilioTime `json:"date_updated"`
	URL                     string     `json:"url"`
	WorkspaceSid            string     `json:"workspace_sid"`
	MaxReservedWorkers      int        `json:"max_reserved_workers"`
}

type TaskQueuePage

type TaskQueuePage struct {
	Page
	TaskQueues []*TaskQueue `json:"task_queues"`
}

type TaskQueuePageIterator

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

func (*TaskQueuePageIterator) Next

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

type TaskQueueService

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

func (*TaskQueueService) Create

func (r *TaskQueueService) Create(ctx context.Context, data url.Values) (*TaskQueue, error)

func (*TaskQueueService) Delete

func (r *TaskQueueService) Delete(ctx context.Context, sid string) error

func (*TaskQueueService) Get

func (r *TaskQueueService) Get(ctx context.Context, sid string) (*TaskQueue, error)

func (*TaskQueueService) GetPage

func (ins *TaskQueueService) GetPage(ctx context.Context, data url.Values) (*TaskQueuePage, error)

GetPage retrieves an TaskQueuePage, filtered by the given data.

func (*TaskQueueService) GetPageIterator

func (c *TaskQueueService) GetPageIterator(data url.Values) *TaskQueuePageIterator

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

func (*TaskQueueService) Update

func (ipn *TaskQueueService) Update(ctx context.Context, sid string, data url.Values) (*TaskQueue, error)

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 TwilioDurationMs

type TwilioDurationMs time.Duration

func (TwilioDurationMs) String

func (tdm TwilioDurationMs) String() string

func (*TwilioDurationMs) UnmarshalJSON

func (tdm *TwilioDurationMs) 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 UsagePeriod

type UsagePeriod struct {
	Start time.Time `json:"start"`
	End   time.Time `json:"end"`
}

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 VerifyPhoneNumber

type VerifyPhoneNumber struct {
	Sid         string           `json:"sid"`
	ServiceSid  string           `json:"service_sid"`
	AccountSid  string           `json:"account_sid"`
	To          PhoneNumber      `json:"to"`
	Channel     string           `json:"channel"`
	Status      string           `json:"status"`
	Valid       bool             `json:"valid"`
	Lookup      PhoneLookup      `json:"lookup"`
	Amount      types.NullString `json:"amount"`
	Payee       types.NullString `json:"payee"`
	DateCreated TwilioTime       `json:"date_created"`
	DateUpdated TwilioTime       `json:"date_updated"`
	URL         string           `json:"url"`
}

type VerifyPhoneNumberService

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

func (*VerifyPhoneNumberService) Check

func (v *VerifyPhoneNumberService) Check(ctx context.Context, verifyServiceID string, data url.Values) (*CheckPhoneNumber, error)

Check calls the Verify API to check if a user-provided token is correct. https://www.twilio.com/docs/verify/api-beta/verification-check-beta#check-a-verification-1

func (*VerifyPhoneNumberService) Create

func (v *VerifyPhoneNumberService) Create(ctx context.Context, verifyServiceID string, data url.Values) (*VerifyPhoneNumber, error)

Create calls the Verify API to start a new verification. https://www.twilio.com/docs/verify/api-beta/verification-beta#start-new-verification

func (*VerifyPhoneNumberService) Get

func (v *VerifyPhoneNumberService) Get(ctx context.Context, verifyServiceID string, sid string) (*VerifyPhoneNumber, error)

Get calls the Verify API to retrieve information about a verification. https://www.twilio.com/docs/verify/api-beta/verification-beta#fetch-a-verification-1

type VideoMedia

type VideoMedia struct {
	Location string `json:"location"`
}

type VideoRecording

type VideoRecording struct {
	Sid             string            `json:"sid"`
	Duration        uint              `json:"duration"`
	Status          Status            `json:"status"`
	DateCreated     TwilioTime        `json:"date_created"`
	SourceSid       string            `json:"source_sid"`
	URI             string            `json:"uri"`
	Size            uint              `json:"size"`
	Type            string            `json:"type"`
	ContainerFormat string            `json:"container_format"`
	Codec           string            `json:"codec"`
	GroupingSids    map[string]string `json:"grouping_sids"`
	Links           map[string]string `json:"links"`
}

type VideoRecordingPage

type VideoRecordingPage struct {
	Meta       Meta              `json:"meta"`
	Recordings []*VideoRecording `json:"recordings"`
}

type VideoRecordingPageIterator

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

func (*VideoRecordingPageIterator) Next

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

type VideoRecordingService

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

func (*VideoRecordingService) Delete

func (vr *VideoRecordingService) Delete(ctx context.Context, sid string) error

Delete the VideoRecording with the given sid. If the VideoRecording has already been deleted, or does not exist, Delete returns nil. If another error or a timeout occurs, the error is returned.

func (*VideoRecordingService) Get

Returns the VideoRecording with the given sid.

func (*VideoRecordingService) GetPage

Returns a list of recordings. For more information on valid values, see https://www.twilio.com/docs/api/video/recordings-resource#recordings-list-resource

func (*VideoRecordingService) GetPageIterator

func (vr *VideoRecordingService) GetPageIterator(data url.Values) *VideoRecordingPageIterator

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

func (*VideoRecordingService) Media

func (vr *VideoRecordingService) Media(ctx context.Context, sid string) (*VideoMedia, error)

When you make a request to this URL, Twilio will generate a temporary URL for accessing this binary data, and issue an HTTP 302 redirect response to your request. The Recording will be returned in the format as described in the metadata.

type VoiceInsightsService

type VoiceInsightsService struct {
	Summary *CallSummaryService
	Metrics *CallMetricsService
	Events  *CallEventsService
}

type VoiceNumberPrices

type VoiceNumberPrices struct {
	Country            string              `json:"country"`
	IsoCountry         string              `json:"iso_country"`
	DestinationNumber  string              `json:"destination_number"`
	OriginationNumber  string              `json:"origination_number"`
	InboundCallPrice   InboundPrice        `json:"inbound_call_price"`
	OutboundCallPrices []OutboundCallPrice `json:"outbound_call_prices"`
	PriceUnit          string              `json:"price_unit"`

	URL string `json:"url"`
}

type VoicePriceService

type VoicePriceService struct {
	Countries *CountryVoicePriceService
	Numbers   *NumberVoicePriceService
}

type VoicePrices

type VoicePrices 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 Worker

type Worker struct {
	Sid          string `json:"sid"`
	AccountSid   string `json:"account_sid"`
	FriendlyName string `json:"friendly_name"`
	// A string that contains JSON attributes, for example:
	// `{"type": "support"}`
	Attributes   string     `json:"attributes"`
	ActivityName string     `json:"activity_name"`
	ActivitySid  string     `json:"activity_sid"`
	Available    bool       `json:"available"`
	DateCreated  TwilioTime `json:"date_created"`
	DateUpdated  TwilioTime `json:"date_updated"`
	URL          string     `json:"url"`
	WorkspaceSid string     `json:"workspace_sid"`
}

type WorkerPage

type WorkerPage struct {
	Page
	Workers []*Worker `json:"workers"`
}

type WorkerPageIterator

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

func (*WorkerPageIterator) Next

type WorkerService

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

func (*WorkerService) Create

func (r *WorkerService) Create(ctx context.Context, data url.Values) (*Worker, error)

Create creates a new Worker.

For a list of valid parameters see https://www.twilio.com/docs/taskrouter/api/workers#action-create.

func (*WorkerService) Delete

func (r *WorkerService) Delete(ctx context.Context, sid string) error

Delete deletes a Worker.

See https://www.twilio.com/docs/taskrouter/api/workers#action-delete for more.

func (*WorkerService) Get

func (r *WorkerService) Get(ctx context.Context, sid string) (*Worker, error)

Get retrieves a Worker by its sid.

See https://www.twilio.com/docs/taskrouter/api/workers#action-get for more.

func (*WorkerService) GetPage

func (ins *WorkerService) GetPage(ctx context.Context, data url.Values) (*WorkerPage, error)

func (*WorkerService) GetPageIterator

func (c *WorkerService) GetPageIterator(data url.Values) *WorkerPageIterator

func (*WorkerService) Update

func (ipn *WorkerService) Update(ctx context.Context, sid string, data url.Values) (*Worker, error)

Update updates a Workers.

See https://www.twilio.com/docs/taskrouter/api/workers#update-a-worker for more.

type Workflow

type Workflow struct {
	Sid          string `json:"sid"`
	AccountSid   string `json:"account_sid"`
	FriendlyName string `json:"friendly_name"`
	// A string that contains JSON configuration, for example:
	//
	// `{"task_routing":{"default_filter":{
	//       "queue":"WQ0c1274082082355320d8a41f94eb57aa"
	//  }}}`
	Configuration                 string     `json:"configuration"`
	AssignmentCallbackURL         string     `json:"assignment_callback_url"`
	FallbackAssignmentCallbackURL string     `json:"fallback_assignment_callback_url"`
	TaskReservationTimeout        int        `json:"task_reservation_timeout"`
	DateCreated                   TwilioTime `json:"date_created"`
	DateUpdated                   TwilioTime `json:"date_updated"`
	URL                           string     `json:"url"`
	WorkspaceSid                  string     `json:"workspace_sid"`
}

type WorkflowPage

type WorkflowPage struct {
	Page
	Workflows []*Workflow `json:"workflows"`
}

type WorkflowPageIterator

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

func (*WorkflowPageIterator) Next

type WorkflowService

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

func (*WorkflowService) Create

func (r *WorkflowService) Create(ctx context.Context, data url.Values) (*Workflow, error)

Create creates a new Workflow.

For a list of valid parameters see https://www.twilio.com/docs/taskrouter/api/workflows#action-create.

func (*WorkflowService) Delete

func (r *WorkflowService) Delete(ctx context.Context, sid string) error

Delete deletes a Workflow.

See https://www.twilio.com/docs/taskrouter/api/workflows#action-delete for more.

func (*WorkflowService) Get

func (r *WorkflowService) Get(ctx context.Context, sid string) (*Workflow, error)

Get retrieves a Workflow by its sid.

See https://www.twilio.com/docs/taskrouter/api/workflows#action-get for more.

func (*WorkflowService) GetPage

func (ins *WorkflowService) GetPage(ctx context.Context, data url.Values) (*WorkflowPage, error)

func (*WorkflowService) GetPageIterator

func (c *WorkflowService) GetPageIterator(data url.Values) *WorkflowPageIterator

func (*WorkflowService) Update

func (ipn *WorkflowService) Update(ctx context.Context, sid string, data url.Values) (*Workflow, error)

List all Workflows.

See https://www.twilio.com/docs/taskrouter/api/workflows#action-list for more.

type WorkspaceService

type WorkspaceService struct {
	Activities *ActivityService
	Queues     *TaskQueueService
	Workflows  *WorkflowService
	Workers    *WorkerService
}

WorkspaceService lets you interact with a TaskRouter Workspace.

Directories

Path Synopsis
cmd
report-data-usage
Binary report-data-usage reports information about how much data your sim cards have used.
Binary report-data-usage reports information about how much data your sim cards have used.
report-data-usage-server
Binary report-data-usage-server sends info to your SIM about how much data has been used.
Binary report-data-usage-server sends info to your SIM about how much data has been used.
Package datausage has utilities for retrieving data usage from a SIM card.
Package datausage has utilities for retrieving data usage from a SIM card.
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