Twilio & Flask SMS response never being triggered - python

We are working on a bot that sends and receives SMS with a conditional response system. Using Twilio, we've followed the documentation to give us the below code. Our group has limited experience with both Flask and Twilio and we're not sure which this is a question of, but our incoming_sms() method is never called. The documentation seems to lack a direct calling of this so we assume it's an event triggered on a text coming into our Twilio number, but when we test this nothing is done. Our web hook shows that the message is being picked up (shown below).
Are we missing a step to trigger the incoming_sms() function?
from twilio.rest import Client
from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse
from twilio import twiml
app = Flask(__name__)
#app.route("/sms", methods=['GET', 'POST'])
def incoming_sms():
body = request.values.get('Body', None)
resp = twiml.Response()
if body == 'Hello':
resp.message("Answer 1")
else:
resp.message("Answer 2")
return str(resp)
app.run(debug=True)
POST method picked up by Webhook:
ToCountry=US
ToState=FL
SmsMessageSid=SM8990a3baba3e88f412c9eed1b1f4ae14
NumMedia=0
ToCity=
FromZip=07960
SmsSid=SM8990a3baba3e88f412c9eed1b1f4ae14
FromState=XX
SmsStatus=received
FromCity=XXXXX
Body=Oh+Jac&FromCountry=US
To=%2B12393091468
ToZip=
NumSegments=1
ReferralNumMedia=0
MessageSid=SM8990a3baba3e88f412c9eed1b1f4ae14
AccountSid=AC87f189511d21d6480cdc84350cbbbb84
From=+1XXXXXXXXX
ApiVersion=2010-04-01

Related

Dialogflow fulfillment webhook using Azure web app gives error

I have created fulfillment code for Dialogflow with Python Flask and deployed it as Azure Web App. Code is working fine with the url provided by Azure.
But if I use the same url in Dialog Flow's Fulfillment webhook, I get an error saying "Webhook call failed. Error: UNKNOWN."
Here's my simple Python Flask Code which is deployed in Azure as Web App.
from flask import Flask, request, make_response, jsonify
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
#app.route("/webhook")
def webhook():
return jsonify("Webhook Successfull")
if __name__ == "__main__":
app.run()
Webhook url in DialogFlow:
For your python code, there are two issues I think you met. First is that the route in the Flask just set to support the GET in default. So you need to set for the POST request manually. See the details here for the parameters:
By default a rule just listens for GET (and implicitly HEAD). Starting
with Flask 0.6, OPTIONS is implicitly added and handled by the
standard request handling.
Another is that you return the message via the function jsonify. It turns the JSON output into a Response object with the application/json mime-type, but you just give ita string. So the POST response will meet the conflict. This may be the problem you met.
You can change the code like this:
from flask import Flask, request, make_response, jsonify
app = Flask(__name__)
#app.route("/", methods=["GET", "POST"])
def hello():
return "Hello World!"
#app.route("/webhook", methods=["GET", "POST"])
def webhook():
return jsonify(response="Webhook Successfull")
if __name__ == "__main__":
app.run()

How to send data from to local server

I am working on wireless hand gesture bot project. I want to send output of hand gesture to bot.
I created a server on raspberry pi using flask and trying to send data through request module but its showing '405 Method Not Allowed
Method Not Allowed
The method is not allowed for the requested URL.'
On client side
import requests
r = requests.post("http://192.168.43.133/", data={'foo': 'bar'})
# And done.
print(r.text) # displays the result body.
on server side
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "Hello"
if __name__ == "__main__":
app.run(host='0.0.0.0',port=80,debug= True)
Ref: http://flask.pocoo.org/docs/1.0/api/#flask.Flask.route
#app.route("/")
def index():
return "Hello"
The app.route("/") only maps the GET http verb by default. You're trying to do a POST. So it won't work.
Try this:
#app.route("/", methods=['GET', 'POST'])
def index():
return "Hello"
thanks. i have a variable 'fingers' whose value changes . Can u tell how to send value of finger to server.

python stackdriver google functions webhook listener

