I have a flask app deployed to Heroku and would like to receive text from Chatfuel (bot building platform) and send back texts in return.
Now, what I did is to use my heroku app as a web-hook, so that Chatfuel can make a simple GET or POST query to my API. The problem is that I have no experience with Flask or APIs, so I am not sure about how my app can receive information (in json format) and send it back to chatfuel.
This is what I wrote so far:
import os
import sys
import json
import requests
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
#app.route('/', methods=['GET'])
def verify():
# when the endpoint is registered as a webhook, it must echo back
# the 'hub.challenge' value it receives in the query arguments
if request.args.get("hub.mode") == "subscribe" and request.args.get("hub.challenge"):
if not request.args.get("hub.verify_token") == os.environ["VERIFY_TOKEN"]:
return "Verification token mismatch", 403
return request.args["hub.challenge"], 200
return "Hello world", 200
#app.route("/json", methods=['GET','POST'])
def json():
url = "chatfuel_api"
data = json.load(urllib2.urlopen(url))
if request.json:
mydata = request.json
return "Thanks",200
else:
return "no json received"
#app.route('/hello', methods = ['GET','POST'])
def api_echo():
if request.method == 'GET':
return "ECHO: GET\n",200
if __name__ == '__main__':
app.run(debug=True)
The verify() function works, as I see an 'Hello world' message if I run the app locally. However, both json() and api_echo() don't work, and when my server receives a get or post request from chatfuel, it returns a 404 error.
As you can see, I really have a lot of confusion, and your help would be really invaluable.
Thanks
You need to make sure you have registered the proper webhook url with Chatfuel. For the code you currently have, to hit the json endpoint the url would be https://www.your_server.com/json
The verify route looks like the hub challenge FB sends, so you would have to register the root of your site (that is, with your current code) with FB to hit the verify function. That url would look like this https://www.your_site.com/
Related
I made a simple flask app that acts as a listener connected to twilio via a webhook. The logic within the app generates a response and returns the response. I'm stuck trying to deploy and host this app. Anyone have experience with this and suggestions?
Below is similar my python file some things are changed such has account info. This is all I have at the moment:
# IMPORTS =============================================================
from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse
# FIELD VARIBALES ===========================================================
account_sid = 'ACCOUNT_SID'
auth_token = 'AUTH_TOKEN'
twilio_number = 'TWILIO_NUMBER'
# FUNCTIONS =======================================================
# Functions to be used in generating response. These are left out for this thread.
# APP =================================================================
app = Flask(__name__)
#app.route("https://mywebhook.com/sms", methods=['GET', 'POST'])
def sms():
"""Send a dynamic reply to an incoming text message"""
# Get the message the user sent our Twilio number
body = request.values.get('Body', None)
# Start our TwiML response
resp = MessagingResponse()
# Determine the right reply for this message
if body == 'hello':
resp.message("Hi!")
elif body == 'bye':
resp.message("Goodbye")
return str(resp)
if __name__ == "__main__":
app.run(debug=True)
I've tried using Netlify and expected a response when texting my twilio number. However there is no response.
I've added a Webhooks listener to a Discord bot, and I'm trying to use that to post notifications to a text channel when a new video is uploaded (trying to eliminate my reliance on MEE6). When I subscribe to notifications at https://pubsubhubbub.appspot.com/subscribe, I get a 200 response, and my server's console prints
66.249.84.174 - - [27/Apr/2021 05:23:51] "GET /webhooks?hub.topic=https://www.youtube.com/xml/feeds/videos.xml%3Fchannel_id%<THE_CHANNEL_ID_I_WANT_NOTIFICATIONS_FOR>&hub.challenge=<A_BUNCH_OF_NUMBERS>&hub.mode=subscribe&hub.lease_seconds=432000 HTTP/1.1" 200 -
However, when a video gets uploaded nothing happens.
I've tried manually triggering a POST request from PostMan to the same endpoint (with the XML body found here https://developers.google.com/youtube/v3/guides/push_notifications as the raw->xml body text), and that seems to hit my console and return a 200, but I'm at a loss as to why I'm not getting any indication when an upload goes up. Code below:
from flask import Flask, Response, request
app = Flask(__name__)
#app.route('/webhooks', methods=['POST'])
def respond():
print(request.json);
return Response(status=200)
#app.route('/webhooks')
def index():
print(('request', request))
print('args:', request.args) # display text in console
print('form:', request.form)
print('data:', request.data)
print('json:', request.json)
print('files:', request.files)
return request.args.get('data', 'none') # send text to web browser
if __name__ == '__main__':
app.run(host='0.0.0.0', port=<MY_PORT>)
I'm hosting on PebbleHost, which is why the host is set to 0.0.0.0; there's a separate IP I'm connecting to for the subscriptions, mapped to a dedicated port. I'm quite new to Webhooks, and this is my first time interacting with the YouTube API, so I'm certain there's something really obvious I'm overlooking.
You have to return hub.challenge for confirmation on subscription.
A Working Example that I made earlier.
from flask import Flask, request
import xmltodict
app = Flask(__name__)
#app.route("/callback", methods=['POST', 'GET'])
def callback():
if request.method == 'POST':
data = xmltodict.parse(request.data)
print(data)
return request.data
else:
return request.args.get('hub.challenge')
app.run('0.0.0.0')
Would you know how to select only the int (number) variables from the inbound sms in the twilio api. At the moment all of my inbound sms' are printing in the terminal after I run this code
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."""
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("")
print(str(body))
return str(resp)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=70, debug=True)
Would you know how I could make the numbers from the body of an inbound sms a variable that I could manipulate and use. To put things into perspective, I'm trying to automate a login process that uses an OTP for authentication. I plan to use selenium to insert this code (number) I recieve through my twilio number
I have the following python script that is connecting to Google Dialogflow using Flask and is using a webhook to retrieve the response from Google Dialogflow.
The limitation is that I currently only enter the query in to the Google Dialogflow frontend, with the result returned here in variable result
However how can I use this same script to submit the query to Google Dialogflow, instead of entering in the front end?
Any help appreciated, thanks!
import json
import os
from flask import Flask
from flask import request
from flask import make_response`
`enter code here # Flask app should start in global layout
app = Flask(__name__)
#app.route('/webhook', methods=['POST'])
def webhook():
req = request.get_json(silent=True, force=True)
res = processRequest(req)
res = json.dumps(res, indent=4)
r = make_response(res)
r.headers['Content-Type'] = 'application/json'
return r
def processRequest(req):
result = req.get("queryResult")
result_message = result['fulfillmentText']
print(result_message)
#app.route('/test', methods=['GET'])
def test():
return "Hello there my friend !!"
if __name__ == '__main__':
port = int(os.getenv('PORT', 5000))
app.run(debug=True, port=port, host='0.0.0.0')`
I discovered shortly after posting this that a webhook is whats known as a reverse API, and only shows results as opposed to two way interactions.
I have created a messenger chatbot with flask, pymessenger and wit.ai.
I want to add facebook provided templates (like buttons, adding images and sound media)(https://developers.facebook.com/docs/messenger-platform/reference/template/button/)
There using some curl and json thing which I do not understand. Can some one help me, where should I put these snippet in my python code.
#app.route('/', methods=['POST'])
def webhook():
data = request.get_json()
log(data)
if data['object'] == 'page':
for entry in data['entry']:
for messaging_event in entry['messaging']:
sender_id = messaging_event['sender']['id']
recipient_id = messaging_event['recipient']['id']
if messaging_event.get('message'):
if 'text' in messaging_event['message']:
messaging_text = messaging_event['message']['text']
else:
messaging_text = 'no text'
response = None
entity, value = wit_response(messaging_text)
if entity == 'newstype':
response = "OK. I will send you {} news".format(str(value))
elif entity == 'cust_greet':
response = get_message()
elif entity == 'cust_bye':
response = "Bye! Have a Good Day!".format(str(value))
elif entity == 'cust_option':
response = "Option 1: Option 2:"
bot.send_text_message(sender_id, response)
return "ok", 200
def log(message):
print(message)
sys.stdout.flush()
HTTP requests use one of these two formats:
GET: All the request information is in the url
POST: Some information is sent via a JSON format to the url
What we see in the Facebook API is a POST request: the url is defined as
https://graph.facebook.com/v2.6/me/messages?access_token=<PAGE_ACCESS_TOKEN>
...and there is POST request information in the JSON section underneath
Curl is a program used to send HTTP requests from the terminal. If you install Curl, you can fill in the JSON/url information, run the command (which sends the POST request), and see the buttons pop up for the recipient. Just as you want your chatbot to do!
However, Curl is a tool, not a Python library!
To do this in Python, you can send the request through Python's built in libraries, or install a package which makes this easier (such as requests), look into "sending http requests via python".
Below is an example (adapted from this question):
from urllib.parse import urlencode
from urllib.request import Request, urlopen
# the url we are sending the request to
url = "https://graph.facebook.com/v2.6/me/..."
# the POST request data
request_data = {
"recipient": {
"id": "<PSID>"
},
"message": {
"attachment": {
...
}
}
}
# create the request with the url and the data
post_request = Request(url, urlencode(request_data).encode())
# send it to Facebook! Response is the API response from Facebook
response = urlopen(post_request).read().decode()