Simple code to receive SMS from Twilio

I don’t know enough about the twilio api to help with (1) - how about you print the t.From value and see what it is from different phones?, but on (2) that doesn’t look like enough code.

All you’re doing it going to sleep for 5 seconds when you get sent a message. There are no other actions happening there, and nothing being done with “value” (which will be the body of the message from twilio forwarded by the agent code)

Good point – sbright33, is that the entirety of the agent code, or do I also need to configure the connection as in the following (it seems like I would, but this code is for posting, and I’m looking to receive only – so far):
`// Agent code
const TWILIO_ACCOUNT_SID = "your-twilio-account-goes-here"
const TWILIO_AUTH_TOKEN = "your-twilio-auth-token-goes-here"
const TWILIO_FROM_NUMBER = “+12015551212” // your phone no goes here
const TWILIO_TO_NUMBER = “+14085551212” // destination phone no

function send_sms(number, message) {
local twilio_url = format(“https://api.twilio.com/2010-04-01/Accounts/%s/SMS/Messages.json”, TWILIO_ACCOUNT_SID);
local auth = “Basic " + http.base64encode(TWILIO_ACCOUNT_SID+”:"+TWILIO_AUTH_TOKEN);
local body = http.urlencode({From=TWILIO_FROM_NUMBER, To=number, Body=message});
local req = http.post(twilio_url, {Authorization=auth}, body);
local res = req.sendsync();
if(res.statuscode != 201) {
server.log("error sending message: "+res.body);
}
}`

Ah… figured that part out - setting my Twilio #s Messaging Response URL to my imp URL is what I needed to do to receive SMS - no credentials required!

I have been going nuts trying to figure out how to get the SMS to send via the agent code. No matter what I do, I get an error from Twilio that the “From” number is wrong. I know the phone numbers have been validated, my authorization is good, etc. because I can use Curl from the command line to make Twilio send an SMS. For my agent code, I am using the send_sms() example above.

No matter what, I get this:
{“code”: 21212, “message”: “The ‘From’ number 12167778433 is not a valid phone number or shortcode.”, “more_info”: “https://www.twilio.com/docs/errors/21212”, “status”: 400}

Has anyone tested that code recently?

Any help? Thanks!

Dumb question but I’ll ask it anyway. Your are placing country code at the start of the no your txting e.g. +1 for US or +44 UK

rubinstu I just spent an hour trying to figure out the same thing only to realize I forgot the 1 for my twilio number - could you post your actual code (with auth token removed obviously) and I’ll see if I can help at all!

Had problem with the code above, but read this on twillio page :slight_smile:

If you received this error while trying to authenticate with your Test Credentials, you probably tried to send a message with a From number from your live account. The only number that can be used to send successful messages with your Test Credentials is +15005550006. For more information, read our documentation on the From number for sending SMS with your test credentials.

but it didn’t help :smiley: :smiley:
Still have troubles with:

The From phone number +15005550006 is not a valid, SMS-capable inbound phone number or short code for your account.

Your FROM number is the number that is assigned to you by Twilio. For example, I live in the 717 area code in PA, and my Twilio number starts with +1717.

I have the same error with the assigned number from the numbers page :confused:

Hi Guys,
I’m new to Electric Imp and have completed my first project with it (Receiving SMS notifications from your Washing Machine).
http://alexba.in/blog/2014/01/06/receiving-sms-notifications-from-your-washer/
The sms function was not working and have used the above code as a replacement.

Just some of the gotchas to be aware of with SMS and Twilio I have found are:

  1. The SMS function used by alexbain has been deprecated by Twilio so I wasnt able to use it (even though the code compiled fine and I wasn’t using a trial account. Use the function posted above (Thanks fduncan for the code!)

  2. The code
    "local twilio_url = format(“https://api.twilio.com/2010-04-01/Accounts/%s/SMS/Messages.json”, TWILIO_ACCOUNT_SID);"
    has a typo in it it should be:
    local twilio_url = format("https://api.twilio.com/2010-04-01/Accounts/%s/SMS/Messages.json&quot, TWILIO_ACCOUNT_SID);

  3. “If you are sending messages while in trial mode, the ‘To’ phone number must be verified with Twilio.” As I’m in Australia and wanted this solution for a long time needed to upgrade my account to use this even for testing.
    https://www.twilio.com/docs/api/rest/sending-messages#post

  4. The test SMS function doesnt actually send an SMS it just tests your API request
    "If you’d like to test API requests to send SMS messages without charging your account or sending an SMS, you can use your test credentials.
    https://www.twilio.com/docs/api/rest/test-credentials

Hope this helps anyone with there SMS Twilio testing.

Weh’ve had good luck with the Twilio class posted in Electric Imp’s Reference Repo:

https://github.com/electricimp/reference/blob/master/webservices/twilio/twilio.agent.nut

I don’t think anything has changed, so that’s another option for anyone working with Twilio :slight_smile:

Very nice! Any plans to implement the X-twilio-signature hash checking (see https://www.twilio.com/docs/security?

I don’t think anyone over here is actively using Twilio, the agent I linked to is a cleaned up version of some old Twilio code we had. If you’re interested in the X-twilio-signature hash checking I would encourage you to take a stab at it and then do a pull request :slight_smile:

As long as you promise not to laugh at my coding skills :slight_smile:

I did capture the headers and body of the http request as a first step. As far as I can tell, there are no values in the query table (which I assume means the URL Twilio sends is simply https://agent.electricimp.com/{agentID}/twilio). The SMS information is in the body of the request, so that makes sense. Yet when I tried to manually hash the url above with my AuthToken, the result didn’t match X-twilio-signature. Obviously, I either misunderstand the hashing process, the http request URL, or life in general. Possibly all three.

I’ll keep trying and keep you posted.

OK, it’s not very pretty, but it seems to work. Comments more than welcomed!

`
function compareTwilio(reqBody, twilioSignature){
local bodyPOST = [];
local postString = “”

foreach(idx, val in reqBody){
       bodyPOST.append(idx + val);
}   

bodyPOST.sort();

foreach(postVariable in bodyPOST){
    postString += postVariable;
}     

return (twilioSignature == (http.base64encode(http.hash.hmacsha1("https://agent.electricimp.com/MY_ID_HERE/twilio" + postString, "MY_TWILIO_KEY_HERE"))));

}`

Sorry about the &quot

It’s a bit off topic, but if you wish to send email instead of SMS, use the service Mailgun. The programming is almost the same:

// Function for sending Email via MailGun
function sendEmailMailGun(subject, message)
{
local from = MAILGUN_FROM_EMAIL;
local to = MAILGUN_TO_EMAIL;
local apikey = MAILGUN_API_KEY;
local domain = MAILGUN_DOMAIN;
local req = http.post(“https://api:” + apikey + "@api.mailgun.net/v2/" + domain + “/messages”, {“Content-Type”: “application/x-www-form-urlencoded”}, “from=” + from + “&to=” + to + “&subject=” + subject + “&text=” + message);
local res = req.sendsync();

//server.log(auth);
if(res.statuscode != 200)
{
    server.log("Error " + res.statuscode + " sending Email message (MailGun): " + res.body );
} else {
    server.log("Sent Email Door State (MailGun): " + a_currentDoorState );
}

}