Help us shape the future of Go! Take the 2026 Go Developer Survey

twilio

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2018 License: MIT Imports: 12 Imported by: 0

README

Baby Twilio

Most of the time with Twilio we want to do one of two things: send an SMS and parse incoming SMSes. This package makes it easy to to both.

Sending SMSes

In the most simple case, you can set three environment variables per Twilio (TWILIO_SID, TWILIO_AUTH_TOKEN, TWILIO_PHONE_NUMBER) and then use a little function to fire off your SMSes.

package main

import (
	"baby-twilio"
	"log"
)

func main() {
	if _, err := twilio.SendSMS("+1-212-555-1212", "Well, hello there."); err != nil {
		log.Fatal("It didn‘t work: ", err)
	}
}

For more thorough examples, including ones that don‘t require setting environment variables, see the examples directory.

Receiving SMSes

Parsing incoming SMSes is just a matter of pointing a webhook at your server in the Twilio admin interface and parsing incoming requests as such:

package main

import (
	"baby-twilio"
	"log"
	"net/http"
)

func main() {

	// Handle incoming HTTP requests
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		var (
			sms *twilio.Request
			err error
		)

		// Decode request data from Twilio
		if sms, err = twilio.NewDecoder(r); err != nil {
			log.Println("could not decode incoming SMS: ", err)
			return
		}

		log.Printf("Incoming SMS from %s: %s", sms.From, sms.Body)
	})

	http.ListenAndServe(":8000", nil)
}

For local development we recommend ngrok or localtunnel

License

MIT

Documentation

Index

Constants

View Source
const (
	TwilioSID         = "TWILIO_SID"
	TwilioAuthToken   = "TWILIO_AUTH_TOKEN"
	TwilioPhoneNumber = "TWILIO_PHONE_NUMBER"
)

Environment variable keys

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	SID         string
	AuthToken   string
	PhoneNumber string
	Timeout     time.Duration
}

Client manages our requests

func NewClient

func NewClient(sid, authToken, phoneNumber string) *Client

NewClient is a factory for the client we use to send requests. One could also just initialize the `Client` struct manually too, of course,

func (Client) SendSMS

func (c Client) SendSMS(to string, msg string) (twilioResponse Response, err error)

SendSMS sends an SMS to a phone number

type Request

type Request struct {
	ToCity        string `url:"ToCity"`
	FromZip       int    `url:"FromZip"`
	MessageSID    string `url:"MessageSID"`
	SMSMessageSID string `url:"SMSMessageSID"`
	ToCountry     string `url:"ToCountry"`
	FromCountry   string `url:"FromCountry"`
	ToZip         string `url:"ToZip"`
	FromState     string `url:"FromState"`
	SMSStatus     string `url:"SMSStatus"` // should maybe be an enum?
	FromCity      string `url:"FromCity"`
	Body          string `url:"Body"`
	To            string `url:"To"`
	AccountSID    string `url:"AccountSID"`
	NumMedia      int    `url:"NumMedia"`
	From          string `url:"From"`
	SMSSid        string `url:"SMSSid"`
	NumSegments   int    `url:"NumSegments"`
}

Request represents an request to a Twilio webhook. These seem to always come in as a standard set of key/value form pairs (as opposed to JSON).

func NewDecoder

func NewDecoder(r *http.Request) (*Request, error)

NewDecoder is simply a wrapper around `Request.Decode()`. Use it like so:

req, _ := twilio.NewDecoder(htmlRequest)
fmt.Println("Hey look, this message is from", req.From)

func (*Request) Decode

func (r *Request) Decode(queryParams []byte) error

Decode decodes our struct TODO: Fix cyclomatic complexity

type Response

type Response struct {

	// Error indicates weather or not the response was an error. This is not
	// part of a normal Twilio response: we added it ourselves to remove some
	// ambigulity in our repsonses
	Error bool `json:"error"`

	// Found only in error responses
	Code     int    `json:"code,omitempty"`
	Message  string `json:"message,omitempty"`
	MoreInfo string `json:"more_info,omitempty"`

	// This is an ambigulous response. If the response is an error, this is an
	// `int`, otherwise this is a `string` (often "queued"). To deal with this
	// curious API design we don't export this and instead process the response
	// into either `.HTTPStatusCode` for errors or `.MessageStatus` for
	// successes.
	Status interface{} `json:"status,omitempty"`

	// HTTPStatusCode is the JSON `status` key in error responses. It will not
	// be set in success responses.
	HTTPStatusCode int `json:"http_status_code,omitempty"`

	// MessageStatus is the JSON `status` key in success responses. It will not
	// be set in error responses.
	MessageStatus string `json:"message_status,omitempty"`

	// Time strings we need to parse separately
	DateCreated string `json:"date_created,omitempty"`
	DateUpdated string `json:"date_updated,omitempty"`
	DateSent    string `json:"date_sent,omitempty"`

	// Parsed time strings
	Created *time.Time `json:"created,omitempty"`
	Updated *time.Time `json:"updated,omitempty"`
	Sent    *time.Time `json:"sent,omitempty"`

	// Found in success responses
	SID                 string            `json:"sid,omitempty"`
	AccountSID          string            `json:"account_sid,omitempty"`
	To                  string            `json:"to,omitempty"`
	From                string            `json:"from,omitempty"`
	MessagingServiceSID string            `json:"messaging_service_sid,omitempty"`
	Body                string            `json:"body,omitempty"`
	NumSegments         string            `json:"num_segments,omitempty"` // Twilio, why is this a string?
	NumMedia            string            `json:"num_media,omitempty"`    // Twilio, why is this a string?
	Direction           string            `json:"direction,omitempty"`
	APIVersion          string            `json:"api_version,omitempty"`
	Price               string            `json:"price,omitempty"`
	PriceUnit           string            `json:"price_unit,omitempty"`
	ErrorCode           string            `json:"error_code,omitempty"`
	ErrorMesssage       string            `json:"error_messsage,omitempty"`
	URI                 string            `json:"uri,omitempty"`
	SubResourceURIs     map[string]string `json:"sub_resource_uris,omitempty"`
}

Response contains values in a Twilio success response received after sending an SMS.

func SendSMS

func SendSMS(to string, msg string) (Response, error)

SendSMS sends an SMS. We expect the following environment varaibles to be set: TWILIO_SID, TWILIO_AUTH_TOKEN, TWILIO_PHONE_NUMBER.

To send an SMS without using environment variables, see `Client`.

func (Response) CheckError

func (r Response) CheckError() error

CheckError checks the response object for an error. If we recieved one, return an error

func (*Response) UnmarshalJSON

func (r *Response) UnmarshalJSON(b []byte) (err error)

UnmarshalJSON implements custom JSON unmarshalling for this struct. We do it here to handle the ambiguity of certain fields.

Directories

Path Synopsis
examples
receive command
send-fancy command
send-simple command

Jump to

Keyboard shortcuts

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