【问题标题】:How to set webhook for telegram bot in python?如何在 python 中为电报机器人设置 webhook?
【发布时间】:2021-05-28 21:02:27
【问题描述】:

我创建了一个机器人,它与 heroku 配合得很好。我想使用 webhook 来处理消息,但我不明白该怎么做。这是我所做的:

  1. 将此代码上传到 heroku

telegrampiu24.py

import telepot
import json
from flask import Flask, request, abort
from telepot.namedtuple import *
bot = telepot.Bot("123456789:abcdefghijklmnopqrstuvwxyz")

app = Flask(__name__)

@app.route('/', methods=['POST','GET'])
def webhook():
    if request.method == 'POST':
        print("post")
        return Response('post',status=200)
    else:
        print("get")
        return Response('get',status=200)

if __name__ == '__main__' or __name__ == '__telegrampiu24__':
    app.run()
  1. 使用 https://api.telegram.org/bot123456789:abcdefghijklmnopqrstuvwxyz/setwebhook?url=https://provaxyz1.herokuapp.com/ 设置 webhook(显然使用我的正确令牌)

我被困在这里,因为如果我向我的机器人发送消息并查看 heroku 上的日志,我总是会收到错误

2021-02-26T13:12:24.889213+00:00 app[test.1]:  * Serving Flask app "telegrampiu24" (lazy loading)
2021-02-26T13:12:24.889246+00:00 app[test.1]:  * Environment: production
2021-02-26T13:12:24.889247+00:00 app[test.1]:    WARNING: This is a development server. Do not use it in a production deployment.
2021-02-26T13:12:24.889247+00:00 app[test.1]:    Use a production WSGI server instead.
2021-02-26T13:12:24.889290+00:00 app[test.1]:  * Debug mode: off
2021-02-26T13:12:24.891889+00:00 app[test.1]:  * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
2021-02-26T13:12:26.000000+00:00 app[api]: Build succeeded
2021-02-26T13:13:02.086234+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=POST path="/" host=provaxyz1.herokuapp.com request_id=54bdbd45bdf fwd="IP" dyno= connect= service= status=503 bytes= protocol=https

我不明白我做错了什么,非常感谢任何帮助!提前致谢

【问题讨论】:

  • Procfile 是什么样的?
  • 测试:python "telegrampiu24.py"

标签: python flask heroku bots telegram


【解决方案1】:

看,The Procfile上的文档:

Heroku 应用程序的 web 进程类型很特殊:它是唯一可以从 Heroku 路由器接收外部 HTTP 流量的进程类型。如果您的应用包含 Web 服务器,则应将其声明为应用的 web 进程。

考虑到这一点,您的错误:No web processes running 建议您将Procfile 更改为包含:

web: python "telegrampiu24.py" 

这个问题以前不会发生,因为在你的机器人中加入 webhook 支持之前,它不需要接收 HTTP 流量,因为另一种方法使用“轮询”,其中进程作为客户端连接到电报的服务器。

尽管注意这仍然是 Flask 的开发服务器。从长远来看,您应该考虑使用像 gunicorn 这样的生产 WSGI 服务器进行部署。将gunicorn 添加到您的requirements.txt,然后拥有Procfile:

web: gunicorn telegrampiu24:app

【讨论】:

  • 真的非常感谢您的回答,非常有帮助!即使有些事情我现在还不完全清楚,它也可以工作!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-16
  • 2021-01-21
  • 2017-11-17
  • 2019-03-14
  • 1970-01-01
  • 2017-09-11
  • 1970-01-01
相关资源
最近更新 更多