flask - 通过 pythonanywhere.com 上的 pyTelegramBotAPI 和 Flask 使用 Telegram bot webhook

标签 flask telegram telegram-bot pythonanywhere py-telegram-bot-api

问题是关于使用 pyTelegramBotAPI 模块在 Telegram 机器人中使用 webhook。
我正在使用 pythonanywhere.com 来托管机器人。

以下代码工作正常:

from flask import Flask, request
import telebot

secret = "A_SECRET_NUMBER"
bot = telebot.TeleBot ('YOUR_AUTHORIZATION_TOKEN')
bot.set_webhook("https://YOUR_PYTHONANYWHERE_USERNAME.pythonanywhere.c..
}".format(secret), max_connections=1)

app = Flask(__name__)
@app.route('/{}'.format(secret), methods=["POST"])
def telegram_webhook():
   update = request.get_json()
   if "message" in update:
   text = update["message"]["text"]
   chat_id = update["message"]["chat"]["id"]
   bot.sendMessage(chat_id, "From the web: you said '{}'".format(text))
return "OK"

但是当我使用 example 中所示的消息处理程序时,我没有收到机器人的回答:
# Process webhook calls
@app.route(WEBHOOK_URL_PATH, methods=['POST'])
def webhook():
   if flask.request.headers.get('content-type') == 'application/json':
   json_string = flask.request.get_data().decode('utf-8')
   update = telebot.types.Update.de_json(json_string)
   bot.process_new_updates([update])
   return ''
else:
   flask.abort(403)

# Handle '/start' and '/help'
@bot.message_handler(commands=['help', 'start'])
   def send_welcome(message):
   bot.reply_to(message,
   ("Hi there, I am EchoBot.\n"
   "I am here to echo your kind words back to you."))

# Handle all other messages
@bot.message_handler(func=lambda message: True, content_types=['text'])
   def echo_message(message):
   bot.reply_to(message, message.text)

我尝试了来自不同库的示例,但仍然没有答案。

有任何想法吗?

如果您可以在 pythonanywhere.com 上分享 Telegram “echo-bot”的工作示例,那就太好了。

谢谢。

最佳答案

您应该在 TeleBot 构造函数中禁用线程,如下所示:

bot = telebot.TeleBot('YOUR_AUTHORIZATION_TOKEN', threaded=False)

我有同样的问题,并在这里找到了解决方案:
https://www.pythonanywhere.com/forums/topic/9562/#id_post_40177

免费的 PythonAnywhere 帐户无法使用线程。

关于flask - 通过 pythonanywhere.com 上的 pyTelegramBotAPI 和 Flask 使用 Telegram bot webhook,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42251231/

相关文章:

node.js - npm ELIFECYCLE 错误退出状态 1

telegram - 如何使用 Telegram bot chat API 获取用户图片/头像?

javascript - Telegram Bot : Sending an image only once, 下次不再下载

bots - 电报机器人 - 保留问题和答案

sockets - socket.gaierror : [Errno 8] nodename nor servname provided,或在 flask 应用程序中未知

javascript - 内存中创建的 Zip 文件已损坏

python - 使用 OpenCV 图像的 Flask 视频流

python - 如何使用 Python post 请求和 Telegram 机器人在 Telegram 上发送具有 InlineKeyboardMarkup 的照片

python - 自定义 flask 应用程序在本地主机上运行良好,但向外部访问者返回 500 响应

javascript - 单击后如何隐藏或删除内联按钮?