问题
I'm trying make a simple telegram bot in Google App Engine.
When I open the console in GAE, and enter the following, the webhook gets set up just fine
curl -F "url=https://example.appspot.com:8443/<token>" -F "certificate=@certificate.pem"
https://api.telegram.org/bot<token>/setWebhook
But when I run this python script in GAE (of course, having deleted the previous webhook), the webhook doesn't get set up. I couldn't figure out what did I do wrong.
import sys
import os
import time
from flask import Flask, request
import telegram
# CONFIG
TOKEN = '<token>'
HOST = 'example.appspot.com' # Same FQDN used when generating SSL Cert
PORT = 8443
CERT = "certificate.pem"
CERT_KEY = "key.pem"
bot = telegram.Bot(TOKEN)
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello World!'
@app.route('/' + TOKEN, methods=['POST','GET'])
def webhook():
update = telegram.Update.de_json( request.get_json(force = True), bot )
chat_id = update.message.chat.id
bot.sendMessage(chat_id = chat_id, text = 'Hello, there')
return 'OK'
def setwebhook():
bot.setWebhook(url = "https://%s:%s/%s" % (HOST, PORT, TOKEN), certificate = open(CERT, 'rb'))
if __name__ == '__main__':
context = (CERT, CERT_KEY)
setwebhook()
time.sleep(5)
app.run(host = '0.0.0.0', port = PORT, ssl_context = context, debug = True)
The app.yaml file is as follows:
runtime: python27
api_version: 1
threadsafe: yes
- url: .*
script: main.app
libraries:
- name: webapp2
version: "2.5.2"
- name: ssl
version: latest
EDIT: I changed the app.yaml file as follows but I still can't set up a webhook. It now gives me "502 bad gateway nginx" error
runtime: python
env: flex
entrypoint: gunicorn -b :8443 main:app
threadsafe: true
runtime_config:
python_version: 2
回答1:
Your app.yaml
indicates a standard GAE environment, where a Flask application is referenced solely through the app
variable and its handlers/routes. The if __name__ == '__main__':
section may not even execute. From Creating a request handler for your Flask app:
Add this line to create an instance of the Flask class and assign it to a variable called app:
appengine/standard/flask/tutorial/main.py
app = Flask(__name__)
But you're attempting to run it as a standalone script - which only works locally for a flexible GAE environment app. From Hello World code review:
appengine/flexible/hello_world/main.py
... if __name__ == '__main__': # This is used when running locally. Gunicorn is used to run the # application on Google App Engine. See entrypoint in app.yaml. app.run(host='127.0.0.1', port=8080, debug=True)
If you do want to run it this way you need to reconfigure you app as a flexible environment one.
Potentially of interest: How to tell if a Google App Engine documentation page applies to the standard or the flexible environment
来源:https://stackoverflow.com/questions/49370552/cant-setup-a-webhook-for-a-telegram-bot