无法为电报机器人设置webhook

时间:2018-03-19 19:03:30

标签: python-2.7 google-app-engine telegram-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文件如下,但我仍然无法设置webhook。它现在给了我“502 bad gateway nginx”错误

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

runtime_config:
  python_version: 2

1 个答案:

答案 0 :(得分:1)

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

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

         

    appengine/standard/flask/tutorial/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)
    
  2.   

但是你试图将它作为一个独立的脚本运行 - 它只适用于灵活的GAE环境应用程序。来自Hello World code review

  

appengine/flexible/hello_world/main.py

    import numpy as np
    import matplotlib.pyplot as plt
    n=1000
    x=np.random.randn(n,1)
    y=np.random.randn(n,1)
    color_xy=np.arctan2(y,x)

    plt.scatter(x,y,s=75,c=color_xy,alpha=0.5)

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

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