【问题标题】:Deploying telegram bot to production along with Django web-site将电报机器人与 Django 网站一起部署到生产环境
【发布时间】:2021-02-26 19:27:40
【问题描述】:

这是我的 bot.py 脚本:

import logging

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)


# Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error.
def start(update, context):
    update.message.reply_text("Start")


def main():
   updater = Updater(TOKEN, use_context=True)
   dp = updater.dispatcher

   dp.add_handler(CommandHandler("start", start))

   updater.start_polling()

   updater.idle()


if __name__ == '__main__':
    main()

我可以通过python bot.py在本地运行它 但是,我不知道如何部署到 Django 生产服务器。

如何使它与view.py 一起工作?我必须为它创建一个视图吗? 有人可以帮忙吗?

【问题讨论】:

  • 您找到解决方案了吗?

标签: python django telegram-bot python-telegram-bot


【解决方案1】:

您需要在某处创建和存储Dispatcher(像单例一样)并手动序列化Update,而不使用内置更新程序。见example with no threading


from telegram import Bot, Update
from telegram.ext import Dispatcher

def create_dispatcher(token):
    # Create bot, update queue and dispatcher instances
    bot = Bot(token)
    
    dispatcher = Dispatcher(bot, None, workers=0)
    
    ##### Register handlers here #####
    
    return dispatcher


dispatcher = create_dispatcher(TOKEN_HERE)


def webhook_view(request)
    update = Update.de_json(json.loads(request.body.decode()), dispatcher.bot)
    dispatcher.process_update(update)
    return '{"status": "ok"}', 200

此外,您还需要setup Webhooks

【讨论】:

    【解决方案2】:

    一种可能性是将其作为管理命令包含在内并按计划运行该命令(如果您想部署到 Heroku https://devcenter.heroku.com/articles/scheduler,Heroku 调度程序很容易)。管理命令基本上执行您使用命令python manage.py your_command_name 定义的功能。如何编写自定义管理命令https://docs.djangoproject.com/en/3.1/howto/custom-management-commands/

    【讨论】:

    • 让我试试。如果成功,将发布答案,在此先感谢。
    猜你喜欢
    • 1970-01-01
    • 2013-10-15
    • 1970-01-01
    • 2018-09-05
    • 2017-08-18
    • 2012-08-03
    • 1970-01-01
    • 2018-09-08
    • 2018-09-05
    相关资源
    最近更新 更多