使用 webhook 的 python-telegram-bot

问题描述 投票:0回答:1

我正在开发一个电报机器人,在我的个人机器(Mac)上运行 该机器人在特定环境中的 python 上运行,并在该环境中安装了模块

现在机器人已经很好了,我想将它放在运行 Apache 的 Web 服务器上。但我有一些疑问。

1)我必须在服务器上为每个人安装每个模块,或者我可以为这个特定的机器人创建一个环境,然后 apache 在该环境上运行该机器人?

2)我正在使用 getUpdates (使我的机器非常慢,但更好地调试错误),现在我想使用 webhook 运行。如果 webhook 而不是 getUpdates 去电报服务器,那么到底需要做什么改变才能让他工作?今天启动并继续运行的代码是:

def main():

updater = Updater(bot_token)
dp = updater.dispatcher

# Commands
dp.add_handler(CommandHandler("info", ranking_putaria))
dp.add_handler(CommandHandler("start", start))

# Start checking updates
dp.add_handler(MessageHandler(Filters.text,echo_msg))
dp.add_handler(MessageHandler(Filters.video | Filters.photo | Filters.document, echo_file))
dp.add_handler(MessageHandler(Filters.sticker, echo_sticker))

# Log errors
#dp.add_error_handler(error)

# start the bot
updater.start_polling()

# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()


if __name__ == '__main__':
main()
python python-telegram-bot
1个回答
1
投票

您可以通过以下步骤设置 webhook:

  1. 在您的电报机器人对象上设置 webhook:

    import os
    PORT = int(os.environ.get('PORT', '5000'))
    bot = telegram.Bot(token = "YOUR TOKEN HERE")
    bot.setWebhook("YOUR WEB SERVER LINK HERE" + "YOUR TOKEN HERE")
    
  2. 用 webhook 替换长轮询 - 即用

     替换 
    updater.start_polling()

    updater.start_webhook(listen="0.0.0.0",
                          port=PORT,
                          url_path="YOUR TOKEN HERE")
    updater.bot.setWebhook("YOUR WEB SERVER LINK HERE" + "YOUR TOKEN HERE")
    updater.idle()
    

当我使用 Heroku 托管我的机器人时,这对我有用。干杯!

© www.soinside.com 2019 - 2024. All rights reserved.