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!
Related
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
I have a local Flask REST API that runs some queries and return JSON responses. My idea is to send a POST request to the API and trigger a function capable of updating my database.
The inspiration behind this idea is the way we create resources in a public Cloud. Example: let's say we create a Virtual Cloud Network on any public cloud. The cloud architecture has several APIs for each module and the creation of a VCN trigger the creation of NAT Gateways, Route Tables, Security Lists, Subnets and so on through a GET or POST request to each resource type.
So inspired by this architecture, I want to do this in a simplified and local manner. My first guess is to use the multiprocessing library to spawn processes as soon as a request hits the endpoint, but I don't know if this the best way or a good practice. Can anyone give me an idea on how to do this or if I am in the right path.
i dont really understand... but i can try to help you,
the following code is a code that is the same API but you can get different responses, i dont know what are you going to do with so i added my own examples.
from flask import *
app = Flask(__name__)
#app.route('/api/route/1', methods=['POST'])
def api_1():
if request.method == 'POST':
# Some code here
#Eg:
# data = request.get_json()
# print(data)
#return data.thing
#OR
return "Hello from route 1"
#app.route('/api/route/2', methods=['POST'])
def api_2():
if request.method == 'POST':
# Some code here
#Eg:
# data = request.get_json()
# print(data)
#return data.thing
#OR
return "Hello from route 2"
#app.route('/api/route/3', methods=['POST'])
def api_3():
if request.method == 'POST':
# Some code here
#Eg:
# data = request.get_json()
# print(data)
#return data.thing
#OR
return "Hello from route 3"
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8000, debug=True)
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.
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
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