I am trying to create a connection to whatsapp and my python script via Twilio, to generate automatic conversations. I follow every step in order of this link https://www.pragnakalp.com/create-whatsapp-bot-with-twilio-using-python-tutorial-with-examples/?unapproved=4864&moderation-hash=3861b2bc00104a39b5f3211076dda854#comment-4864
The problem arrays when I start a conversation with the bot, that in my ngrok port, ngrok http 5000 it says POST/ 403 Forbidden, in the section of https requests.
Before sending the message to the bot I run my python script:
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
app = Flask(__name__)
##app.route("/wa")
#def wa_hello():
# return "Hello, World!"
#app.route("/wasms", methods=['POST'])
def wa_sms_reply():
"""Respond to incoming calls with a simple text message."""
# Fetch the message
msg = request.form.get('Body').lower() # Reading the message from the whatsapp
print("msg-->", msg)
resp = MessagingResponse()
reply = resp.message()
# Create reply
if msg == "hi":
reply.body("hello!")
return str(resp)
if __name__ == "__main__":
app.run(debug=True)
I tried running commands like ngrok http https://localhost:5000, turning off firewalls on my Mac, allowing my country on the Twilio´s web page, inserting config.hosts << /.*\.ngrok\.io/ in my terminal and restaring my laptop, config.hosts << "a0000000.ngrok.io" and skip_before_action :verify_authenticity_token but nothing of this work for me. The error os shown here:enter image description here
Related
I tried to code a simple sms chatbot using Twilio & Flask. The code runs fine, and the console connects, but Twilio doesn't. Some website also said something about ngrok? When I text the Twilio phone number it says, "Thanks for the message. Configure your number's SMS URL to change this message. Cheers, Londo.
try:
from flask import Flask, request
import requests
from twilio.twiml.messaging_response import MessagingResponse
import datetime
except ModuleNotFoundError:
from subprocess import call
modules = ["flask","datetime"]
call("pip install " + ' '.join(modules), shell=True)
app = Flask(__name__)
x = datetime.datetime.now()
#app.route('/bot', methods=['POST'])
def bot():
incoming_msg = request.values.get('Body', '').lower()
resp = MessagingResponse()
msg = resp.message()
responded = False
if 'Hi' in incoming_msg:
msg.body("Hello Londo! *Type: 'Yo*")
responded = True
if 'Yo' in incoming_msg:
msg.body(f'Good morning!, the date is {x.strftime("%X")}. *Type: I am up*')
responded = True
if 'I am up' in incoming_msg:
msg.body('Do 10 pushups and 5 pullups! *Type: Done*')
responded = True
if 'Done' in incoming_msg:
msg.body('Now make the bed. *Type: Ok')
responded = True
if 'Ok' in incoming_msg:
msg.body('Wake TF up!')
responded = True
if not responded:
msg.body('I only respond to certian commands')
return str(resp)
if __name__ == '__main__':
app.run()
You need two things here.
First, you need your application to have a publicly accessible URL. Using ngrok is one way to achieve that, though there are others. To do so, download and install ngrok, then run ngrok http PORT where PORT is the port number your application is running on. When you do this, ngrok will give you a URL which your application is now available on.
Second, you need to configure your Twilio phone number with this URL. Open the Twilio console, navigate to your number and configure it. In the messaging section, add your URL (https://RANDOM_SUBDOMAIN.ngrok.io/bot) to the field for the webhook when you receive a message. Save the number and text it again, you should be good.
Do note that every time you start ngrok you will get a different subdomain, so you may have to update your number again. You can overcome this by paying for an ngrok account that allows for you to choose a subdomain, or by using the Twilio CLI to create the proxy to your localhost.
I am new to python and coding in general and I have been tasked with creating a Google Chat Bot that will send an alert in a Google Chat Room when our hardware monitoring service detects an issue. The general premise of the project is that the monitoring service takes my webhook URL and uses it to give me the JSON and I have to get that to the Google Chat in a readable and timely fashion.
This is what I have so far :
from flask import Flask, request, abort, Response
from json import dumps
from httplib2 import Http
app = Flask(__name__)
def main(botmsg):
url = #placeholder for Google Chat Webhook URL#
bot_message = {
'text' : botmsg}
message_headers = {'Content-Type': 'application/json; charset=UTF-8'}
http_obj = Http()
Response = http_obj.request(
uri=url,
method='post',
headers=message_headers,
body=dumps(bot_message),
)
print(Response)
#app.route('/', methods=['POST'])
def respond():
if request.method == 'POST':
print(request.json)
return Response(status=200)
else: abort(400)
if __name__ == '__main__':
app.run()
At first I had this exact file running locally. I would spin up my flask server but I could never get the main() to ping the Google Chat when I triggered it with a local webhook. Alone, the main function is working but I couldn't call the function in response to receiving the webhook. Now I am struggling with the same issue with this code in a Google Function pinging it using Github.
I get this error in my function logs when I ping it with the webhook:
"TypeError: Object of type Request is not JSON serializable"
I have been scraping the internet for weeks on how to do this to no avail so if anyone could give me some pointers it would be greatly appreciated!
Following the Twilio SMS Python Quickstart guide found here:
https://www.twilio.com/docs/sms/quickstart/python
I can get up to the "Receive and reply to inbound SMS messages with Flask" section perfectly fine, with both my http://localhost:5000/ and ngrok URL showing the correct "Hello World" message.
However, as soon as I replace the run.py file code with the instructed code to reply to the sender with an sms, both URLs become dead with a "404 Not Found" error.
Have tried restarting everything etc.
run.py:
# /usr/bin/env python
# Download the twilio-python library from twilio.com/docs/libraries/python
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
app = Flask(__name__)
#app.route("/sms", methods=['GET', '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)
Any ideas?
As soon as I change the run.py code back to the original "Hello World" code both URLs run fine.
Also, the ngrok server does show an attempted connection when I send an sms message to the twilio number too, but with a "404 Not Found" message next to it.
I have faced the following problem after moving my bot to the new server. I use webhook to get updates but now the bot does not get them from telegram servers. I tried to send POST request with curl from the remove server and bot handled it in a normal way. I checked webhook with getWebhookInfo and it returned an object with non-empty url and pending_update_count equal to 74 without errors. I guess, it means that telegram servers are not able to send POST request to my host for some reason.
OS of my server is Arch Linux.
I use pyTelegramBotAP.
CONFIG = ConfigParser()
CONFIG.read(os.path.join('data', 'config.ini'))
# webhook url
URL_BASE = "https://{}:{}".format(CONFIG['server']['ip'], CONFIG.getint('server', 'port'))
URL_PATH = "/{}/".format(CONFIG['telegram bot']['token'])
BOT = telebot.TeleBot(CONFIG['telegram bot']['token'])
# server that will listen for new messages
APP = web.Application()
URL = URL_BASE + URL_PATH
BOT.set_webhook(url=URL, certificate=open(CONFIG['ssl']['certificate'], 'rb'))
# Build ssl context
CONTEXT = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
CONTEXT.load_cert_chain(CONFIG['ssl']['certificate'], CONFIG['ssl']['private key'])
# Start aiohttp server
web.run_app(
APP,
host=CONFIG['server']['listen'],
port=CONFIG['server']['port'],
ssl_context=CONTEXT,
)
Please, help!
Telegram webhook only talks to https endpoints, so I suggest to check your server against https connections.
Also, getWebhookInfo call returns a status object with the latest error infomation of your endpoint. Have a look of that error info and might find the exact problem.
Please check the Firewall on your server, It is quite possible firewall on your server is not passing message to your application.
To check firewall status run $ ufw status
Please show you URL_BASE without real IP.
What operating system is on your server?
You send test request from the CURL to URL of the Telegram or of your server?
Can you getting response from your server if you run simple app?
Example:
from aiohttp import web
async def hello(request):
return web.Response(text='Hello world!')
app = web.Application()
app.add_routes([web.get('/', hello)])
web.run_app(app, host='localhost', port=3003)
Check response:
$ curl localhost:3003
Hello world!
Please provide more detailed information on how you troubleshoot.
I'm learning python and as a project I'm trying to create a program that will recieve an SMS message, process it, and then depending on what is in that message, send back information.
I am using Twilio in python with Flask and ngrok to do all the SMS stuff, but I am still not sure how to actually receive an SMS as data that I can read and process, as there is no documentation that I can find on it. It would be great if someone could help me with this.
I already know how to receive and send SMS with Twilio, I just need to know how to get the precise message that was sent to my Twilio number.
I believe you already know how to configure Twilio to hit your endpoint when a message comes in. If you configure at Twilio for a POST request, then the data passed to you from Twilio will be in request.form.
If you take a look at Twilio's example here:
(https://www.twilio.com/docs/sms/tutorials/how-to-receive-and-reply-python)
indeed the example makes no use of the data that is coming in.
The modified code below shows some data that is available from the request (and you can write your code depending on what you'd like to do with it).
the number from where the message was sent request.form['From'],
your Twilio number request.form['To']
and the body of the message request.form['Body']
from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse
app = Flask(__name__)
#app.route("/sms", methods=['POST'])
def sms_reply():
"""Respond to incoming calls with a simple text message."""
# Use this data in your application logic
from_number = request.form['From']
to_number = request.form['To']
body = request.form['Body']
# Start our TwiML response
resp = MessagingResponse()
# Add a message
resp.message("The Robots are coming! Head for the hills!")
return str(resp)
if __name__ == "__main__":
app.run(debug=True)
Some other parameters are also available in the request:
MessageSid
SmsSid
AccountSid
MessagingServiceSid
From
To
Body
NumMedia
Docs: (https://www.twilio.com/docs/sms/twiml#request-parameters)
Also you can find more examples if you google for "twilio blog python flask"