Reputation: 999
I'm having a tough time understanding Twilio. I've read the docs, and plan to read them again, but I was hoping for some pointers. I am using Ruby on Rails for my application.
What I want to do is to be able to receive a text message from a user with some body text. Then, I want to be able to save that text in my model some how. How do I go about doing this?
Thank you!
Upvotes: 4
Views: 2035
Reputation: 3369
If you're using Node Express, here's a snippet that worked for me:
app.post('/respondToMessage', function(req, res) {
var twiml = new twilio.TwimlResponse();
console.log('sms message =', req.body.Body);
twiml.message('respondToMessage');
res.type('text/xml');
res.send(twiml.toString());
});
You're parsing for the JSON attribute Body from a response that usually looks like this:
{
"ToCountry": "",
"ToState": "",
"SmsMessageSid": "",
"NumMedia": "",
"ToCity": "",
"FromZip": "",
"SmsSid": "",
"FromState": "",
"SmsStatus": "",
"FromCity": "",
"Body": "The attribute you're parsing for",
"FromCountry": "",
"To": "",
"MessagingServiceSid": "",
"ToZip": "",
"NumSegments": "",
"MessageSid": "",
"AccountSid": "",
"From": "+",
"ApiVersion": ""
}
Upvotes: 0
Reputation: 336
You can get the body of an sms message just like you would get the content from a textbox in a web application. In python, it would be
mybody = request.args.get('body')
Upvotes: 0
Reputation: 1790
user2515526,
Recently I set up my first Rails app that draws upon some Twilio Functionality - primarily that of receiving, processing, and responding to SMS messages - and I agree: from a noob's perspective, the Twillio documentation can definitely be cleared up ^^.
I found this git repo to be extremely helpful. The guy essentially walks you through pretty much all you need to know to get up and running.
Upvotes: 1
Reputation: 18037
The Twilio number can be associated with a callback URL which it will send a POST request to when it receives an SMS. This callback URL should be customized to point to a controller in your app that you will use for processing SMS. From there, you can just read the params hash for details of the SMS message received. Of note: params['From']
and params['Body']
. Store the text from those params into any model you like!
Twilio Callback URL
http<s>://<your domain.com>/sms
Route
resource :sms, only: :create
Controller
class SmsController < ApplicationController
skip_before_filter :force_ssl # You may need this if your app uses https normally
def create
# Do something with params['From'] -- contains the phone number the SMS came from
# Do something with params['Body'] -- contains the text sent in the SMS
# <Reponse/> is the minimum to indicate a "no response" from Twilio
render xml: "<Response/>"
end
end
Upvotes: 5