Verify message was sent with Twilio - Python - python

I have a small script that sends text messages with Twilio using Python.
This is my code:
import os
from twilio.rest import Client
account_sid = os.environ.get('TWILIO_ACCOUNT_SID')
auth_token = os.environ.get('TWILIO_AUTH_TOKEN')
client = Client(account_sid, auth_token)
cell_number = os.environ.get('CELL_PHONE_NUMBER')
text_message = input("Enter a message to send: ")
send_message = client.messages.create(from_=os.environ.get('TWILIO_PHONE_NUMBER'),
to=cell_number,
body=text_message
print(send_message)
And this is the response I get back:
<Twilio.Api.V2010.MessageInstance account_sid=MY_ACCOUNT_SID sid=SMc5e8f335198144b4b3c7f401af511f11>
I was wondering what the best way was to validate that the message was actually sent in code.
I thought of doing something like this:
if send_message:
print("Message sent.")
else:
print("Message not sent.")
And I was just wondering if there was a better way to do that.

I understand that this is a relatively old question and you might have figured out a way to achieve the desired behavior, but just wanted to post my thoughts so that it may help other learners like me in the future.
So basically, twilio provides developers with a functionality of webhooks using which the status of messages can be tracked. You will have to provide an extra parameter while creating the message wherein you will have to pass the callback url pointing to a server which will be logging the status of the sent messages.
When your python script sends a SMS by doing a POST request to twilio server, twilio will send the status of the message to the callback URL as a parameter by making a post or a get request.
This document describes how to achieve the above behavior with the help of example code snippets. In case you used another method to track the status of the messages, let us know so that it will help the community.

Related

Put <Gather> result in variable in twilio.rest

So, i have this code:
import os
from twilio.rest import Client
xml=f'''
<Response>
<Say language="ru-RU">Здравствуйте, пожалуйста введите код для подтверждения.</Say>
</Response>'''
account_sid = ('AC274461ad47988c753424a3c8735dbcc1')
auth_token =('8ac88e8d5bce419ae3b5cbac4fc255f9')
client = Client(account_sid, auth_token)
call = client.calls.create( twiml=xml,
to='+375336412273',
from_='+12318247004',
)
print(call.sid)
I want to put in xml, that way, so i could put result of (what user typed in) in variable.
I want to do it only with python and twilio.rest, on twilio site i only found how to do it with flask, url and twiml.
Twilio developer evangelist here.
In order to be able to run interactive phone calls, there needs to be a way for your application to give instructions to Twilio, receive responses and then give further instructions. The instructions are the TwiML that you send to Twilio, but the way that Twilio communicates things back to you, like the result of what a user typed during a <Gather>, is via webhooks. Webhooks are HTTP requests from Twilio that include data about the call, like user input, in the body of the request.
To use that data and provide Twilio with further TwiML instructions your application needs to be able to receive HTTP requests and respond with an HTTP response containing the TwiML.
There are example in the Twilio documentation using Flask because Flask is a good way to receive and respond to HTTP requests in Python. You could build an application without a framework like Flask, but you would still need to be able to receive an incoming HTTP request and respond to it.

Twilio trigger Python function on SMS receive

Utilizing Twilio, upon receiving any SMS I'm seeking to trigger a Python function that reads the contents of the message, then conditionally performs an action.
I'm referencing from Twilio docs right now (.py):
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
message = client.messages('MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch()
print(message.to)
Does anyone know how to automatically set up a trigger OnReceive?
The example you show fetches a known message (a message that has already been received and you know its ID).
In order to have a script that is triggered by incoming message you need to setup a webhook and you need to have an endpoint (server) where you can pick up a trigger sent to you by twilio (eg at www.yourdomain.com/sms).
You might not be able to do it just from within a raspbery pi connected to the internet. You need to setup a trigger somewhere on a server, store the incoming messages somehow and then one solution would be to keep polling the server from raspberry pi, fetching new messages and clearing the list.

Receiving and processing an SMS with Twilio in Python

I'm learning python and as a project I'm trying to create a program that will recieve an SMS message, process it, and then depending on what is in that message, send back information.
I am using Twilio in python with Flask and ngrok to do all the SMS stuff, but I am still not sure how to actually receive an SMS as data that I can read and process, as there is no documentation that I can find on it. It would be great if someone could help me with this.
I already know how to receive and send SMS with Twilio, I just need to know how to get the precise message that was sent to my Twilio number.
I believe you already know how to configure Twilio to hit your endpoint when a message comes in. If you configure at Twilio for a POST request, then the data passed to you from Twilio will be in request.form.
If you take a look at Twilio's example here:
(https://www.twilio.com/docs/sms/tutorials/how-to-receive-and-reply-python)
indeed the example makes no use of the data that is coming in.
The modified code below shows some data that is available from the request (and you can write your code depending on what you'd like to do with it).
the number from where the message was sent request.form['From'],
your Twilio number request.form['To']
and the body of the message request.form['Body']
from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse
app = Flask(__name__)
#app.route("/sms", methods=['POST'])
def sms_reply():
"""Respond to incoming calls with a simple text message."""
# Use this data in your application logic
from_number = request.form['From']
to_number = request.form['To']
body = request.form['Body']
# Start our TwiML response
resp = MessagingResponse()
# Add a message
resp.message("The Robots are coming! Head for the hills!")
return str(resp)
if __name__ == "__main__":
app.run(debug=True)
Some other parameters are also available in the request:
MessageSid
SmsSid
AccountSid
MessagingServiceSid
From
To
Body
NumMedia
Docs: (https://www.twilio.com/docs/sms/twiml#request-parameters)
Also you can find more examples if you google for "twilio blog python flask"

SMS with Twilio Test Credential does not work

I am using Twilio Test crredentials o send a sample SMS message to my phone number which is already verified. When I run this script, it returns an SID and seems to work as expected only that I never receive the ext.. What am I missing?
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "AC3196c6a6fchha5de2c64a57e453e8e4b35"
auth_token = "fa1b7f6fdf3384ece5f5eda67cf7b42e28b"
client = Client(account_sid, auth_token)
message = client.messages.create(
to = "+12068515737",
from_ = "+15005550006",
body = "Jenny please?! I love you <3")
print(message.sid)
Twilio developer evangelist here.
That is the expected result when using test credentials. They are supposed to behave like real credentials, but never actually cause a message to be sent, or the call to be made or number to be bought. They are just for testing that the HTTP request was made correctly.
To send a message, you should use your real credentials. If you still have a trial account and a verified number, then you can send a message to that verified number using your trial account and it won't cost you anything. Only once you upgrade your account and add credit yourself will it cost to send an SMS message.
Let me know if that helps at all.

How to send customized reposne using Twilio API?

I am new to Twilio API and I am calling to a number and I want to play a customized message. Can anyone tell me how to do it? I know that I have to create a response file but I am not sure how to give that file in URL.
Here is my code.
# Download the library from twilio.com/docs/libraries
from twilio.rest import TwilioRestClient
# Get these credentials from http://twilio.com/user/account
account_sid = "xxxxxx"
auth_token = "yyyyyy"
client = TwilioRestClient(account_sid, auth_token)
# Make the call
call = client.calls.create(to="aaaaa", # Any phone number
from_="bbbbb", # Must be a valid Twilio number
url="??????")
print call.sid
What should I write in URL?
Thanks
Twilio developer evangelist here.
There are a couple of things you can do here. The url you enter in the outgoing call needs to respond with some XML (TwiML) when Twilio requests it.
If you want Twilio to play a message, you could write the following TwiML:
<Response>
<Say>Hello from my new Twilio app</Say>
</Response>
This can be a static file hosted anywhere. For example, you could use http://twimlbin.com/ to host it and then use the url given to you by that service.
Alternatively, you could create a webserver application using something like Python's Flask. There is a guide to this on the Twilio site here: https://www.twilio.com/docs/quickstart/python/twiml/say-response. You can then open your local development site to Twilio using a tool like ngrok and there's a good explanation of how to do that in this blog post: https://www.twilio.com/blog/2013/10/test-your-webhooks-locally-with-ngrok.html.
Hope that helps, let me know if there's anything more I can help you with.

Categories

Resources