I'm trying to create a stackdriver webhook listener in google cloud functions, using the following script:
import sys
import logging
import json
from flask import Flask
from flask import Response, request
def webhook(request):
logging.info("Stackdriver ga360_merge_ready starting up on %s" % (str.replace(sys.version, '\n', ' ')))
app = Flask(__name__)
#app.route('/', methods=['POST'])
def simple_handler():
""" Handle a webhook post with no authentication method """
json_data = json.loads(request.data)
logging.info(json.dumps(json_data, indent=4))
return Response("OK")
For the above, I have the following URL:
https://xxxxx.cloudfunctions.net/webhook
"webhook" is the cloud functions name. when I put this URL in with an ending slash, as per the code, it doesn't seem to send across the message in from stackdriver, essentially, I want the message to also come through, presently, all I get is the below three log entries:
Not sure what I'm missing, I'm new to the python/webhooks world
Your simple_handler is never being called because the request is never being routed to the app you've created.
Is there a reason your function is set up like that? I would expect it to be something like this instead:
import sys
import logging
import json
logging.info("Stackdriver ga360_merge_ready starting up on %s" % (str.replace(sys.version, '\n', ' ')))
def webhook(request):
""" Handle a webhook post with no authentication method """
logging.info(json.dumps(request.get_json(), indent=4))
return Response("OK")

Why is vcard not being received in replied sms when using MessagingResponse?

When I use MessagingResponse.message with media_url parameter or when I append a Media instance to a pre created Message object and return as the answer to an sms in my webhook (already registered on twilio), the vcard which I'm attaching to the answer is not received by the destination.
When I use Client.create and use the media_url the vcard is received successfully.
I've tried with two different accounts and the result is the same. The problem in using Client.create approach is: it'll create a new message trip and it'll cost $0.02. If i just reply with MessagingResponse, it'll cost $0.0075.
I've found this, but I think it is not related: iOS failing to render vcf file
Any concerns about why could I solve this?
My configuration:
Programming language: python 2.7.12
Web Framework: Flask 0.12.2
Twilio API version: 6.3.0
Endpoing SO: Windows 10
Test code
from flask import Flask, request, send_from_directory
from twilio.twiml.messaging_response import MessagingResponse, Message, Media
from twilio.rest import Client
app = Flask(__name__, static_url_path="")
#app.route('/vcards/<path:path>')
def send_vcards(path):
return send_from_directory('vcards', path)
#app.route("/", methods=['GET', 'POST'])
def hey_there():
"""Respond to incoming messages"""
# Calls with client works fine.
# client = Client("SID", "TOKEN")
# client.messages.create(to=request.form["From"], from_="+TWILIO_NUMBER", body="Test with no vcard")
resp = MessagingResponse().message(body="hey, there!",
to=request.form["From"])
resp.append(Media("http://server:port/vcards/test.vcf"))
return str("Ok")
if __name__ == "__main__":
app.run(debug=True)
Update
I just found that the cost is associated with sending media, not with the reply/start of a message. If any media is sent (with media_url or media attaching), it will cost $0.02.
Solution
resp = MessagingResponse()
message = Message(to=request.form["From"])
message.body("hey, there!")
message.media("server:port/vcards/test.vcf")
resp.append(message)
The solution was given by twilio support.
The way it work is this link:
Twilio MMS Examples Page

Incoming SMS with Python SMPP

I'm an new to using SMPP. I am not quite sure incoming messages works. I am implementing this in Python 2.7 using smpplib.I was able to connect to the SMPP service and send out SMS using a bind_transmitter.
In the example there is a function call recv_handler, however I don't see it call for anywhere. Here is the function:
def recv_handler(self, **args):
print 'Message received:', args
Any help would be great. Thank you.
Megan from Twilio here.
I know this question is a bit old. But for someone who lands here looking how to deal with incoming SMS you can get started quickly here:
from flask import Flask, request, redirect
import twilio.twiml
app = Flask(__name__)
#app.route("/", methods=['GET', 'POST'])
def hello_monkey():
resp = twilio.twiml.Response()
resp.message("Hello, Mobile Monkey")
return str(resp)
if __name__ == "__main__":
app.run(debug=True)
Hope this helps!

Categories