Can't get status of sms from Twilio - python

I had some issue when works with Twilio API. I tried to get sms status as is delivered, queue, failed or another, but I couldn't find this method at Rest API.
I use Python and Django.
def send_sms(self, msg):
ACCOUNT_SID = self.profile.twilio_sid
AUTH_TOKEN = self.profile.twilio_auth_token
client_phone_number = self.profile.phone_number
twilio_phone_number = "+1"+str(self.profile.twilio_number)
client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)
message = client.messages.create(
body=msg,
to=client_phone_number,
from_=twilio_phone_number,
)
sid = message.sid
So how can I get sms status with sid what i have? Without response processing if it is possible
I found answer. All what I need is added to my code
body = client.messages.get(sid)
status =body.status

Twilio evangelist here.
To get an individual instance resource, use resources.ListResource.get(). Provide the sid of the resource you’d like to get.
msg = client.messages.get(sid)
print msg.to
You could also provide a status callback URL when you sent the message to have Twilio notify you via a webhook request when the message status changes:
https://www.twilio.com/docs/api/rest/sending-messages#post-parameters-optional
Hope that helps.

I found answer. All what I need is added to my code
body = client.messages.get(sid)
status = body.status

Message message = twilio.GetMessage(messageSid);

Related

Verify message was sent with Twilio - 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.

Inserting Twillio message history into data structure or text file

I have extracted my message history from Twillio - it prints it to python's shell. However, I cannot find a reasonable way to place it into a data structure or a text file for further analysis of the messages. My account sid and account token are hidden just for this post. Nothing is written to my txt file either.
from twilio.rest import Client
account_sid = 'XXXX'
auth_token = 'XXXX'
client = Client(account_sid, auth_token)
from twilio.twiml.messaging_response import Message, MessagingResponse
from flask import Flask, request, redirect
app = Flask(__name__) #creating a flask app
#app.route("/sms", methods=['GET', 'POST']) #creating an sms route
def sms_reply():
"""Respond to incoming calls with a simple text message."""
# Start our TwiML response
resp = MessagingResponse()
# Add a message
resp.message("The Robots are coming! Head for the hills!")
return str(resp)
text = []
messages = client.messages.list()
for record in messages:
text.append(record.body.encode("utf-8"))
My message history:
Sent from your Twilio trial account - Your verification code is: 219042
Test
Twilio developer evangelist here.
As my teammate Phil mentioned above, you seem to be conflating responding to an incoming webhook with hitting the API and fetching message history.
These Twilio docs mention how to retrieve message history in Python.
The following code writes message history to a .txt file called "chathistory.txt".
from twilio.rest import Client
account_sid = 'XXXX'
auth_token = 'XXXX'
client = Client(account_sid, auth_token)
messages = client.messages.list(limit=20)
writetofile = open("chathistory.txt", 'w')
for record in messages:
print(record.body)
writetofile.write(record.body + '\n')
writetofile.close()
Let us know if this helps at all!

Twilio SMS Python - Simple send a message

New to Twilio, have followed the SMS Python Quickstart guide successfully, and have combined two bits together, but now have some redundant code that I can't seem to get rid of without getting errors.
I have Python code that takes in coordinates from a text message, converts this into a Google Maps link, and sends that link to a different phone number.
However, currently it is also sending this reply to the original sender phone number, as that is what the original guide has you set up.
I only want it to send the message to the specified number, not reply to the original sender.
run.py:
# /usr/bin/env python
# Download the twilio-python library from twilio.com/docs/libraries/python
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
# 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 = 'account_sid'
auth_token = 'auth_token'
client = Client(account_sid, auth_token)
app = Flask(__name__)
#app.route("/", methods=['GET', 'POST'])
def sms_reply():
messages = client.messages.list()
print(messages[0].body)
coord = messages[0].body
lat,lon = coord.split(":")
mapURL = "https://www.google.com/maps/search/?api=1&query=" + lat + "," + lon
message = client.messages.create(
body=mapURL,
from_='+442030954643',
to='+447445678954'
)
"""Respond to incoming messages with a friendly SMS."""
# Start our response
resp = MessagingResponse()
# Add a message
resp.message(mapURL)
return str(resp)
if __name__ == "__main__":
app.run(debug=True)
Whenever I take out the lines I think are to do with the replying message to sender, it seems to break some of the other lines that I still need.
Any help much appreciated, thanks!
Twilio developer evangelist here.
You don't need to reply back to the incoming message and you can avoid this by returning an empty TwiML response.
As an extra win here, you don't have to call the API to get the body of the last message that was sent. That will be available in the POST request parameters to the endpoint. You can access those via request.form so the Body parameter will be available at request.form['Body'].
Try something like this:
# /usr/bin/env python
# Download the twilio-python library from twilio.com/docs/libraries/python
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
# 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 = 'account_sid'
auth_token = 'auth_token'
client = Client(account_sid, auth_token)
app = Flask(__name__)
#app.route("/", methods=['GET', 'POST'])
def sms_reply():
coord = request.form['Body']
lat,lon = coord.split(":")
mapURL = "https://www.google.com/maps/search/?api=1&query=" + lat + "," + lon
message = client.messages.create(
body=mapURL,
from_='+442030954643',
to='+447445678954'
)
# Start our empty response
resp = MessagingResponse()
return str(resp)
if __name__ == "__main__":
app.run(debug=True)
It's because your output in your sms_reply function is returning a TwiML that sends a message. I think it's normal to have some feedback from the service. If you don't want to reply with the mapURL you can just say somethink like "Thank you".
Otherwise, you can take a look to TwiML documentation to see what other actions you can do.

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.

Categories

Resources