twilio

package module
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Jun 30, 2021 License: MIT Imports: 36 Imported by: 387

README

twilio-go

Build Status PkgGoDev Release Learn OSS Contribution in TwilioQuest

Project Status

⚠ This project is currently in PILOT and under active development. If you've identified an issue, please open an issue. If you would like to participate in the pilot, please sign up for Twilio Insiders.

All the code here was generated by twilio-oai-generator by leveraging openapi-generator and twilio-oai. If you find an issue with the generation or the OpenAPI specs, please go ahead and open an issue or a PR against the relevant repositories.

Documentation

The documentation for the Twilio API can be found here.

The Go library documentation can be found here.

Supported Go Versions

This library supports the following Go implementations:

  • 1.15
  • 1.16

Installation

To use twilio-go in your project initialize go modules then run:

go get github.com/twilio/twilio-go

Getting Started

Getting started with the Twilio API couldn't be easier. Create a RestClient and you're ready to go.

API Credentials

The Twilio RestClient needs your Twilio credentials. You should pass these directly to the constructor (see the code below).

package main

import "github.com/twilio/twilio-go"

func main() {
    accountSid := "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    authToken := "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY"
    client := twilio.NewRestClient(accountSid, authToken)
}

package main

import "github.com/twilio/twilio-go"

func main() {
    accountSid := "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    authToken := "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY"
    subaccountSid := "ACYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY"
    client := twilio.NewRestClientWithParams(accountSid, authToken, twilio.RestClientParams{
        AccountSid: subaccountSid,
    })
}

We suggest storing your credentials as environment variables and then use it in your code. Why? You'll never have to worry about committing your credentials and accidentally posting them somewhere public.

package main

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

func main() {
    accountSid := os.Getenv("TWILIO_ACCOUNT_SID")
    authToken := os.Getenv("TWILIO_AUTH_TOKEN")
    client := twilio.NewRestClient(accountSid, authToken)
}
Specify a Region and/or Edge
package main

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

func main() {
    accountSid := os.Getenv("TWILIO_ACCOUNT_SID")
    authToken := os.Getenv("TWILIO_AUTH_TOKEN")
    client := twilio.NewRestClient(accountSid, authToken)
    client.SetRegion("au1")
    client.SetEdge("sydney")
}

This will result in the hostname transforming from api.twilio.com to api.sydney.au1.twilio.com.

A Twilio client constructed without these parameters will also look for TWILIO_REGION and TWILIO_EDGE variables inside the current environment.

Buy a phone number
package main

import (
    "fmt"
    "github.com/twilio/twilio-go"
    openapi "github.com/twilio/twilio-go/rest/api/v2010"
    "os"
)

func main() {
    accountSid := os.Getenv("TWILIO_ACCOUNT_SID")
    authToken := os.Getenv("TWILIO_AUTH_TOKEN")
    phoneNumber := "AVAILABLE_TWILIO_PHONE_NUMBER"
    subaccountSid := os.Getenv("TWILIO_SUBACCOUNT_SID")

    client := twilio.NewRestClientWithParams(accountSid, authToken, twilio.RestClientParams{
        AccountSid: subaccountSid,
    })

    params := &openapi.CreateIncomingPhoneNumberParams{}
    params.SetPhoneNumber(phoneNumber)

    resp, err := client.ApiV2010.CreateIncomingPhoneNumber(params)
    if err != nil {
        fmt.Println(err.Error())
        err = nil
    } else {
        fmt.Println("Phone Number Status: " + *resp.Status)
    }
}
Send a text message
package main

import (
    "encoding/json"
    "fmt"
    "github.com/twilio/twilio-go"
    openapi "github.com/twilio/twilio-go/rest/api/v2010"
    "os"
)

func main() {
    accountSid := os.Getenv("TWILIO_ACCOUNT_SID")
    authToken := os.Getenv("TWILIO_AUTH_TOKEN")
    from := os.Getenv("TWILIO_FROM_PHONE_NUMBER")
    to := os.Getenv("TWILIO_TO_PHONE_NUMBER")
    subaccountSid := os.Getenv("TWILIO_SUBACCOUNT_SID")

    client := twilio.NewRestClientWithParams(accountSid, authToken, twilio.RestClientParams{
        AccountSid: subaccountSid,
    })

    params := &openapi.CreateMessageParams{}
    params.SetTo(to)
    params.SetFrom(from)
    params.SetBody("Hello there")

    resp, err := client.ApiV2010.CreateMessage(params)
    if err != nil {
        fmt.Println(err.Error())
        err = nil
    } else {
        response, _ := json.Marshal(*resp)
        fmt.Println("Response: " + string(response))
    }
}
Make a call
package main

import (
    "fmt"
    "github.com/twilio/twilio-go"
    openapi "github.com/twilio/twilio-go/rest/api/v2010"
    "os"
)

