gotwilio

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

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

Go to latest
Published: Feb 14, 2015 License: BSD-2-Clause Imports: 17 Imported by: 0

README

Overview

This is an unofficial Go API library for Twilio. Gotwilio supports making voice calls, sending text messages, validating requests, creating TWiML responses, and various REST resources.

License

Gotwilio is licensed under a BSD license.

Installation

To install gotwilio, run go get github.com/Januzellij/gotwilio.

Getting Started

Just create a Twilio client with either NewTwilioClient(accountSid, authToken) or NewTwilioClientFromEnv(), and store the accountSid and authToken in TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN environment variables, respectively. For security purposes, please use NewTwilioClientFromEnv() in any open source code.

Docs

All documentation can be found here

SMS Example

package main

import (
	"log"

	"github.com/Januzellij/gotwilio"
)

func main() {
	accountSid := "ABC123..........ABC123"
	authToken := "ABC123..........ABC123"
	twilio := gotwilio.NewTwilioClient(accountSid, authToken)

	from := "+15555555555"
	to := "+15555555555"
	message := "Welcome to gotwilio!"
	_, exception, err := twilio.SendSMS(from, to, message, "", "")
	if exception != nil {
		log.Fatal(*exception)
	}
	if err != nil {
		log.Fatal(err)
	}
}

Voice Example

package main

import "github.com/Januzellij/gotwilio"

func main() {
	accountSid := "ABC123..........ABC123"
	authToken := "ABC123..........ABC123"
	twilio := gotwilio.NewTwilioClient(accountSid, authToken)

	from := "+15555555555"
	to := "+15555555555"
	callbackParams := gotwilio.NewCallbackParameters("http://example.com")
	_, exception, err := twilio.CallWithUrlCallbacks(from, to, callbackParams)
	if exception != nil {
		log.Fatal(*exception)
	}
	if err != nil {
		log.Fatal(err)
	}
}

Validate Example

package main

import (
	"log"
	"net/http"

	"github.com/Januzellij/gotwilio"
)

func root(w http.ResponseWriter, r *http.Request) {
	twilio, err := NewTwilioClientFromEnv()
	if err != nil {
		// one or more environment variables are missing
		log.Fatal(err)
	}
	url := "http://example.com/"
	isValid, err := gotwilio.Validate(r, url, twilio.authToken)
	if err != nil {
		// the request was malformed
	}
	if isValid {
		// proceed, the request is from Twilio
	}
}

func main() {
	http.HandleFunc("/", root)
	http.ListenAndServe(":8080", nil)
}

Twiml Response Example

package main

import (
	"log"
	"os"

	"github.com/Januzellij/gotwilio"
)

func main() {
	newSay := gotwilio.Say{Text: "test", Voice: "alice"}
	newPause := gotwilio.Pause{Length: "2"}
	resp := gotwilio.NewTwimlResponse(newSay, newPause)
	err := resp.SendTwimlResponse(os.Stdout) // when using Twiml in a real web app, this would actually be written to a http.ResponseWriter.
	if err != nil {
		// something other than TWiML verbs was given to the TWiML response
		log.Fatal(err)
	}
}

Usage Record Example

package main

import (
	"fmt"
	"log"

	"github.com/Januzellij/gotwilio"
)

func main() {
	twilio, err := gotwilio.NewTwilioClientFromEnv()
	if err != nil {
		log.Fatal(err)
	}
	filter := &gotwilio.UsageFilter{StartDate: "2012-6-4", EndDate: "2014-1-1"}
	records, exception, err := twilio.UsageRecordsDaily(filter)
	if exception != nil {
		log.Fatal(*exception)
	}
	if err != nil {
		log.Fatal(err)
	}
	for _, record := range records.UsageRecords {
		fmt.Printf("Category: %s, Usage: %d \n", record.Category, record.Usage)
	}
}

Documentation

Overview

Package gotwilio is a library for interacting with http://www.twilio.com/ API. It is an extended version of http://godoc.org/github.com/sfreiberg/gotwilio

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Validate

func Validate(r *http.Request, url, authToken string) (bool, error)

Validate checks if an http request actually came from Twilio, and is not faked. Validate uses directions from https://www.twilio.com/docs/security

Types

type CallbackParameters

type CallbackParameters struct {
	Url                  string // Required
	Method               string // Optional
	FallbackUrl          string // Optional
	FallbackMethod       string // Optional
	StatusCallback       string // Optional
	StatusCallbackMethod string // Optional
	SendDigits           string // Optional
	IfMachine            string // False, Continue or Hangup; http://www.twilio.com/docs/errors/21207
	Timeout              int    // Optional
	Record               bool   // Optional
}

