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.
Related
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?
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.
I would like to use Twilio Whatsapp messages with custom templates. I'm trying to send messages using a Python client. We have different types of messages and we would like to manage them from Twilio backend. We created several templates, but I have no idea how to specify a template in the code.
In the official documentation there is no mention of this. I looked into the source code of the client, here is a code from class MessageList, that I use for message creation:
def create(self, to, status_callback=values.unset, application_sid=values.unset,
max_price=values.unset, provide_feedback=values.unset,
attempt=values.unset, validity_period=values.unset,
force_delivery=values.unset, content_retention=values.unset,
address_retention=values.unset, smart_encoded=values.unset,
persistent_action=values.unset, from_=values.unset,
messaging_service_sid=values.unset, body=values.unset,
media_url=values.unset):
There is nothing similar to the template name in function parameters.
Is it possible at all to specify the template programmatically?
Twilio developer evangelist here.
When you want to send a message using a template, all you have to do is ensure that the body of the message you are sending matches the template. For example, if your templates is:
Your login code for {{1}} is {{2}}.
Then sending the message:
Your login code for Twilio is 12345.
matches that template and will send successfully. So you don't specify the template programmatically, just with your message content.
You can see more about sending template messages with the Twilio API for WhatsApp here.
from twilio.rest import Client
client = Client() # this is the Twilio sandbox testing number
from_whatsapp_number = 'whatsapp:+14155238886'
to_whatsapp_number = 'whatsapp:+15005550006'
client.messages.create(body='Ahoy,world!', from_=from_whatsapp_number, to=to_whatsapp_number)
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>
I created 2 applications in my Azure directory, 1 for my API Server and one for my API client. I am using the Python ADAL Library and can successfully obtain a token using the following code:
tenant_id = "abc123-abc123-abc123"
context = adal.AuthenticationContext('https://login.microsoftonline.com/' + tenant_id)
token = context.acquire_token_with_username_password(
'https://myapiserver.azurewebsites.net/',
'myuser',
'mypassword',
'my_apiclient_client_id'
)
I then try to send a request to my API app using the following method but keep getting 'unauthorized':
at = token['accessToken']
id_token = "Bearer {0}".format(at)
response = requests.get('https://myapiserver.azurewebsites.net/', headers={"Authorization": id_token})
I am able to successfully login using myuser/mypass from the loginurl. I have also given the client app access to the server app in Azure AD.
Although the question was posted a long time ago, I'll try to provide an answer. I stumbled across the question because we had the exact same problem here. We could successfully obtain a token with the adal library but then we were not able to access the resource I obtained the token for.
To make things worse, we sat up a simple console app in .Net, used the exact same parameters, and it was working. We could also copy the token obtained through the .Net app and use it in our Python request and it worked (this one is kind of obvious, but made us confident that the problem was not related to how I assemble the request).
The source of the problem was in the end in the oauth2_client of the adal python package. When I compared the actual HTTP requests sent by the .Net and the python app, a subtle difference was that the python app sent a POST request explicitly asking for api-version=1.0.
POST https://login.microsoftonline.com/common//oauth2/token?api-version=1.0
Once I changed the following line in oauth2_client.py in the adal library, I could access my resource.
Changed
return urlparse('{}?{}'.format(self._token_endpoint, urlencode(parameters)))
in the method _create_token_url, to
return urlparse(self._token_endpoint)
We are working on a pull request to patch the library in github.
For the current release of Azure Python SDK, it support authentication with a service principal. It does not support authentication using an ADAL library yet. Maybe it will in future releases.
See https://azure-sdk-for-python.readthedocs.io/en/latest/resourcemanagement.html#authentication for details.
See also Azure Active Directory Authentication Libraries for the platforms ADAL is available on.
#Derek,
Could you set your Issue URL on Azure Portal? If I set the wrong Issue URL, I could get the same error with you. It seems that your code is right.
Base on my experience, you need add your application into Azure AD and get a client ID.(I am sure you have done this.) And then you can get the tenant ID and input into Issue URL textbox on Azure portal.
NOTE:
On old portal(manage.windowsazure.com),in the bottom command bar, click View Endpoints, and then copy the Federation Metadata Document URL and download that document or navigate to it in a browser.
Within the root EntityDescriptor element, there should be an entityID attribute of the form https://sts.windows.net/ followed by a GUID specific to your tenant (called a "tenant ID"). Copy this value - it will serve as your Issuer URL. You will configure your application to use this later.
My demo is as following:
import adal
import requests
TenantURL='https://login.microsoftonline.com/*******'
context = adal.AuthenticationContext(TenantURL)
RESOURCE = 'http://wi****.azurewebsites.net'
ClientID='****'
ClientSect='7****'
token_response = context.acquire_token_with_client_credentials(
RESOURCE,
ClientID,
ClientSect
)
access_token = token_response.get('accessToken')
print(access_token)
id_token = "Bearer {0}".format(access_token)
response = requests.get(RESOURCE, headers={"Authorization": id_token})
print(response)
Please try to modified it. Any updates, please let me know.