Twilio SMS 发送与接收指南说明书


2024年7月3日发(作者:加气块图片)

Twilio

#twilio

Table of Contents

About

Chapter 1: Getting started with Twilio

Remarks

Versions

Examples

Sending an SMS Message from a US Number

Sending an SMS Message using Promises

1

2

2

2

2

2

3

Chapter 2: How To Receive SMS Messages with Ruby on Rails

Examples

Using the Twilio Gem

5

5

5

Chapter 3: How To Send an SMS with Ruby

Examples

Using the Twilio Gem

7

7

7

Chapter 4: Send an SMS message using Bash and cURL

Syntax

Parameters

Examples

Send a single message using an alphanumeric sender id

8

8

8

8

8

Chapter 5: Send messages in Python

Syntax

Parameters

Remarks

Examples

Sending MMS

Sending SMS

Sending messages and MMS through Twilio

10

10

10

10

10

10

11

11

Chapter 6: Sending messages in

Introduction

Parameters

Remarks

13

13

13

13

2.0 SDK Deprecation

Parameter Reference

Examples

Sending Your First Message

13

13

14

14

Installing The Node Module

Sending Your Message

14

14

Credits15

About

You can share this PDF with anyone you feel could benefit from it, downloaded the latest version

from: twilio

It is an unofficial and free Twilio ebook created for educational purposes. All the content is

extracted from Stack Overflow Documentation, which is written by many hardworking individuals at

Stack Overflow. It is neither affiliated with Stack Overflow nor official Twilio.

The content is released under Creative Commons BY-SA, and the list of contributors to each

chapter are provided in the credits section at the end of this book. Images may be copyright of

their respective owners unless otherwise specified. All trademarks and registered trademarks are

the property of their respective company owners.

Use the content presented in this book at your own risk; it is not guaranteed to be correct nor

accurate, please send your feedback and corrections to ********************

/1

Chapter 1: Getting started with Twilio

Remarks

Twilio provides a platform for communication via IP messaging (chat), video, voice, SMS and

MMS. This simple example demonstrates how to send an SMS text message using the Twilio

module for .

Versions

Version

1.0.0

Release Date

2016-04-12

Examples

Sending an SMS Message from a US Number

This is how to send an SMS text message from a US number using Twilio's SDK.

First you need to install the client using:

npm install twilio

Then, you have to create an account on their website.

Once you have an account, you'll need the account SID and auth token that you can find on the

online dashboard.

/2

In the code example below, replace

[Account SID]

and

[Auth Token]

with the ones from your

account.

// Twilio Credentials

var accountSid = '[Account SID]';

var authToken = '[Auth Token]';

//require the Twilio module and create a REST client

var client = require('twilio')(accountSid, authToken);

({

to: "+", // Any number Twilio can deliver to

from: "+", // A number you bought from Twilio and can use for outbound

communication

body: "Hey Jenny, thanks for the pull request, will merge it right away."

}, function(err, message) {

();

});

Sending an SMS Message using Promises

Twilio's API natively supports promises, allowing you to use promises when sending

