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)
Related
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'm sending emails using the Sendgrid API, but every email that I send does not have the Subjet.
My code looks like this:
def send_notification(sendgrid_key, p_email):
message = Mail(
from_email=('my_email#mail.com'),
to_emails=(p_email),
subject='subject email',
)
message.template_id = 'XXXXXX'
try:
sg = SendGridAPIClient(sendgrid_key)
response = sg.send(message)
except Exception as e:
print(str(e))
Eventhought, I have set the subjet, I'm still receiving emails without subject. Moreover, I do not have any errors when my app run.
Twilio SendGrid developer evangelist here.
When you are using SendGrid's dynamic templates you actually set the subject in the template, not through the API. Take a look at this screenshot to see where you set the subject in the template editor.
If you want to set the subject dynamically too, you can add a template string in the subject and set that through dynamic template variables when you send the email. Check this article on creating a dynamic email subject line with mustache templates for more information.
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"
I'm having some trouble understanding and implementing the Google Directory API's users watch function and push notification system (https://developers.google.com/admin-sdk/reports/v1/guides/push#creating-notification-channels) in my Python GAE app. What I'm trying to achieve is that any user (admin) who uses my app would be able to watch user changes within his own domain.
I've verified the domain I want to use for notifications and implemented the watch request as follows:
directoryauthdecorator = OAuth2Decorator(
approval_prompt='force',
client_id='my_client_id',
client_secret='my_client_secret',
callback_path='/oauth2callback',
scope=['https://www.googleapis.com/auth/admin.directory.user'])
class PushNotifications(webapp.RequestHandler):
#directoryauthdecorator.oauth_required
def get(self):
auth_http = directoryauthdecorator.http()
service = build("admin", "directory_v1", http=auth_http)
uu_id=str(uuid.uuid4())
param={}
param['customer']='my_customer'
param['event']='add'
param['body']={'type':'web_hook','id':uu_id,'address':'https://my-domain.com/pushNotifications'}
watchUsers = service.users().watch(**param).execute()
application = webapp.WSGIApplication(
[
('/pushNotifications',PushNotifications),
(directoryauthdecorator.callback_path, directoryauthdecorator.callback_handler())],
debug=True)
Now, the receiving part is what I don't understand. When I add a user on my domain and check the app's request logs I see some activity, but there's no usable data. How should I approach this part?
Any help would be appreciated. Thanks.
The problem
It seems like there's been some confusion in implementing the handler. Your handler actually sets up the notifications channel by sending a POST request to the Reports API endpoint. As the docs say:
To set up a notification channel for messages about changes to a particular resource, send a POST request to the watch method for the resource.
source
You should only need to send this request one time to set up the channel, and the "address" parameter should be the URL on your app that will receive the notifications.
Also, it's not clear what is happening with the following code:
param={}
param['customer']='my_customer'
param['event']='add'
Are you just breaking the code in order to post it here? Or is it actually written that way in the file? You should actually preserve, as much as possible, the code that your app is running so that we can reason about it.
The solution
It seems from the docs you linked - in the "Receiving Notifications" section, that you should have code inside the "address" specified to receive notifications that will inspect the POST request body and headers on the notification push request, and then do something with that data (like store it in BigQuery or send an email to the admin, etc.)
Managed to figure it out. In the App Engine logs I noticed that each time I make a change, which is being 'watched', on my domain I get a POST request from Google's API, but with a 302 code. I discovered that this was due to the fact I had login: required configured in my app.yaml for the script, which was handling the requests and the POST request was being redirected to the login page, instead of the processing script.
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.