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!
Related
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
I want to build a bot on messenger with Python. I am following the official documentation from Facebook, but they are using a repository made in javascript, and this Youtube tutorial which is in python but already one year old, so not up to date.
When sending a message to the app I don't get any data back despite running the following code, which I believe is a webhook:
from flask import Flask, request
PAGE_ACCESS_TOKEN = 'My Page Access Tokens from https://developers.facebook.com/apps/2924966724200691/messenger/settings/'
app = Flask(__name__)
#app.route('/', methods = ['GET'])
def webhook():
if request.method =='GET':
token = request.args.get('hub.verify_token')
challenge = request.args.get('hub.challenge')
if token == 'secret':
return str(challenge)
return '400'
else:
print(request.data)
return '200'
if __name__ == '__main__':
app.run(debug = True)
I am using ngrok.
Everything that happens to Messenger bot should be sent as an event to my terminal where the webhook is running. Yet I don't have anythong. Let me know if you need any more information.
I'm attempting to create a Flask application in Python that communicates with a RESTful API that uses OAuth2.0, but I'm having trouble sending requests. I'm successfully getting an access token from the server, but when I try to make a GET or POST request, I always get a 404 as a response. I'm new to RESTful API's so I don't know what I could possibly be doing wrong here or what a 404 means in this context.
Here is the .py file where I attempt to send a GET and POST request to the API. TokenHandler is just a helper class I made that keeps track of token related info, and the print(response) lines always print "Response [404]".
from flask import Flask, render_template, request, redirect
from src.apitest import TokenHandler
import requests
from oauthlib.oauth2 import LegacyApplicationClient
from requests_oauthlib import OAuth2Session
import json
app = Flask(__name__)
token_handler = TokenHandler()
#app.route('/find_customer')
def find_customer():
return render_template('customer_find_page.html')
#app.route('/find_customer', methods=['POST'])
def find_customer_get():
customer_id = request.form['text0']
oauth = OAuth2Session(client=LegacyApplicationClient(client_id=token_handler.CLIENT_ID))
oauth.fetch_token(token_url=token_handler.TOKEN_ENDPOINT,
username=token_handler.USERNAME, password=token_handler.PASSWORD, client_id=token_handler.CLIENT_ID,
client_secret=token_handler.CLIENT_SECRET,
scope=token_handler.SCOPE)
response = oauth.get("https://sedonacloudtest.com/api/customers/"+customer_id)
print(response)
return redirect('/find_customer')
#app.route('/add_customer')
def add_customer():
return render_template('customer_add_page.html')
#app.route('/add_customer', methods=['POST'])
def add_customer_post():
customer_id = request.form['text0']
customer_name = request.form['text1']
data = {"customer_id": customer_id, "customer_name": customer_name}
oauth = OAuth2Session(client=LegacyApplicationClient(client_id=token_handler.CLIENT_ID))
oauth.fetch_token(token_url=token_handler.TOKEN_ENDPOINT,
username=token_handler.USERNAME, password=token_handler.PASSWORD, client_id=token_handler.CLIENT_ID,
client_secret=token_handler.CLIENT_SECRET,
scope=token_handler.SCOPE)
response = oauth.post("https://sedonacloudtest.com/api/customers", data=data)
print(response)
return redirect('/add_customer')
if __name__ == "__main__":
app.run()
I am new to API, and get a tasks of creating POST API. I have created a code somehow.
I want to add data to the hello.txt through post API, So how will I do it?
Here is my code:
import flask
from flask import request, jsonify
app = flask.Flask(__name__)
app.config["DEBUG"] = True
#app.route('/api/v1/resources/messages', methods = ['POST'])
def api_message():
if request.headers['Content-Type'] == 'text/plain':
return "Text Message: " + request.data
elif request.headers['Content-Type'] == 'application/octet-stream':
return "Binary message written!"
elif request.headers['Content-Type'] == 'application/json':
f = open('F:\Asif_Ahmed\Projects\api\hello.txt',"w")
f.write(request.data)
f.close()
return "JSON Message: " + json.dumps(request.json)
else:
return "415 Unsupported Media Type ;)"
app.run()
from flask import Flask, jsonify, render_template, request #import flask library
from flask_basicauth import BasicAuth # import flask library for create basic authentication if needed
from flask_cors import CORS # import flask library Cross-Origin Resource Sharing that is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin
app = Flask(__name__)
CORS(app) #set-up cors for my app
#if you want use basic authentication you need set-up username and password
app.config['BASIC_AUTH_USERNAME'] = 'admin'
app.config['BASIC_AUTH_PASSWORD'] = 'password'
basic_auth = BasicAuth(app)#set-up username and password for my app but in this case I'm not specifying yet in which API use them
#app.route('/api/v1/resources/add_messages', methods=['POST'])#create my POST api
#basic_auth.required# set-up basic authentication for this API, comment out if not needed
def update_credential ():
json_credential=request.get_json()#get the JSON sent via API
print (json_credential["message"])#get the node "message" of my JSON
###########
#code to write in your file, you need write the json_credential["message"]
###########
return ("ok")
if __name__ == '__main__':
app.run(host='0.0.0.0', port=1024, threaded=True)#start my flask app with local_host IP and specific port, if you don't specify the port it will run in the default port
In this case the JSON Input should be:
{"message":"your text"}
Please let me know if something is not clear, I even try this code on my local and the JSON is passed without problems.....
So you need run your python script and see that the API is running, if you had no JSON to send and was just a simple API that give back information you should have used even Chrome but in this case that you need send some JSON data I would advice you to use Postman.
See screenshot example:
I have a Python app running on Google App Engine. I am trying to perform an Oauth 2 authentication without using oauth libraries.
I need a session to store the information returned from the Google auth code (access token) and send it to the next request. When I try to store the JSON into a flask session key, my app goes to an Internal Server Error with no debug info. My code is practically a copy-paste from Google's HTTP Rest example in their Oauth2 for web server apps documentation (link commented in code).
import logging
import flask
from flask import render_template, session
import json
import urllib
from google.appengine.api import urlfetch
#Code from https://developers.google.com/identity/protocols/OAuth2WebServer
app = flask.Flask(__name__)
CLIENT_ID = '[].apps.googleusercontent.com'
CLIENT_SECRET = '[]'
SCOPE = 'email'
REDIRECT_URI = 'https://[].appspot.com/oauthcallback'
#check for last oauth step, if not go to intermediate steps
#app.route('/')
def index():
if 'credentials' not in flask.session:
return flask.render_template('index.html')
credentials = json.loads(flask.session['credentials'])
if credentials['expires_in'] <= 0:
return flask.redirect(flask.url_for('oauthcallback'))
else:
headers = {'Authorization': 'Bearer {}'.format(credentials['access_token'])}
req_uri = 'https://www.googleapis.com/oauth2/v2/userinfo'
r = requests.get(req_uri, headers=headers)
return r.text
#ask user to sign in, send code to googleapi to get token
#app.route('/oauthcallback')
def oauthcallback():
if 'code' not in flask.request.args:
auth_uri = ('https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id={}&redirect_uri={}&scope={}').format(CLIENT_ID, REDIRECT_URI, SCOPE)
return flask.redirect(auth_uri)
else:
auth_code = flask.request.args.get('code')
data = {'code': auth_code, 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, 'redirect_uri': REDIRECT_URI, 'grant_type': 'authorization_code'}
r = urlfetch.fetch("https://www.googleapis.com/oauth2/v4/token", payload=data, method="POST")
#return r.content #prints json
flask.session['credentials'] = r.content #breaks here
return flask.redirect(flask.url_for('index'))
if __name__ == '__main__':
import uuid
app.secret_key = str(uuid.uuid4())
app.debug = True
app.run()
Did you enable the redirect URI?
https://developers.google.com/api-client-library/python/auth/web-app
Create authorization credentials
Any application that uses OAuth 2.0 to access Google APIs must have authorization credentials that identify the application to Google's OAuth 2.0 server. The following steps explain how to create credentials for your project. Your applications can then use the credentials to access APIs that you have enabled for that project.
Open the Credentials page in the API Console.
Click Create credentials > OAuth client ID.
Complete the form. Set the application type to Web application. Applications that use languages and frameworks like PHP, Java, Python, Ruby, and .NET must specify authorized redirect URIs. The redirect URIs are the endpoints to which the OAuth 2.0 server can send responses.
For testing, you can specify URIs that refer to the local machine, such as http://localhost:8080. With that in mind, please note that all of the examples in this document use http://localhost:8080 as the redirect URI.