Plivo python message - python

I'm creating a web app in Python with Bottle which has the task to retrieve messages from Plivo. First, when I send a message to Plivo, it's like if I didn't. I can't find a Python example and I don't know much about web protocols and so on to configure all by myself.
I have the following issues which I haven't been able to fix:
1. Setting up Plivo to forward messages. In the site, you can create applications with these input options:
Application name
Sub account
Answer url
Answer method
Fallback_answer url
Fallback method
Hangup url
Hangup method
Message url
Message method
Default number app
Default endpoint app
Public uri
Setting up at least part of it should get my messages to my server. I don't know what.
2. I've got the following python code:
from bottle import route, run, request
#route('/hello', method=['GET', 'POST'])
def hello():
return "Hello World!"
bottlelog = open('bottlelog.txt').read
bottlelog.append(request + '\n')
bottlelog.close()
run(host='0.0.0.0', port=8080, debug=True)
It should save the request information in this file but at least right now it doesn't.
3. Answer. Should my server answer something specific when Plivo notifies me of my messages?
I hope that you can help me at least to find out where I should head to resolve my problems. Excuse me if I'm kind of messy, I'm new to web development and I'm just getting to know stuff.
Thank you all

Your Plivo number must be linked to an application which has a "Message url" present. When an SMS is received on your number, Plivo will send a hook to the "Message url" with the parameters Text, From, To, Type and MessageUUID. The HTTP method used to send these parameters is the "Message method" set in the application.
For the setup you described, your bottle server is listening on 8080 and has a route /hello/ open. Your Message Url should be http://<your-server-name>:8080/hello/ and the Message method should be set as POST. Click on "Create" to create your application
Next step is to link your Plivo number to the application you just created. Click on the "Numbers" tab in the dashboard. You will be able to see all your Plivo numbers under the "Your Numbers" section. By clicking on the number you'll be given an option to choose your application. Select the "Receive Message" app and click on "Update".
This sample code should get you up and running.
from bottle import run, request, HTTPResponse
#route('/hello/', method=['POST'])
def hello():
Text = request.forms.get('Text')
From = request.forms.get('From')
print "Message received: %s - by %s" % (Text, From)
return HTTPResponse(status=200)
run(host='0.0.0.0', port=8080, debug=True)
Run this code on your server and you'll be able to see the incoming messages on the console when an SMS is received on your Plivo number.

Related

Android app written in kotlin with the volley library fails to call my backend, which was written in python with django

so as the post says, i'm making an app, for which i have a server/rest api written with the django framework. When i try to call the api using volley, i fail to get any response, and i don't see it show up on my server's dashboard
The server is running on my local machine, and the app is running on an emulator, since i'm using android studio
i'd like to send a request and display the response in a textview on the app, for now thats all i need to continue onto the next part
What ends up happening instead is that it seems to not even hit my server, the app displays the text i set for if the request fails, adn it doesn't show up on the dashboard of my server
here's basically all the code in my mobile app
val textView = findViewById<TextView>(R.id.text)
val queue = Volley.newRequestQueue(this)
val url = "http://127.0.0.1:8000//index"//i also tried to use 192.168.1.2 as the host ip. the port is always 8000
val stringRequest = StringRequest(Request.Method.GET, url,
Response.Listener<String> { response ->
// Display the first 500 characters of the response string.
textView.text = "Response is: ${response.substring(0, 500)}"
},
Response.ErrorListener { textView.text = "That didn't work!" })
queue.add(stringRequest)
Please check the logs. They should show you a security error because you use HTTP clear text traffic.
With the default settings, apps aren't allowed to transmit cleartest HTTP traffic.
You must either add an SSL certificate to your backend or allow HTTP traffic.
Check out this StackOverflow thread to see how to enable clear text web requests.

Python Flask server getting 'code 400' errors (POST request sent from Telegram-webhook)

