无法为电报机器人设置 Webhook



我正在尝试在Google App Engine中制作一个简单的电报机器人。

当我在 GAE 中打开控制台并输入以下内容时,Webhook 设置得很好

curl -F "url=https://example.appspot.com:8443/<token>"  -F "certificate=@certificate.pem" 
      https://api.telegram.org/bot<token>/setWebhook

但是当我在 GAE 中运行这个 python 脚本时(当然,删除了以前的 webhook(,webhook 没有设置。我不知道我做错了什么。

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)

app.yaml 文件如下所示:

runtime: python27
api_version: 1
threadsafe: yes
- url: .*
  script: main.app
libraries:
- name: webapp2
  version: "2.5.2"
- name: ssl
  version: latest

编辑:我按如下方式更改了 app.yaml 文件,但我仍然无法设置网络钩子。它现在给我"502 错误的网关 nginx"错误

runtime: python
env: flex
entrypoint: gunicorn -b :8443 main:app
threadsafe: true
runtime_config:
  python_version: 2

您的app.yaml表示标准 GAE 环境,其中 Flask 应用程序仅通过 app 变量及其处理程序/路由进行引用。if __name__ == '__main__':部分甚至可能无法执行。从为 Flask 应用创建请求处理程序:

  1. 添加此行以创建 Flask 类的实例,并将其分配给名为 app 的变量:

    应用引擎/标准/烧瓶/教程/主要.py

    app = Flask(__name__)
    

但您尝试将其作为独立脚本运行 - 该脚本仅适用于灵活的 GAE 环境应用。来自Hello World代码审查:

应用引擎/灵活/hello_world/主要.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)

如果您确实想以这种方式运行它,则需要将应用程序重新配置为灵活的环境应用程序。

可能感兴趣的内容:如何判断 Google App Engine 文档页面适用于标准环境还是灵活环境

最新更新