SMS with Twilio – Examples

Once you’ve signed up for an account with Twilio, you can start to send and receive SMS.

Sending SMS

Sending SMS is easy if you have the Twilio Ruby Gem.  The following code is straight from Twilio’s API Explorer: https://www.twilio.com/user/account/developer-tools/api-explorer

#!/usr/bin/env ruby
require 'twilio-ruby'

@account_sid = # your account SID here
@auth_token = # your authtoken here
@from_number = # your twilio phone number here
@to_number = # the number that will receive the sms
# set up a client to talk to the Twilio REST API
@client = Twilio::REST::Client.new(@account_sid, @auth_token)

@account = @client.account
@message = @account.messages.create({:from => @from_number, :to => @to_number, :body => 'This is a message from Twilio!'})
puts @message

Sending MMS (or mobile media) is as easy as including a URL to the media in your twilio message:

@message = @account.messages.create({ :from => @from_number,
 :to => @to_number,
 :body => "Here\'s my mood.",
 :media_url => "http://i.imgur.com/VE6KwSq.jpg" })

Receiving SMS
Receiving an SMS (and MMS) is more difficult.  Since you don’t know when an SMS will be sent to you, Twilio will want to forward the SMS message to you when it is received by their service.  Specifically, Twilio will want to post the info to an HTTP server. A Sinatra web app would be a great option.

Twilio has some documentation here: http://www.twilio.com/docs/quickstart/ruby/sms/hello-monkey

However, if you simply want to handle the contents of the SMS, then you can pull that information out of the params[].  For example, params[‘Body’] will contain the SMS message, and params[‘From’] will contain the phone number of the person who sent the SMS.

Twilio needs to know the URL that you’d like to use for incoming SMS.  Click on the phone number that will receive SMS and fill in your URL in the field labeled “SMS Request URL”.

twilio-sms-request

I have put together a sample Sinatra web app that will send and receive SMS.  You can view and clone the code from the Redial github account:

https://github.com/itp-redial/twilio-demo

More info on Twilio’s new MMS capability: https://www.twilio.com/blog/2014/09/getting-started-with-twilio-mms.html