Context
I'm currently following this tutorial. - Telegram Bot with Python Tutorial #3: Creating Bot and Webhook | Project
FIRST STEP
I have set-up a Flask server using the following python code:
from flask import Flask
from flask import request
from flask import Response
import json
app = Flask(__name__)
#app.route('/', methods=['POST', 'GET'])
def index():
if request.method == 'POST':
print(request)
message = request.json()
with open('telegram_request.json', 'w', encoding='utf-8') as filename:
json.dump(message, filename, ensure_ascii=False, indent=4)
# prevents telegram from spamming
return Response('Ok', status=200)
else:
return """
<h1> Flask Server </h1>
<h2> Up and running </h2>
"""
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=8443)
SECOND STEP
I port forwarded port 8443 in my router to make the server visible to the outside world (tunneling step in tutorial).
The domain name "myprivatedomain.com:8443" now redirects/refers to the flask server that is set-up.
THIRD STEP
I set-up the Telegram-API webhook correctly, getting the following response code from Telegram:
{"ok":true,"result":true,"description":"Webhook was set"}
NOW
Before sending a message in the Telegram chat: there were no errors.
After sending a message in the chat, the following errors popped up:
code 400, message Bad HTTP/0.9 request type
('RANDOM BYTE VALUES like \x00\x03')
code 400, message Bad request syntax
('RANDOM BYTE VALUES like \x00\x03')
code 400, message Bad request version
('RANDOM BYTE VALUES like \x00\x03')
WHAT I WANT
According to the tutorial, you can write a .json file when Telegram makes a POST request (see example: here). I want to save the message object provided by the Telegram webhook (as showcased in the tutorial video). Using the webhook for getting updates is better than constantly querying the getUpdates() method; that method returns old messages also.
WHAT I'VE TRIED
I've tried to add:
ssl_context='adhoc'
to
app.run(debug=True, host='0.0.0.0', port=8443)
to make the connection HTTPS.
While using this ssl_context, loading the homepage isn't possible either..
PREFERABLE OUTPUT
When the user sends a message inside the Telegram chat --> Python saves a .json file of the message object.
You need to have SSL enabled for this to work. Telegram is trying to initiate an SSL session with your server, but you don't have SSL enabled, so you are seeing the bad request.
ssl_context='adhoc' may work for a test app, but I also have a hunch that telegram requires a VALID SSL certificate, not just an ad-hoc (or self-signed one). Notice the lock to the left of the URL in the video and the lack of a security warning that would be present with an invalid or self-signed certificate.
To make sure SSL is working set the ssl_context to adhoc, start the app, and browse to https://myprivatedomain.com:8443/index. If you can browse to it, then Telegram will also be able to browse to it, after getting a valid certificate, of course.
Next, to get a valid (and free) SSL certificate you can use LetsEncrypt.
Once you have a valid SSL certificate and key file you can pass the ssl_context argument to app.run with a tuple of the path to the certificate file and the path to the key file ("/path/to/fullchain.pem", "/path/to/privkey.pem")
Your full run function should look like this
app.run(debug=True, host='0.0.0.0', port=8443, ssl_context=("/path/to/fullchain.pem", "/path/to/privkey.pem"))
Alternatively you can use Apache or Nginx to secure your site with SSL, and reverse proxy to your bot. Those options would normally be used in a final product, so I understand if you don't want to get into the weeds with them right now, but it is good practice regardless.
Hopefully that helps.

Reply to Incoming Message Twilio SMS Python Quickstart

I'm currently working on the Twilio SMS Quickstart; specifically I'm stuck on the "Reply to an incoming message using Twilio SMS".
*update, I've realized I haven't used the 'request' module I imported from Flask. Would appreciate any tips on if I need to utilize this module and, if I do, how do I use it in this specific script?
Up to this point I've successfully sent a message using a Twilio script called "send_sms.py". I'm now stuck with being unable use my virtualenv to receive and reply to messages. Here's the code titled 'run.py':
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
app = Flask(__name__)
#app.route('/sms', methods=['POST'])
def sms_ahoy_reply():
"""Respond to incoming messages with a friendly SMS."""
# Start our response
resp = MessagingResponse()
# Add a message
resp.message("Ahoy! Thanks so much for your message.")
return str(resp)
if __name__ == "__main__":
app.run(debug=True)
I get an error from my code editor, Spyder, next to 'from flask import Flask, request'; however, when I delete ', request' the error goes away.
As a result of this issue I'm unable to successfully run the script which would allow me to receive and reply to text messages via Twilio.