func main() {
    accountSid := os.Getenv("TWILIO_ACCOUNT_SID")
    authToken := os.Getenv("TWILIO_AUTH_TOKEN")
    from := os.Getenv("TWILIO_FROM_PHONE_NUMBER")
    to := os.Getenv("TWILIO_TO_PHONE_NUMBER")

    client := twilio.NewRestClient(accountSid, authToken)

    params := &openapi.CreateCallParams{}
    params.SetTo(to)
    params.SetFrom(from)
    params.SetUrl("http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient")

    resp, err := client.ApiV2010.CreateCall(params)
    if err != nil {
        fmt.Println(err.Error())
        err = nil
    } else {
        fmt.Println("Call Status: " + *resp.Status)
        fmt.Println("Call Sid: " + *resp.Sid)
        fmt.Println("Call Direction: " + *resp.Direction)
    }
}
Create a Serverless Function
package main

import (
    "fmt"
    "github.com/twilio/twilio-go"
    openapi "github.com/twilio/twilio-go/rest/serverless/v1"
)

func main() {
    accountSid := os.Getenv("TWILIO_ACCOUNT_SID")
    authToken := os.Getenv("TWILIO_AUTH_SID")
    serviceSid := "ZSxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

    client := twilio.NewRestClient(accountSid, authToken)

    params := &openapi.CreateFunctionParams{}
    params.SetFriendlyName("My Serverless func")

    resp, err := client.ServerlessV1.CreateFunction(serviceSid, params)
    if err != nil {
        fmt.Println(err.Error())
        err = nil
    } else {
        fmt.Println(*resp.Sid)
    }
}

Create a Studio Flow
package main

import (
    "encoding/json"
    "fmt"
    "os"

    "github.com/twilio/twilio-go"
    openapi "github.com/twilio/twilio-go/rest/studio/v2"
)

func main() {
    accountSid := os.Getenv("TWILIO_ACCOUNT_SID")
    authToken := os.Getenv("TWILIO_AUTH_TOKEN")

    var jsonStr = `{
   "description":"Twilio Studio flow service",
   "initial_state":"Trigger",
   "states":[
      {
         "properties":{
            "offset":{
               "y":0,
               "x":0
            }
         },
         "transitions":[

         ],
         "name":"Trigger",
         "type":"trigger"
      }
   ]
}`

    definition := make(map[string]interface{})
    _ = json.Unmarshal([]byte(jsonStr), &definition)

    client := twilio.NewRestClient(accountSid, authToken)
    params := &openapi.CreateFlowParams{
        Definition: &definition,
    }
    params.SetCommitMessage("commit")
    params.SetFriendlyName("Studio flow from Go")
    params.SetStatus("draft")

    resp, err := client.StudioV2.CreateFlow(params)
    if err != nil {
        fmt.Println(err.Error())
    } else {
        fmt.Println(*resp.Sid)
    }
}
Handling Exceptions
package main

import (
    "fmt"
    "os"

    "github.com/twilio/twilio-go"
    "github.com/twilio/twilio-go/framework/error"
    openapi "github.com/twilio/twilio-go/rest/api/v2010"
)

func main() {
    accountSid := os.Getenv("TWILIO_ACCOUNT_SID")
    authToken := os.Getenv("TWILIO_AUTH_TOKEN")
    phoneNumber := os.Getenv("TWILIO_PHONE_NUMBER")

    client := twilio.NewRestClient(accountSid, authToken)

    params := &openapi.CreateIncomingPhoneNumberParams{}
    params.SetPhoneNumber(phoneNumber)

    resp, err := client.ApiV2010.CreateIncomingPhoneNumber(params)
    if err != nil {
        twilioError := err.(*error.TwilioRestError)
        fmt.Println(twilioError.Error())
    }
}

For more descriptive exception types, please see the Twilio documentation.

Advanced Usage

Using Standalone Products

Don't want to import the top-level Twilio RestClient with access to the full suite of Twilio products? Use standalone product services instead:

package main

import (
    "os"

    "github.com/twilio/twilio-go/client"
    apiv2010 "github.com/twilio/twilio-go/rest/api/v2010"
    serverless "github.com/twilio/twilio-go/rest/serverless/v1"
)

func main() {
    accountSid := os.Getenv("TWILIO_ACCOUNT_SID")
    authToken := os.Getenv("TWILIO_AUTH_TOKEN")

    // Create an instance of our default BaseClient implementation
    defaultClient := &client.Client{
        Credentials: client.NewCredentials(accountSid, authToken),
    }
    defaultClient.SetAccountSid(accountSid)

    coreApiService := apiv2010.NewApiServiceWithClient(defaultClient)
    serverlessApiService := serverless.NewApiServiceWithClient(defaultClient)
}
Using a Custom Client
package main

import (
    "fmt"
    "net/http"
    "net/url"
    "os"

    "github.com/twilio/twilio-go"
    "github.com/twilio/twilio-go/client"
    openapi "github.com/twilio/twilio-go/rest/api/v2010"
)

type MyClient struct {
    client.Client
}

