Skip to content

Instantly share code, notes, and snippets.

@mmcken3
Last active December 6, 2018 01:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmcken3/d2a485cb713b9f68ebeb28cc73c0c2af to your computer and use it in GitHub Desktop.
Save mmcken3/d2a485cb713b9f68ebeb28cc73c0c2af to your computer and use it in GitHub Desktop.
How to send a text message with Twilio using Go
package twilio
import (
"encoding/json"
"fmt"
"math/rand"
"net/http"
"net/url"
"strings"
"time"
)
// SendTextMessage will pack up the passed message and send it over a Twilio phone number that you set
func SendTextMessage(message string, sid string, token string) error {
urlStr := "https://api.twilio.com/2010-04-01/Accounts/" + sid + "/Messages.json"
// Create message body
msgBody := fmt.Sprintf("You message body is this: %v", message)
// Set up rand
rand.Seed(time.Now().Unix())
msgData := url.Values{}
// Set the target destination phone number with +1 type format
msgData.Set("To", fmt.Sprintf("+11234567890"))
// Set the target from Twilio phone number with +1 type format
msgData.Set("From", "+19999999999")
// Set the message body for the text
msgData.Set("Body", msgBody)
msgDataReader := *strings.NewReader(msgData.Encode())
client := &http.Client{}
req, _ := http.NewRequest("POST", urlStr, &msgDataReader)
// Set Auth tokens for Twilio on the request
req.SetBasicAuth(sid, token)
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
// Make the Twilio API call to send the text
resp, _ := client.Do(req)
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
var data map[string]interface{}
decoder := json.NewDecoder(resp.Body)
err := decoder.Decode(&data)
if err == nil {
fmt.Println(data["sid"])
return err
}
} else {
fmt.Println(resp.Status)
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment