Put <Gather> result in variable in twilio.rest - python

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.

Related

Twilio Whatsapp Sandbox Configuration for deploying application via AWS elastic beanstalk

enter image description here
Currently I am developing a chatbot for my application with django, using a twilio trial account.
The chatbot functions properly with ngrok.io, i.e. when the server is operating locally, which mean that when I send a whatsapp message to the twilio sandbox with operation of simply "python manage.py runserver", he will automatically reply me according to my script.
However, as I started deploying the application using the AWS elastic beanstalk, I found that it is only possible for the sandbox to send out whatsapp message by POST request on the web application, but not capable to respond to POST request sent out from whatsapp.
In what way I can deal with it? Is it related to AWS settings or Twilio settings? Some CORS related issues?
Great thanks in advance.
(Please forgive me if my use of language is not accurate as I am not with computer science background.)
Below is part of the code that I applied.
#csrf_exempt
def message(request):
account_sid = 'xxx'
auth_token = 'xxx'
client = Client(account_sid, auth_token)
client_phone_number = request.POST.get('From').removeprefix("whatsapp:+852")
client_phone_number.removeprefix("+852")
incoming_message = request.POST.get('Body')
conversation_sid = request.POST.get('conversation_sid')
incoming_message = incoming_message.lower()
response = MessagingResponse()
#processing the incoming message to produce the text
resp = "text"
response.message(resp)
return HttpResponse(str(response))
I have tried pasting https://xxxxx-env.yyyyyyy.us-east-1.elasticbeanstalk.com/whatsapp/ to the sandbox configuration cell as shown in the image and it resulted to what I mentioned above. The whatsapp url is set just like typically done for other urls for django, followed by message(request) to process the request sent out from the whatsapp. Any other proper way I can do it?

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.

Must I always use `url` field in making outbound calls with Twilio API in Python?

I've been trying to figure out how to make outbound call to leave a voicemail when answering machine is detected. I'm still in the beginning of the exploration and been trying to follow Twilio example like this. I want to use Python, so I'm copy-pasting the example from Twilio below:
# 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
# DANGER! This is insecure. See http://twil.io/secure
account_sid = 'your account sid'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
call = client.calls.create(
url='http://demo.twilio.com/docs/voice.xml',
to='+1555123456',
from_='+1501123456'
)
print(call.sid)
In the above code, it seems like Twilio's Python SDK always expects url (publicly available XML file/response) as resource to ping to. I'm wondering if I can build a valid XML (TwiML) file and refer to it in the above client.calls.create(...) call. In other words, how do I make Twilio 'speak' what I designed in my local (on my computer) XML file (if that's even possible)? I only plan to run my Python script from my personal computer on need basis, and I don't have any access to server anywhere.
Thank you in advance for your answer/suggestion!
A publicly accessible URL is a requirement. You can use Twilio Studio or Twilio Serverless Functions if you want Twilio to host your logic so you don't need to expose a public URL.
For development, you can use a tool called Ngrok, which will tunnel the Twilio TwiML request to your private application.
You can find more detail here.
How to test webhooks locally with ngrok - Twilio Tip #6
Well you could test this about by using pythons simple http server. and just have it server that file.
curl http://demo.twilio.com/docs/voice.xml -o voice.xml
python -m SimpleHTTPServer
#run to above commands then
#try using bellow?
call = client.calls.create(
url='http://localhost:8000/voice.xml',
to='+1555123456',
from_='+1501123456'
)
#the file at that location is dead simple
<Response>
<Say voice="alice">Thanks for trying our documentation. Enjoy!</Say>
<Play>http://demo.twilio.com/docs/classic.mp3</Play>
</Response>

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"

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