首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在google云函数上使用电报webhook?

如何在google云函数上使用电报webhook?
EN

Stack Overflow用户
提问于 2019-08-20 16:18:50
回答 2查看 1.9K关注 0票数 0

我已经在google cloud函数上使用python中的webhooks设置了一个电报机器人。基于互联网上的一些示例代码,我让它作为一个简单的echo-bot工作,但是它的结构与我在使用长轮询之前编写的bot非常不同:

代码语言:javascript
复制
# 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函数)。

如何将上面的逻辑转换成下面我更熟悉的逻辑:

代码语言:javascript
复制
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仪表板上产生错误)。

如有任何帮助,我们将不胜感激!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-08-20 17:39:56

我从 github telebot repo from yukuku,它在 App Engine 上设置了一个电报机器人,并使用 python 实现了 webhook。如前所述,您可能希望使用 App Engine 在同一个 main.py 文件中实现具有许多功能的机器人。 我刚刚尝试过,它对我有用。

票数 1
EN

Stack Overflow用户

发布于 2021-02-25 13:14:54

我做到了这是我的片段

代码语言:js
复制
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"
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57569416

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档