我已经在google cloud函数上使用python中的webhooks设置了一个电报机器人。基于互联网上的一些示例代码,我让它作为一个简单的echo-bot工作,但是它的结构与我在使用长轮询之前编写的bot非常不同:
# main.py
import os
import telegram
def webhook(request):
bot = telegram.Bot(token=os.environ["TELEGRAM_TOKEN"])
if request.method == "POST":
update = telegram.Update.de_json(request.get_json(force=True), bot)
chat_id = update.message.chat.id
# Reply with the same message
bot.sendMessage(chat_id=chat_id, text=update.message.text)
return "ok"我不知道如何向其中添加更多的处理程序或不同的函数,尤其是因为云函数只需要我来命名一个函数从脚本运行(在本例中为webhook函数)。
如何将上面的逻辑转换成下面我更熟悉的逻辑:
import os
TOKEN = "TOKEN"
PORT = int(os.environ.get('PORT', '8443'))
updater = Updater(TOKEN)
# add example handler
def start(update, context):
context.bot.send_message(chat_id=update.message.chat_id, text="Hello, I am dice bot and I will roll some tasty dice for you.")
start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)
# start webhook polling
updater.start_webhook(listen="0.0.0.0",
port=PORT,
url_path=TOKEN)
updater.bot.set_webhook("https://.herokuapp.com/" + TOKEN)
updater.idle()这段代码与长轮询具有相同的结构,因此我知道如何添加额外的处理程序。然而,它有两个问题:
它是文档中的代码片段heroku,所以我不知道这是否同样适用于google云函数
这个不会产生一个我可以在云函数中调用的函数,我尝试将上面的所有代码包装在一个大函数中webhook简单地运行它,但它不起作用(并且不会在我的google仪表板上产生错误)。
如有任何帮助,我们将不胜感激!
发布于 2019-08-20 17:39:56
我从 github telebot repo from yukuku,它在 App Engine 上设置了一个电报机器人,并使用 python 实现了 webhook。如前所述,您可能希望使用 App Engine 在同一个 main.py 文件中实现具有许多功能的机器人。
我刚刚尝试过,它对我有用。
发布于 2021-02-25 13:14:54
我做到了这是我的片段
from telegram import Bot,Update
from telegram.ext import CommandHandler,Dispatcher
import os
TOKEN = os.getenv('TOKEN')
bot = Bot(token=TOKEN)
dispatcher = Dispatcher(bot,None,workers=0)
def start(update,context):
context.bot.send_message(chat_id=update.effective_chat.id,text="I am a bot, you can talk to me")
dispatcher.add_handler(CommandHandler('start',start))
def main(request):
update = Update.de_json(request.get_json(force=True), bot)
dispatcher.process_update(update)
return "OK"
# below function to be used only once to set webhook url on telegram
def set_webhook(request):
global bot
global TOKEN
s = bot.setWebhook(f"{URL}/{TOKEN}") # replace your functions URL,TOKEN
if s:
return "Webhook Setup OK"
else:
return "Webhook Setup Failed"https://stackoverflow.com/questions/57569416
复制相似问题