SMS messages (this example was taken and adapted directly from Twilio's API Docs).

// Create an authenticated Twilio REST API client

var twilio = require('twilio');

var client = new ient('ACCOUNT_SID', 'AUTH_TOKEN');

// A simple example of sending an sms message using promises

var promise = ll({

to:'+777', // a number to call

from:'+', // a Twilio number you own

body: 'Hello, world.' // A URL containing TwiML instructions for the call

/3

});

// You can assign functions to be called, at any time, after the request to

// Twilio has been completed. The first function is called when the request

// succeeds, the second if there was an error.

promise

.then(function(sms) {

('Call success! SMS SID: ' + );

}, function(error) {

('Call failed! Reason: ' + e);

});

Read Getting started with Twilio online: /twilio/topic/443/getting-started-with-

twilio

/4

Chapter 2: How To Receive SMS Messages

with Ruby on Rails

Examples

Using the Twilio Gem

Assuming you have a Twilio account and API credentials, add the following to your Gemfile:

gem 'twilio-ruby'

Alternatively you can

gem install twilio-ruby

.

To have Twilio send an incoming SMS to a particular route in your application, you need to

configure the Messaging URL for your phone number. Once that's done, you need to set up a

route in

config/

:

TwilioSample:: do

resources :messages

end

This creates a set RESTful routes (

GET /messages

to list messages,

POST /messages

to create a

message, etc.) that will send requests to the

MessagesController

. With these routes defined, you

would set the Messaging URL in the Twilio dashboard to

/messages

as an HTTP

POST Webhook.

Your controller handles the message:

class MessagesController < ApplicationController

def create

# First, check to see if this message really came from Twilio

uri, signature = [ol, _with_port, ].join,

['HTTP_X_TWILIO_SIGNATURE']

validator = Twilio::Util::(ENV['TWILIO_AUTH_TOKEN'])

if te(uri, t_parameters, signature)

# The params hash has the data from the Twilio payload

"I just got this message from #{params[:From]}: #{params[:Body]}"

# Send back a response that Twilio can handle

render xml: { Sms: "Thanks, I got your message" }.to_xml(root: 'Response')

else

# This request didn't come from Twilio, so return a "Forbidden" response

head(403)

end

end

/5

end

Read How To Receive SMS Messages with Ruby on Rails online:

/twilio/topic/3673/how-to-receive-sms-messages-with-ruby-on-rails

/6

Chapter 3: How To Send an SMS with Ruby

Examples

Using the Twilio Gem

This assumes you have a twilio account and have purchased/reserved a

If you are using bundler add the following line to your Gemfile to include

twilio-ruby

in your

project:

gem 'twilio-ruby'

otherwise enter

gem install twilio-ruby

on the command line. You might need

sudo

if you're using

system Ruby and not ruby-env etc.

and the code

# Instantiate a Twilio REST client with your account SID and auth token,

# which can be found on your dashboard.

client = Twilio::REST::("your_account_sid", "your_auth_token")

(from: "+", to: "+", body: "Hello, world!")

Read How To Send an SMS with Ruby online: /twilio/topic/1760/how-to-send-

an-sms-with-ruby

/7

Chapter 4: Send an SMS message using Bash

and cURL

Syntax

•/{Api version}/Accounts/{AccountSid}/ {body}

Parameters

Parameter

{Api version}

{Account Sid}

{body}

Details

Versioning date of the API. e.g. 2010-04-01

The Account Sid. Starts AC

URL encoded body including From, To, Body and MessagingServiceSid

Examples

Send a single message using an alphanumeric sender id

An HTTP POST request is sent to a URL of the format: "/2xxx-xx-

xx/Accounts/[AccountSid]/

The example below uses a alphanumeric string as the sender. At the time of writing a sender ID

can only be added through a service request Twlio.

Example Request:

To="+447111111111" ;

From="Wxxxxxxxxx" ;

MessagingServiceSid="MGxxxxxxxxxxxxxxxxxxxxxx" ;

Body="Test Message" ;

AccountSid="ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ;

AuthToken="[Auth Token]" ;

CMD="curl --request POST "/2010-04-

01/Accounts/${AccountSid?}/" " ;

CMD="${CMD?}--data-urlencode "From=${From?}" " ;

CMD="${CMD?}--data-urlencode "To=${To?}" " ;

CMD="${CMD?}--data-urlencode "MessagingServiceSid=${MessagingServiceSid?}" " ;

CMD="${CMD?}--data-urlencode "Body=${Body?}" " ;

CMD="${CMD?}-u "${AccountSid?}:${AuthToken?}"" ;

echo "${CMD?}" ;

eval "${CMD?}" ;

Example Response (JSON, formatted):

/8

{

"sid":"SMxxxxxxxxxxxxx",

"date_created":"Tue, 26 Jul 2016 12:50:07 +0000",

"date_updated":"Tue, 26 Jul 2016 12:50:07 +0000",

"date_sent":null,

"account_sid":"ACxxxxxxxxxx",

"to":"+447111111111",

"from":"Wxxxxxxxxx",

"messaging_service_sid":"MGxxxxxxxxxxx",

"body":"Test Message",

"status":"accepted",

"num_segments":"0",

"num_media":"0",

"direction":"outbound-api",

"api_version":"2010-04-01",

"price":null,

"price_unit":null,

"error_code":null,

"error_message":null,

"uri":"/2010-04-01/Accounts/ACxxxxxxxxxxxx/Messages/",

"subresource_uris":{

"media":"/2010-04-01/Accounts/ACxxxxxxxxx/Messages/SMxxxxxxxxxxxx/"

}

}

Read Send an SMS message using Bash and cURL online:

/twilio/topic/4237/send-an-sms-message-using-bash-and-curl

/9

Chapter 5: Send messages in Python

Syntax

•class es(*args, **kwargs)

Parameters

Parameter

to (str)

from_ (str)

body (str)

status_callback

application_sid

(str)

Details

The destination phone number.

The phone number sending this message (must be a verified Twilio

number)

The message you want to send, limited to 160 characters.

A URL that Twilio will POST to when your message is processed.

The 34 character sid of the application Twilio should use to handle this

phone call.

Remarks

Twilio will send SMS messages for long codes (in the US, a regular ten digit number) at a rate of

one message per second. For additional throughput, you can use pools of numbers with Copilot or

apply for a shortcode, which can send 30 messages or more per second.

Examples

Sending MMS

You can add an image to your message using the parameter

media_url

.

# Download the twilio-python library from /docs/libraries

from import TwilioRestClient

# Find these values at /user/account

account_sid = "ACXXXXXXXXXXXXXXXXX"

auth_token = "YYYYYYYYYYYYYYYYYY"

client = TwilioRestClient(account_sid, auth_token)

message = (

to="+",

from_="TWILIO_NUMBER",

body="Hello there, StackOverflow!",

media_url=[

/10

'/',

'/'])

Sending SMS

To send your first SMS with Twilio and Python you'll just need the Twilio-Python helper library to

get started.

# Download the twilio-python library from /docs/libraries

from import TwilioRestClient

# Find these values at /user/account

account_sid = "ACXXXXXXXXXXXXXXXXX"

auth_token = "YYYYYYYYYYYYYYYYYY"

client = TwilioRestClient(account_sid, auth_token)

message = (to="+", from_="TWILIO_NUMBER",

body="Hello there, StackOverflow!")

Sending messages and MMS through Twilio

Twilio help build apps that communicate with everyone in the world. Voice & Video, Messaging

and Authentication APIs for every application.

You can get an API key for free.

To send a message through Twilio, your application needs to make an HTTP POST request to

Twilio with the following things:

1. The phone number you want to send the message to.

2. Twilio number from which you’re attempting to send the message. (Only Twilio message-

enabled phone numbers will work)

3. The body of the message.

To send an SMS, make an HTTP POST request to the Messages resource.

POST /20xx-xx-xx/Accounts/xxxxxxx/Messages

Below is an example code to show how sending messeges with Twilio API will work.

# Download the twilio-python library from /docs/libraries

from import TwilioRestClient

# Find these values at /user/account

account_sid = "ACXXXXXXXXXXXXXXXXX"

auth_token = "YYYYYYYYYYYYYYYYYY"

client = TwilioRestClient(account_sid, auth_token)

message = (

to = "+",

from_ = "+",

/11

body = "Hello there!"

)

If the Twilio number supports MMS, then you can send and receive MMS also.

Below is code to send MMS through Twilio API.

message = (

to = "+",

from_ = "+",

body = "Hello there!",

media_url=[

'/',

'/'

])

Read Send messages in Python online: /twilio/topic/579/send-messages-in-

python

/12

Chapter 6: Sending messages in

Introduction

Twilio allows you to send and receive text messages with by using the twilio-node library

to make calls. This guide assumes you've already setup an account with Twilio and have your

account SID and the authentication token from the Twilio Console.

Parameters

Parameter

to

from

body

StatusCallback

maxPrice

validityPeriod

provideFeedback

mediaUrl

Details

A valid phone number to receive the message

A Twilio number that is assigned to you

The body of the text message limited to 1600 characters

A URL that Twilio posts to when a message status changes

Set the maximum price of a message

The number of seconds the message will remain in the Twilio queue

Boolean value, when set to true

A URL containing a gif, png or jpeg content that will be sent with the

message

Remarks

2.0 SDK Deprecation

Twilio has two versions of the twilio-node module, a 2.0 SDK and a 3.0 SDK. It is recommended to

use the 3.0 SDK as the 2.0 SDK will be deprecated on the 8/31/2017.

Deprecation notice: New functionality will only be added to the new library (Node

Helper Library 3.x). The old library (2.x) will be officially supported until 8/31/2017. After

that day, Twilio will stop providing bug fixes and Support might ask you to upgrade

before debugging issues. /docs/libraries/node

Parameter Reference

/13

You can refer to the Twilio REST documents for a more detailed description. Twilio also has a

JSdocs which can be used as a reference.

Examples

Sending Your First Message

Installing The Node Module

You can install this module by running the command below in your project directory:

npm install twilio

Sending Your Message

const accountSID = ''; // Obtained from the Twilio Console

const authToken = ''; // Obtained from the Twilio Console

const client = require('twilio')(accountSID, authToken);

({

to: '', // Number you want to send to

from: '', // From a valid Twilio number

body: 'Hello, from Stack Overflow', // What appears in the text message

})

.then((message) => ());

Read Sending messages in online: /twilio/topic/9955/sending-

messages-in-node-js

/14

Credits

S.

No

1

Chapters

Getting started with

Twilio

How To Receive

SMS Messages with

Ruby on Rails

How To Send an

SMS with Ruby

Contributors

Adam, cdock, Community, ddoria921, Kevin Whinnery,

msmanek, Sven

2Benjamin Curtis

3derrek, Steve Graham

4

Send an SMS

message using Bash antonycc

and cURL

Send messages in

Python

Sending messages

in

anthon, Henk Langeveld, Jacob Budin, Megan Speir, Shubham

Gupta

Matt Shirley

5

6

/15