Flask CGI app issues with print statement

I have a simple flask application deployed using CGI+Apache running on a shared hosting server.
The app runs Flask 0.11.1 on Python 2.6 along with Flask-Mail 0.9.1.
One of the pages in the app has a contact form that sends an email and redirects back to the same page.
The contact form has a POST action to '/sendmail' that is defined in Flask controller as follows -
#app.route("/sendmail", methods=['GET','POST'])
def send_mail():
print "Sending Email"
mail = SendMail(app)
mail.send_mail(request.form['name'], request.form['mail'], request.form['phoneNo'], request.form['message'])
return render_template('contact.html')
Here's the issue -
With the code above, the app sends me an email successfully, however then gives an error '/sendmail' not found. The template fails to render.
If I remove the print statement from the snippet, the app renders contact.html successfully after sending the email.
What explains the behaviour of print statement in the snippet? Considering the execution is sequential, shouldn't the block fail at the print statement itself without sending the email instead of failing during rendering the template?
Print statement should not create an error as it is one of the statement like others. Instead since you are not checking for request.method=='POST', this should create and throw an error in your get request. To redirect to the same page return redirect("/sendmail") Do not forget to import from flask like this from flask import redirect

Plivo - Not receiving sms

I've just started using Plivo to set up an sms service. I'm trying to receive SMSs on my server but my server just doesn't seem to receive them.
I've set it up on heroku, the below is my code:
import plivo, plivoxml
import os
import os.path
from flask import Flask, request
app = Flask(__name__)
#app.route("/receive-sms/",methods=['GET','POST'])
def inbound_sms():
# Sender's phone number
from_number = request.values.get('From')
print from_number
# Receiver's phone number - Plivo number
to_number = request.values.get('To')
# The text which was received
text = request.values.get('Text')
params = {
"src": to_number,
"dst": from_number,
}
body = "Thanks, we've received your message."
# Generate a Message XML with the details of
# the reply to be sent.
r = plivoxml.Response()
r.addMessage(body, **params)
return r.to_xml()
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
# print port
app.run(host='0.0.0.0', port=port)
On Plivo, my message url is:
http://ripmac.herokuapp.com/receive-sms/
I've linked my Plivo number to the right plivo application.
Additionally, I'm not sure if I'm supposed to see messages when I login on Plivo and navigate to the logs->SMS. There are no logs which is starting to make me think that there is something wrong with the port/message url. Any help will be much appreciated. Thanks!
I'm new as well and was having the exact problem as the poster above me. I was looking through their documentation and i found this:
"Note: If you are using a Plivo Trial account for this example, you can only send sms to phone numbers that have been verified with Plivo. Phone numbers can be verified at the Sandbox Numbers page."
Once i added my phone number, it worked.
One more thing: when i filled out the form to verify the number, i noticed it would not validate with [area code]number. The other thing i made sure i did was send the number in the format [CountryCode][Area Code] Number
My experience.
I bought a Plivo US number.
I setup the Application with "Message URL" but my server was never hit when I tried to send an SMS from an IT or a UK number.
I tried to call using the UK number and I found the log for missing "Hangup URL" in SMS/Logs/Debug.
With the helpdesk we tried to send SMS from a US numbers. It works.
I haven't read about any limitation for the SMS source country and also the help desk didn't says nothing about it in the ticket (I explained everything precisely).
So, that's it. A US number cannot receive SMS from a non-US number. (but apparently calls work). I also tried to receive a verification code from PayPal US and this does not work too.
The help desk guy suggested me to buy a UK number for SMS from UK, but they don't sell UK numbers if you select "SMS"!

Categories