Twilio Go library

Overview

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: [email protected]

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 [email protected]. Donations are not tax deductible in the USA.

Comments
  • Updates key for conference sid

    Updates key for conference sid

    Hi, Today I found an issue that related to the conversation token. That issue happens when we try to send an access token with Video Grand to Twilio via client side. I have 2 decoded tokens:

    1. The token that generated in Twilio console.
    2. The token that generated in the package.

    Twilio version:

    "grants": {
        "identity": "1",
        "video": {
          "room": "1"
        }
     }
    

    Package version:

    "grants": {
        "identity": "1",
        "video": {
          "configuration_profile_sid": "1"
        }
    }
    

    So, Twilio version is valid.

    opened by oceanicdev 10
  • Implement lookup service (https://www.twilio.com/lookup)

    Implement lookup service (https://www.twilio.com/lookup)

    This PR implements the Lookup service: https://www.twilio.com/lookup Docs are here: https://www.twilio.com/docs/api/lookups

    Includes the implementation for the service together with some tests for it. I've added some entries to the .gitignore file to exclude Eclipse IDE garbage. Also fixed a test in messages_test.go that was panicking after a previous error.

    opened by leonelquinteros 8
  • Support for ApplicationSid parameter

    Support for ApplicationSid parameter

    Hi, as far as I can see there is not support for the ApplicationSid parameter (instead of using the Url) when making a call.

    If so, I can create a PR to include it because in our scenario we'd like to configure URLs and status callbacks using an app

    Thanks!

    opened by alecha 8
  • Support Go modules

    Support Go modules

    This adds support for Go modules. Because this package is already at version 2.4, we can't just directly add go.mod and go.sum; instead, we need to bump the version to 3.0.0 and namespace the module with /v3. Remember, Go modules require a /vN namespace for every version greater than 1. Because we're already midway through version 2, I think that the best course of action would be to introduce Go modules in a new major version.

    Once merged, this should be tagged as v3.0.0. If needed, subsequent work on the version 2 train should be done in a v2 branch made from the commit before this one.

    opened by tekkamanendless 4
  • Added TaskRouter Activity API

    Added TaskRouter Activity API

    This PR adds the TaskRouter activity API (https://www.twilio.com/docs/taskrouter/api/activities)

    I'm planning on also adding TaskQueues, Worker and Workflows but thought I'd start with Activity first as it's the easiest.

    This is also my first ever GoLang PR 🎉

    opened by joshhornby 4
  • Add Serverless Services + Functions API

    Add Serverless Services + Functions API

    Description

    Adds a few APIs from the Functions & Assets (API):

    • Service
    • Function
    • Function Version

    Notes

    • I followed the naming convention of the repo, but that resulted in a stuttering struct name ServiceService. Open to suggestions if that is an issue.

    Usage A combined example showing a chained use case:

    client := twilio.NewClient(sid, token, nil)
    maxPageSize := url.Values{"PageSize": []string{"50"}}
    iterator := client.Serverless.Services.GetPageIterator(maxPageSize)
    for {
    	page, err := iterator.Next(ctx)
    	if err == twilio.NoMoreResults {
    		break
    	}
    	for _, s := range page.Services {
    		fmt.Printf("service: %#v\n", s)
    		service := client.Serverless.Service(s.Sid)
    		funcIter := service.Functions.GetPageIterator(maxPageSize)
    		for {
    			fPage, err := funcIter.Next(ctx)
    			if err == twilio.NoMoreResults {
    				break
    			}
    			for _, f := range fPage.Functions {
    				fmt.Printf("function: %#v\n", f)
    				versions := service.Function(f.Sid).Versions
    				verIter := versions.GetPageIterator(maxPageSize)
    				for {
    					fvPage, err := verIter.Next(ctx)
    					if err == twilio.NoMoreResults {
    						break
    					}
    
    					latestVersion := fvPage.FunctionVersions[0]
    					fmt.Printf("latest version: %#v\n", latestVersion)
    
    					content, err := versions.GetContent(ctx, latestVersion.Sid)
    					if err != nil {
    						return err
    					}
    					fmt.Printf("content: %#v\n", content)
    				}
    			}
    		}
    	}
    }
    
    opened by saurori 3
  • feat(chat): add push notification token inside the token

    feat(chat): add push notification token inside the token

    Changelog

    • Added: Possibility to add push notification key inside ChatGrant token.

    See ref: https://www.twilio.com/docs/chat/javascript/push-notifications-web#step-4-pass-the-api-credential-sid-in-your-access-token

    opened by luispiresgympass 3
  • Add Voice Insights API

    Add Voice Insights API

    Description

    Added all three Twilio Voice Insights API:

    • Summary
    • Events
    • Metrics

    Usage

    # https://insights.twilio.com/v1/Voice/{CallSid}/Metrics
    t.client.Insights.VoiceInsights(callSID).Metrics.GetPage(ctx, params)
    
    # https://insights.twilio.com/v1/Voice/{CallSid}/Events
    t.client.Insights.VoiceInsights(callSID).Events.GetPage(ctx, params)
    
    # https://insights.twilio.com/v1/Voice/{CallSid}/Summary
    t.client.Insights.VoiceInsights(callSID).Summary.Get(ctx)
    t.client.Insights.VoiceInsights(callSID).Summary.GetPartial(ctx)
    
    opened by yeoji 3
  • Assumes US by default - should be configurable

    Assumes US by default - should be configurable

    https://github.com/kevinburke/twilio-go/blob/113f30c37433cfcec823220cc8ece2be14619bf0/types.go#L25

    Either extend NewPhoneNumber() with a default, or add NewPhoneNumberWithDefault() ?

    opened by kgolding 3
  • Unable to build due to errors in http.go

    Unable to build due to errors in http.go

    Hi @kevinburke,

    My codebase is using saintpete/twilio-go which works great until now as we need AvailableNumbers to provision new phone numbers. Trying this project but I can't get it to build. Any help would be very appreciated.

    Appears that there's an incompatibility with: github.com/kevinburke/rest

    Thank you! -Laura

    # github.com/saintpete/twilio-go
    ./http.go:110:3: unknown field 'StatusCode' in struct literal of type rest.Error
    ./http.go:247:15: rerr.StatusCode undefined (type *rest.Error has no field or method StatusCode)
    

    My go version: go version go1.12 darwin/amd64

    opened by lauraeci 3
  • Task Router Workflow Configuration

    Task Router Workflow Configuration

    I'm looking into building the TaskRouter Workflow API into this package.

    The endpoint takes a Configuration parameter which is a JSON encoded string, but in reality we can build a structured type from this string. The string must look like:

    {
        "task_routing": {
            "default_filter": {
                "queue": "WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
            },
            "filters": [
                {
                    "expression": "type=='sales'",
                    "targets": [
                        {
                            "queue": "WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
                        }
                    ]
                },
                {
                    "expression": "type=='marketing'",
                    "targets": [
                        {
                            "queue": "WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
                            "expression": "task.foo == worker.foo" <-- This is optional 
                        }
                    ]
                },
                {
                    "expression": "type=='support'",
                    "targets": [
                        {
                            "queue": "WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
                        }
                    ]
                }
            ]
        }
    }
    

    I'm looking for some advice/help in how we can model this Go side, I think we should force a user into building valid configurations and not allow them to pass in a simple json string.

    opened by joshhornby 3
  • Migrate to github.com/golang-jwt/jwt

    Migrate to github.com/golang-jwt/jwt

    Hi @kevinburke,

    first of all thank you a whole lot for maintaing this project! We're successfully using this library in Notify. However, yesterday dependabot threw a security alert about a flaw in github.com/dgrijalva/jwt-go. We were able to backtrace the dependency graph to this library here.

    Not sure if you're aware of this yet, so I just quickly wanted to let you know and check if you plan to replace this with, as recommended, https://github.com/golang-jwt/jwt. Of course, depending on the required effort, I'd be willing to help out with this too!

    Best regards

    opened by nikoksr 0
  • APIKey + APISecret login?

    APIKey + APISecret login?

    API keys are revokable credentials for the Twilio API. You can use API keys to authenticate to the REST API using basic auth with “user=KeySid” and “password=KeySecret”. You can also use API keys to sign access tokens which are also used by our Real-Time Communications SDKs. Access tokens are short-lived credentials that can be distributed safely to client-side applications.

    Is this supported? how?

    opened by saniales 0
  • How to include messaging service id on sending sms

    How to include messaging service id on sending sms

    I can't find the sample for adding messaging service id for sms

    the SendMessage function only accept Body, From and To, how to include MessagingServiceSid

    please help me

    image

    opened by kmacute 1
  • Notify / Messaging Examples

    Notify / Messaging Examples

    I see in the code there seems to be support for Messaging and Notify APIs however those service don't have any ability to send from what I can tell. Are these APIs supported currently? If yes would it be possible to provide an example?

    opened by devotoare 0
Owner
Kevin Burke
Formerly engineering at Twilio and Shyp. Now doing consulting, possibly for you. Get in touch!
Kevin Burke
General purpose library for reading, writing and working with OpenStreetMap data

osm This package is a general purpose library for reading, writing and working with OpenStreetMap data in Go (golang). It has the ability to read OSM

Paul Mach 246 Dec 30, 2022
S2 geometry library in Go

Overview S2 is a library for spherical geometry that aims to have the same robustness, flexibility, and performance as the best planar geometry librar

Go 1.5k Jan 8, 2023
Go package for fast high-level image processing powered by libvips C library

bimg Small Go package for fast high-level image processing using libvips via C bindings, providing a simple programmatic API. bimg was designed to be

Tom 2.1k Jan 2, 2023
Image processing library and rendering toolkit for Go.

blend Image processing library and rendering toolkit for Go. (WIP) Installation: This library is compatible with Go1. go get github.com/phrozen/blend

Guillermo Estrada 61 Nov 11, 2022
Go bindings to OpenGL Utility Library

GLU This package offers minimal bindings for GLU functions. Usage go get github.com/go-gl-legacy/glu License Copyright 2012 The go-gl Authors. All ri

go-gl legacy 21 Aug 18, 2018
Go binding for the cairo graphics library

go-cairo Go binding for the cairo graphics library Based on Dethe Elza's version https://bitbucket.org/dethe/gocairo but significantly extended and up

Erik Unger 125 Dec 19, 2022
A library for playing with colors in go (golang).

go-colorful A library for playing with colors in Go. Supports Go 1.13 onwards. Why? I love games. I make games. I love detail and I get lost in detail

Lucas Beyer 1k Dec 30, 2022
A lightning fast image processing and resizing library for Go

govips A lightning fast image processing and resizing library for Go This package wraps the core functionality of libvips image processing library by

David Byttow 816 Jan 8, 2023
This is old and unmaintained code, ignore it. starfish is a simple, SDL based, 2D graphics and user input library for Go. If you intend to work on it, please fork from the 'devel' branch, not 'master'. Current release: 0.12.0

What is starfish? What starfish is: starfish is a simple 2D graphics and user input library for Go built on SDL. What starfish is not: While it is bui

Gary Talent 12 Jun 4, 2019
A library to read, write, and transform Stereolithography (.stl) files in Go.

stl A library to read, write, and transform Stereolithography (.stl) files in Go. It is used in the command line STL manipulation tool stltool. Featur

Hagen Schendel 65 Sep 26, 2022
Go Language Library for SVG generation

SVGo: A Go library for SVG generation The library generates SVG as defined by the Scalable Vector Graphics 1.1 Specification (http://www.w3.org/TR/SVG

Anthony Starks 2k Jan 6, 2023
:eyeglasses: Go library for [d]encoding glTF 2.0 files

gltf A Go module for efficient and robust serialization/deserialization of glTF 2.0, a royalty-free specification for the efficient transmission and l

Quim Muntal 187 Jan 1, 2023
Port of webcolors library from Python to Go

go-webcolors A library for working with color names and color value formats defined by the HTML and CSS specifications for use in documents on the Web

Jyotiska Khasnabish 27 Sep 26, 2022
Avatar generation library for GO language

GOvatar GOvatar is an avatar generation library written in GO Install To install the library and command-line program, use the following: $ go get -u

Oleg Lobanov 537 Dec 29, 2022
A Grid based 2D Graphics library

gridder Built on top of Go Graphics github.com/fogleman/gg with the idea to simplify visualizing Grids using 2D Graphics. Dependencies gg github.com/f

Raed Shomali 59 Dec 1, 2022
go library for image programming (merge, crop, resize, watermark, animate, ease, transit)

Result Terminal Code mergi -t TT -i https://raw.githubusercontent.com/ashleymcnamara/gophers/master/Facepalm_Gopher.png -r "131 131" -i https://raw.gi

Noel Yahan 197 Jan 6, 2023
Pure Golang Library that allows simple LSB steganography on images

Steganography Lib Steganography is a library written in Pure go to allow simple LSB steganography on images. It is capable of both encoding and decodi

Rafael Passos 176 Dec 22, 2022
Go cross-platform glfw library for creating an OpenGL context and receiving events.

glfw Package glfw experimentally provides a glfw-like API with desktop (via glfw) and browser (via HTML5 canvas) backends. It is used for creating a G

null 77 Sep 27, 2022
A pure Go 3D math library.

MathGL This is a Go matrix and vector math library specialized for Open GL graphics capabilities. This package is made primarily with code generation

OpenGL with Golang 466 Dec 24, 2022