【问题标题】:Can't setup a webhook for a telegram bot无法为电报机器人设置 webhook
【发布时间】:2018-03-19 19:03:30
【问题描述】:

我正在尝试在 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 文件更改如下,但仍然无法设置 webhook。它现在给我“502 bad gateway nginx”错误

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

runtime_config:
  python_version: 2

【问题讨论】:

  • 收到任何错误消息吗?另外,请提供此服务的 app.yaml 文件
  • "Hello World" 每当我运行它时都会显示。当我尝试运行 webhook() 时,我收到“错误请求浏览器(或代理)发送了此服务器无法理解的请求”。但我认为那是因为根本没有设置到电报的 webhook(我在 Telegram Bot API 中使用 getWebhookInfo 进行了检查)。
  • 请注意,flex env 与标准环境有很大不同,您可能需要阅读一下。你做了端口转发吗? cloud.google.com/appengine/docs/flexible/python/…

标签: python-2.7 google-app-engine telegram-webhook


【解决方案1】:

您的app.yaml 表示标准GAE 环境,其中仅通过app 变量及其处理程序/路由引用Flask 应用程序。 if __name__ == '__main__': 部分甚至可能不会执行。来自Creating a request handler for your Flask app

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

    appengine/standard/flask/tutorial/main.py

    app = Flask(__name__)
    

但您正尝试将其作为独立脚本运行 - 该脚本仅适用于灵活的 GAE 环境应用程序。来自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)

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

可能感兴趣:How to tell if a Google App Engine documentation page applies to the standard or the flexible environment

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-05-28
  • 2017-09-16
  • 2017-11-17
  • 2019-03-14
  • 1970-01-01
  • 1970-01-01
  • 2017-08-18
  • 1970-01-01
相关资源
最近更新 更多