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

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

Related

Twilio & Flask SMS response never being triggered

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

ngrok server doesn't connect with dialogfow

I am an absolute beginner in chat bot. I am learning on my own and went on developing a very simple chat bot using Dialog flow. I have a python code for responding the request to my Dialog flow bot. I have enabled "webhook" in fulfillment and also enabled in "Intent".My ngrok url is http://ae3df23b.ngrok.io/. I have written a function in my python code which respond to ngrok which connects Dialog flow. Now problem is that It is showing error "404 not found" and The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. Please help me guys. Thanks in advance.
My code is
#import necessary packages and libraries
import urllib
import os
import json
from flask import Flask
from flask import request
from flask import make_response
app=Flask(__name__)
#app.route('/webhook', methods=['POST'])
def webhook():
req=request.get_json(silent=True, force=True)
print("Request:")
print(json.dumps(req, indent=4))
res=makeWebhookResult(req)
res=json.dumps(res, indent=4)
print(res)
r=make_response(res)
r.headers['Content-Type']='application/json'
return r
def makeWebhookResult(req):
if req.get("result").get("action")!="interest":
return {}
result=req.get("result")
parameters=result.get("parameters")
name=parameters.get("Banknames")
bank={'SBI':'10%', 'HDFC Bank':'9%', 'Bank of Baroda':'11', 'Federal Bank':'8.9%', 'ICICI Bank': '11.5%'}
speech='The interest rate of '+ name + "is" + str(bank[name])
print("Response:")
print(speech)
return {
"speech":speech,
"displayText":speech,
"source":"BankInterestRates"
}
if __name__ == "__main__":
port=int(os.getenv('PORT', 80))
print("Starting app on port %d", (port))
app.run(debug=True, port=port, host='0.0.0.0')
I think you should use https://ae3df23b.ngrok.io/webhook. You are missing the path. Also, use https and generate a new ngrok URL and update the fulfilment.
Try using this format instead https://ae3df23b.ngrok.io/[replace-with-your-project-id]/us-central1/dialogflowFirebaseFulfillment
and make sure u start ngrok with port 5000 and host your functions with "firebase serve" command

Calling Python file in an Ajax Call

So I have established a pretty decent understanding of the simple architecture of an angularjs app, calling $http and posting to a php page, and receiving data back.
What I'm wondering, is how to do the same type of function with python. Is it possible to have python act the same, with self contained script files that accept post data and echo json back?
$username = $_POST['username'];
type variable assignment at the beginning of the script, and:
echo json_encode(response);
type response.
I'm wanting to use Python for some Internal Tools for my company, as it offers better libraries for remotely running powershell scripts (as the tools are all linux hosted) and overall just has libraries that fit my needs. I'm just having a difficult time finding a concise answer to how this could be set up.
---EDIT------
So I set up a quick example using the information below.
the angular:
var app = angular.module("api");
app.controller("MainController", ["$scope","$http",MainController]);
function MainController($scope,$http){
$http.post('/api',{test: "hello"})
.then(function(response){
console.log(response.data);
})
}
The flask:
from flask import Flask, request
import json
app = Flask(__name__)
#app.route('/api', methods=['POST', 'GET'])
def api():
if request.method == 'POST':
request.data
return 'You made it' # Just so I originally could see that the flask page
if __name__ == "__main__":
app.run()
I'm getting a 404 for that URL. If I change the angular to look at 'localhost:5000/api' (where my flask app is running),it gives me the error of "Unsupported URL Type".
I am seeing when I do the first case, it tries to look at http://localhost/api , which is correct! except for the port. Which is why I tried to specify the port.
Any suggestions for a next step?
Use flask.
You could host your app on a flask "server" and return the content you'd like too with a python processing.
http://flask.pocoo.org/
Use the documentation to setup a route where you'll POST your data using jquery or whatever, then on the route you can do your python stuff and return a JSON to your angular app if you need to.
from flask import request
#app.route('/test', methods=['POST', 'GET'])
def test():
if request.method == 'POST':
print request.data['your_field']
return your_json_data

Method not allowed - 405 Error - with Twilio API, using flask and python, heroku

I was following a Twilio tutorial on sending SMS through the API. I followed all the steps, however, I am receiving a 405 error. My code:
from flask import Flask
from twilio import twiml
import os
app = Flask(__name__)
#app.route('/sms', methods=['POST'])
def sms():
r = twiml.Response()
r.sms("This is awesome!")
return str(r)
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
if port == 5000:
app.debug = True
app.run(host='0.0.0.0', port=port)
I am getting a 405 error (method not allowed), when calling my url, which looks like: http://my-url.herokuapp.com/sms, which is also associated like this to the twilio account. When I include 'GET', everything works, this is not according to tutorial however. Any hints?
Looking at the repository it seems that you will actually need to text to the number that Twillo is proxying for you. If you want to access the URL in your browser as well you will need to add 'GET' to the methods list (as you discovered).

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