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.
Related
NOT : I only have rcon password
I want to retrieve the logs on the csgo server, but I couldn't do it.
I can use c# nodejs and python
I created a project in replit using python and flask and with logaddress_add_http.I added the link of this project to the csgo server and it worked, but I could not figure out how to get the logs by adding the ip of my own computer with the logaddress_add to the csgo server.
Please help me, I couldn't find any sources about this
log on
logaddress_add_http "https://CSGO.synx12.repl.co"
My Code:
from flask import Flask,request
app=Flask(__name__)
#app.route("/",methods=["GET","POST"])
def index():
if(request.method=="GET"):
return "GET"
elif(request.method=="POST"):
data=request.get_data()
print(data)
return f"Data : {data}"
if(__name__=="__main__"):
app.run(host="0.0.0.0",port=8080)
I'm sending a message to the server with rcon
And Result
here logaddress_add_http works fine but I couldn't get logaddress_add to work at all
I want your help for this.
hi i'm new in flask and twilio, i'm try to send 2 images with 1 request but just appears the last image that i put in the array
this is my code
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
from twilio.rest import Client
from dotenv import load_dotenv
import os
load_dotenv()
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello, World!"
#app.route("/sms", methods=['POST'])
def sms_reply():
"""Respond to incoming calls with a simple text message."""
# Fetch the message
msg = request.form.get('Body')
# CLIENT
client = Client(os.getenv("TWILIO_ID"), os.getenv("AUTH_TOKEN"))
number = request.values.get('From', '')
# creating the message
if msg == "imagen":
message = client.messages.create(
from_='whatsapp:+14155238886',
media_url=["https://demo.twilio.com/owl.png", "https://demo.twilio.com/bunny.png"],
to=number
)
resp = MessagingResponse()
resp.message("imagen : {}".format(message.body))
return str(resp)
how could see in the "media_url" parameter i put 2 urls, but twilio just send my 1, i made a mistake?. i try it in this way too
mss = MessagingResponse()
resp = mss.message("this is a message")
resp.body("imagen1")
resp.media("https://demo.twilio.com/owl.png")
resp.body("imagen2")
resp.media("https://demo.twilio.com/bunny.png")
return str(resp)
but is the same. thnks for ur help
Twilio developer evangelist here. That code should work, it's just that there is no bunny image at that URL. You will need your image to be hosted at a publicly-accessible URL like these:
message = client.messages.create(
from_="YOUR-TWILIO-NUMBER",
to="NUMBER-TO-RECEIVE-IMAGES",
body="Test sending two messages",
media_url=["https://data.whicdn.com/images/339398954/original.gif", "https://thumbs.gfycat.com/PrestigiousUntidyBetafish-max-1mb.gif"],
)
That returns this image:
I'd recommend using Twilio Runtime Assets, our static file hosting service that allows developers to quickly upload and serve the files needed to support their applications. host your files that support web, voice, and messaging applications. Assets is commonly used to host .mp3 audio files used in TwiML, to serve images sent through MMSes, or store configuration used by Twilio Functions. You can also deploy the images to be hosted on web servers.
Let me know if this helps at all!
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.
I have a woocommerce site set up with a webhook to a python app I have hosted on heroku.
I can't get the message the woocommerce is sending.
The code is here below:
from flask import Flask, request
app = Flask (__name__)
#app.route('/hook/', methods=['GET','POST'])
def hook():
print(request.get_json())
return "200 OK"
All I need for now is somthing to show up in the heroku log but I get nothing.
You need to store this message in the database or some other place and then read it and show to the user.
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.