These are the paramters to use when you want Twilio to use callback urls. See http://www.twilio.com/docs/api/rest/making-calls for more info.

func NewCallbackParameters

func NewCallbackParameters(url string) *CallbackParameters

NewCallbackParameters returns a CallbackParameters type with the specified url and CallbackParameters.Timeout set to 60.

type Client

type Client struct {
	Text   string `xml:",chardata"`
	Url    string `xml:"url,attr,omitempty"`
	Method string `xml:"method,attr,omitempty"`
}

type Conference

type Conference struct {
	Text                   string `xml:",chardata"`
	Muted                  string `xml:"muted,attr,omitempty"`
	Beep                   string `xml:"beep,attr,omitempty"`
	StartConferenceOnEnter string `xml:"startConferenceOnEnter,attr,omitempty"`
	EndConferenceOnExit    string `xml:"endConferenceOnExit,attr,omitempty"`
	WaitUrl                string `xml:"waitUrl,attr,omitempty"`
	WaitMethod             string `xml:"waitMethod,attr,omitempty"`
	MaxParticipants        string `xml:"maxParticipants,attr,omitempty"`
}

type Dial

type Dial struct {
	Text         string   `xml:",chardata"`
	Action       string   `xml:"action,attr,omitempty"`
	Method       string   `xml:"method,attr,omitempty"`
	Timeout      string   `xml:"timeout,attr,omitempty"`
	HangupOnStar string   `xml:"hangupOnStar,attr,omitempty"`
	TimeLimit    string   `xml:"timeLimit,attr,omitempty"`
	CallerId     string   `xml:"callerId,attr,omitempty"`
	Record       string   `xml:"record,attr,omitempty"`
	Numbers      []Number `xml:"Number"`
	Clients      []Client `xml:"Client"`
}

type Exception

type Exception struct {
	Status   int    `json:"status"`    // HTTP specific error code
	Message  string `json:"message"`   // HTTP error message
	Code     int    `json:"code"`      // Twilio specific error code
	MoreInfo string `json:"more_info"` // Additional info from Twilio
}

Exception is a representation of a twilio exception.

func (*Exception) Error

func (exception *Exception) Error() string

type Gather

type Gather struct {
	XMLName     xml.Name `xml:"Gather"`
	Action      string   `xml:"action,attr,omitempty"`
	Method      string   `xml:"method,attr,omitempty"`
	Timeout     string   `xml:"timeout,attr,omitempty"`
	FinishOnKey string   `xml:"finishOnKey,attr,omitempty"`
	NumDigits   string   `xml:"numDigits,attr,omitempty"`
	Say         Say      `xml:"Say"`
	Play        Play     `xml:"Play"`
	Pause       Pause    `xml:"Pause"`
}

type Message

type Message struct {
	XMLName        xml.Name `xml:"Message"`
	To             string   `xml:"to,attr,omitempty"`
	From           string   `xml:"from,attr,omitempty"`
	Action         string   `xml:"action,attr,omitempty"`
	Method         string   `xml:"method,attr,omitempty"`
	StatusCallback string   `xml:"statusCallback,attr,omitempty"`
	Body           string   `xml:"Body,omitempty"`
	Media          string   `xml:"Media,omitempty"`
}

type Number

type Number struct {
	Text       string `xml:",chardata"`
	SendDigits string `xml:"sendDigits,attr,omitempty"`
	Url        string `xml:"url,attr,omitempty"`
	Method     string `xml:"method,attr,omitempty"`
}

type Pause

type Pause struct {
	Length string `xml:"length,attr"`
}

type Play

type Play struct {
	Text   string `xml:",chardata"`
	Loop   string `xml:"loop,attr,omitempty"`
	Digits string `xml:"digits,attr,omitempty"`
}

type Queue

type Queue struct {
	Text   string `xml:",chardata"`
	Url    string `xml:"url,attr,omitempty"`
	Method string `xml:"method,attr,omitempty"`
}

type Record

type Record struct {
	Action             string `xml:"action,attr,omitempty"`
	Method             string `xml:"method,attr,omitempty"`
	Timeout            string `xml:"timeout,attr,omitempty"`
	FinishOnKey        string `xml:"finishOnKey,attr,omitempty"`
	MaxLength          string `xml:"maxLength,attr,omitempty"`
	Transcribe         string `xml:"transcribe,attr,omitempty"`
	TranscribeCallback string `xml:"transcribeCallback,attr,omitempty"`
	PlayBeep           string `xml:"playBeep,attr,omitempty"`
}

type Redirect

type Redirect struct {
	Text   string `xml:",chardata"`
	Method string `xml:"method,attr,omitempty"`
}

type Response

type Response struct {
	Verbs []interface{}
}