func (c *MyClient) SendRequest(method string, rawURL string, data url.Values, headers map[string]interface{}) (*http.Response, error) {
    // Custom code to pre-process request here
    resp, err := c.Client.SendRequest(method, rawURL, data, headers)
    // Custom code to pre-process response here
    fmt.Println(resp.StatusCode)
    return resp, err
}

func main() {
    accountSid := os.Getenv("TWILIO_ACCOUNT_SID")
    authToken := os.Getenv("TWILIO_AUTH_TOKEN")

    customClient := &MyClient{
        Client: client.Client{
            Credentials: client.NewCredentials(accountSid, authToken),
        },
    }
    customClient.SetAccountSid(accountSid)

    twilioClient := twilio.NewRestClientWithParams(accountSid, authToken, twilio.RestClientParams{Client: customClient})

    // You may also use custom clients with standalone product services
    twilioApiV2010 := openapi.NewApiServiceWithClient(customClient)
}

Local Usage

Building

To build twilio-go run:

go build ./...
Testing

To execute the test suite run:

go test ./...
Generating Local Documentation

To generate documentation, from the root directory:

godoc -http=localhost:{port number}

Then, navigate to http://localhost:{port number}/pkg/github.com/twilio/twilio-go in your local browser.

Example:

godoc -http=localhost:6060

http://localhost:6060/pkg/github.com/twilio/twilio-go

Documentation

Overview

Package twilio provides bindings for Twilio's REST APIs.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Meta

type Meta struct {
	FirstPageURL    *string `json:"first_page_url"`
	Key             *string `json:"key"`
	LastPageURL     *string `json:"last_page_url,omitempty"`
	NextPageURL     *string `json:"next_page_url"`
	Page            *int    `json:"page"`
	PageSize        *int    `json:"page_size"`
	PreviousPageURL *string `json:"previous_page_url"`
	URL             *string `json:"url"`
}

Meta holds relevant pagination resources.

type RestClient added in v0.8.0

type RestClient struct {
	*client.RequestHandler
	AccountsV1      *AccountsV1.ApiService
	ApiV2010        *ApiV2010.ApiService
	AutopilotV1     *AutopilotV1.ApiService
	BulkexportsV1   *BulkexportsV1.ApiService
	ChatV1          *ChatV1.ApiService
	ChatV2          *ChatV2.ApiService
	ConversationsV1 *ConversationsV1.ApiService
	EventsV1        *EventsV1.ApiService
	FaxV1           *FaxV1.ApiService
	FlexV1          *FlexV1.ApiService
	FrontlineV1     *FrontlineV1.ApiService
	InsightsV1      *InsightsV1.ApiService
	IpMessagingV1   *IpMessagingV1.ApiService
	IpMessagingV2   *IpMessagingV2.ApiService
	LookupsV1       *LookupsV1.ApiService
	MessagingV1     *MessagingV1.ApiService
	MonitorV1       *MonitorV1.ApiService
	NotifyV1        *NotifyV1.ApiService
	NumbersV2       *NumbersV2.ApiService
	PricingV1       *PricingV1.ApiService
	PricingV2       *PricingV2.ApiService
	ProxyV1         *ProxyV1.ApiService
	ServerlessV1    *ServerlessV1.ApiService
	StudioV1        *StudioV1.ApiService
	StudioV2        *StudioV2.ApiService
	SupersimV1      *SupersimV1.ApiService
	SyncV1          *SyncV1.ApiService
	TaskrouterV1    *TaskrouterV1.ApiService
	TrunkingV1      *TrunkingV1.ApiService
	TrusthubV1      *TrusthubV1.ApiService
	VerifyV2        *VerifyV2.ApiService
	VideoV1         *VideoV1.ApiService
	VoiceV1         *VoiceV1.ApiService
	WirelessV1      *WirelessV1.ApiService
}

RestClient provides access to Twilio services.

func NewRestClient added in v0.8.0

func NewRestClient(username string, password string) *RestClient

NewRestClient provides an initialized Twilio RestClient.

func NewRestClientWithParams added in v0.8.0

func NewRestClientWithParams(username string, password string, params RestClientParams) *RestClient

NewRestClientWithParams provides an initialized Twilio RestClient with params.

func (*RestClient) SetEdge added in v0.8.0

func (c *RestClient) SetEdge(edge string)

SetEdge sets the Edge for the Twilio request.

func (*RestClient) SetRegion added in v0.8.0

func (c *RestClient) SetRegion(region string)

SetRegion sets the Region for the Twilio request. Defaults to "us1" if an edge is provided.

func (*RestClient) SetTimeout added in v0.8.0

func (c *RestClient) SetTimeout(timeout time.Duration)

SetTimeout sets the Timeout for Twilio HTTP requests.

type RestClientParams added in v0.8.0

type RestClientParams struct {
	AccountSid string
	Client     client.BaseClient
}

Directories

Path Synopsis
Package client provides internal utilities for the twilio-go client library.
Package client provides internal utilities for the twilio-go client library.
rest

Jump to

Keyboard shortcuts

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