Response is a representation of a TWiML response. More information about TWiML can be found at https://www.twilio.com/docs/api/twiml

func NewTwimlResponse

func NewTwimlResponse(verbs ...interface{}) *Response

NewTwimlResponse creates a Response with the provided verbs. Verbs will appear in XML in the order provided

func (*Response) SendTwimlResponse

func (resp *Response) SendTwimlResponse(w io.Writer) error

SendTwimlResponse encodes the Response and writes it to the provided io.Writer

type Say

type Say struct {
	Text     string `xml:",chardata"`
	Voice    string `xml:"voice,attr,omitempty"`
	Loop     string `xml:"loop,attr,omitempty"`
	Language string `xml:"language,attr,omitempty"`
}

type Sip

type Sip struct {
	Text     string `xml:",chardata"`
	Username string `xml:"username,attr,omitempty"`
	Password string `xml:"password,attr,omitempty"`
	Url      string `xml:"url,attr,omitempty"`
	Method   string `xml:"method,attr,omitempty"`
}

type SmsResponse

type SmsResponse struct {
	Sid         string   `json:"sid"`
	DateCreated string   `json:"date_created"`
	DateUpdate  string   `json:"date_updated"`
	DateSent    string   `json:"date_sent"`
	AccountSid  string   `json:"account_sid"`
	To          string   `json:"to"`
	From        string   `json:"from"`
	Body        string   `json:"body"`
	Status      string   `json:"status"`
	Direction   string   `json:"direction"`
	ApiVersion  string   `json:"api_version"`
	Price       *float32 `json:"price,omitempty"`
	Url         string   `json:"uri"`
}

SmsResponse is returned after a text/sms message is posted to Twilio

func (*SmsResponse) DateCreatedAsTime

func (sms *SmsResponse) DateCreatedAsTime() (time.Time, error)

Returns SmsResponse.DateCreated as a time.Time object instead of a string.

func (*SmsResponse) DateSentAsTime

func (sms *SmsResponse) DateSentAsTime() (time.Time, error)

Returns SmsResponse.DateSent as a time.Time object instead of a string.

func (*SmsResponse) DateUpdateAsTime

func (sms *SmsResponse) DateUpdateAsTime() (time.Time, error)

Returns SmsResponse.DateUpdate as a time.Time object instead of a string.

type Twilio

type Twilio struct {
	AccountSid, AuthToken, BaseUrl string
}

Twilio stores basic information important for connecting to the twilio.com REST api such as AccountSid and AuthToken.

func NewTwilioClient

func NewTwilioClient(accountSid, authToken string) *Twilio

NewTwilioClient creates a new Twilio struct from provided credentials. Not recommended for use in public code, see TwilioClientFromEnv

func NewTwilioClientFromEnv

func NewTwilioClientFromEnv() (*Twilio, error)

NewTwilioClientFromEnv creates a new Twilio struct from environment variables. Recommended for use in public code

func (*Twilio) CallWithApplicationCallbacks

func (twilio *Twilio) CallWithApplicationCallbacks(from, to, applicationSid string) (*VoiceResponse, *Exception, error)

Place a voice call with an ApplicationSid specified.

func (*Twilio) CallWithUrlCallbacks

func (twilio *Twilio) CallWithUrlCallbacks(from, to string, callbackParameters *CallbackParameters) (*VoiceResponse, *Exception, error)

Place a voice call with a list of callbacks specified.

func (*Twilio) SendSMS

func (twilio *Twilio) SendSMS(from, to, body, statusCallback, applicationSid string) (*SmsResponse, *Exception, error)

SendSMS uses Twilio to send a text message. See http://www.twilio.com/docs/api/rest/sending-sms for more information.

func (*Twilio) UsageRecords

func (twilio *Twilio) UsageRecords(filter *UsageFilter) (*UsageRecords, *Exception, error)

UsageRecords returns all UsageRecord's at the list resource, with the given filter parameters, if provided. The error returned results from a misformatted url, failed http request, or bad JSON. The exception is an error from the Twilio API.

func (*Twilio) UsageRecordsAllTime

func (twilio *Twilio) UsageRecordsAllTime(filter *UsageFilter) (*UsageRecords, *Exception, error)

UsageRecordsAllTime is equivalent to UsageRecords

func (*Twilio) UsageRecordsDaily

func (twilio *Twilio) UsageRecordsDaily(filter *UsageFilter) (*UsageRecords, *Exception, error)

UsageRecordsDaily returns UsageRecord's over a daily time interval

func (*Twilio) UsageRecordsLastMonth

func (twilio *Twilio) UsageRecordsLastMonth(filter *UsageFilter) (*UsageRecords, *Exception, error)

UsageRecordsLastMonth returns UsageRecord's for last months's usage

func (*Twilio) UsageRecordsMonthly

func (twilio *Twilio) UsageRecordsMonthly(filter *UsageFilter) (*UsageRecords, *Exception, error)

UsageRecordsMonthly returns UsageRecord's over a monthly time interval

func (*Twilio) UsageRecordsThisMonth

func (twilio *Twilio) UsageRecordsThisMonth(filter *UsageFilter) (*UsageRecords, *Exception, error)

UsageRecordsThisMonth returns UsageRecord's for this months's usage

func (*Twilio) UsageRecordsToday

func (twilio *Twilio) UsageRecordsToday(filter *UsageFilter) (*UsageRecords, *Exception, error)

UsageRecordsToday returns UsageRecord's for today's usage

func (*Twilio) UsageRecordsYearly

func (twilio *Twilio) UsageRecordsYearly(filter *UsageFilter) (*UsageRecords, *Exception, error)

UsageRecordsYearly returns UsageRecord's over a yearly time interval

func (*Twilio) UsageRecordsYesterday

func (twilio *Twilio) UsageRecordsYesterday(filter *UsageFilter) (*UsageRecords, *Exception, error)

UsageRecordsYesterday returns UsageRecord's for yesterday's usage

type UsageFilter

type UsageFilter struct {
	Category, StartDate, EndDate string
}

UsageFilter contains all UsageRecord filter query parameters

type UsageRecord

type UsageRecord struct {
	Category    string   `json:"category"`
	Description string   `json:"description"`
	AccountSid  string   `json:"account_sid"`
	StartDate   string   `json:"start_date"`
	EndDate     string   `json:"end_date"`
	Count       int64    `json:"count"`
	CountUnit   string   `json:"count_unit"`
	Usage       int64    `json:"usage"`
	UsageUnit   string   `json:"usage_unit"`
	Price       *float32 `json:"price,omitempty"`
	PriceUnit   string   `json:"price_unit"`
	ApiVersion  string   `json:"api_version"`
	Uri         string   `json:"uri"`
}

UsageRecord contains all data for a Twilio Usage Record

type UsageRecords

type UsageRecords struct {
	FirstPageUri    string        `json:"first_page_uri"`
	End             int           `json:"end"`
	PreviousPageUri string        `json:"previous_page_uri"`
	Uri             string        `json:"uri"`
	PageSize        int           `json:"page_size"`
	Start           int           `json:"start"`
	UsageRecords    []UsageRecord `json:"usage_records"`
}

UsageRecords contains a a list of requested UsageRecord's and metadata

type VoiceResponse

type VoiceResponse struct {
	Sid            string   `json:"sid"`
	DateCreated    string   `json:"date_created"`
	DateUpdated    string   `json:"date_updated"`
	ParentCallSid  string   `json:"parent_call_sid"`
	AccountSid     string   `json:"account_sid"`
	To             string   `json:"to"`
	ToFormatted    string   `json:"to_formatted"`
	From           string   `json:"from"`
	FromFormatted  string   `json:"from_formatted"`
	PhoneNumberSid string   `json:"phone_number_sid"`
	Status         string   `json:"status"`
	StartTime      string   `json:"start_time"`
	EndTime        string   `json:"end_time"`
	Duration       int      `json:"duration"`
	Price          *float32 `json:"price,omitempty"`
	Direction      string   `json:"direction"`
	AnsweredBy     string   `json:"answered_by"`
	ApiVersion     string   `json:"api_version"`
	Annotation     string   `json:"annotation"`
	ForwardedFrom  string   `json:"forwarded_from"`
	GroupSid       string   `json:"group_sid"`
	CallerName     string   `json:"caller_name"`
	Uri            string   `json:"uri"`
}

VoiceResponse contains the details about successful voice calls.

func (*VoiceResponse) DateCreatedAsTime

func (vr *VoiceResponse) DateCreatedAsTime() (time.Time, error)

Returns VoiceResponse.DateCreated as a time.Time object instead of a string.

func (*VoiceResponse) DateUpdatedAsTime

func (vr *VoiceResponse) DateUpdatedAsTime() (time.Time, error)

Returns VoiceResponse.DateUpdated as a time.Time object instead of a string.

func (*VoiceResponse) EndTimeAsTime

func (vr *VoiceResponse) EndTimeAsTime() (time.Time, error)

Returns VoiceResponse.EndTime as a time.Time object instead of a string.

func (*VoiceResponse) StartTimeAsTime

func (vr *VoiceResponse) StartTimeAsTime() (time.Time, error)

Returns VoiceResponse.StartTime as a time.Time object instead of a string.

Jump to

Keyboard shortcuts

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