首页 > 解决方案 > Python-Telegram-Bot:通过不同模块中的机器人发送消息

问题描述

我正在使用 python-telegram-bot 库编写一个 Telegram 机器人。
当发布新的 YoutubeChannel 时,机器人应该向用户发送消息。我创建了一个 telegram_bot.py,在其中创建了一个 TelegramBot 类。在这个类中,我有这个功能:
telegram_bot.py

def __init__(self):
    self.updater = Updater(token=telegram_token, use_context=True)
    self.dispatcher = self.updater.dispatcher  
    self.updater.start_polling()

def send_message(self, text_message, context: CallbackContext):
    context.bot.send_message(
        chat_id="@<<my username>>", text=text_message)

在 main.py 中,我有一行代码应该使用上述函数发送消息,如下所示:
main.py

from telegram_bot import TelegramBot  

tg_bot = TelegramBot()
tg_bot.send_message("New video!")

但是,当我运行上面的代码时,我得到了这个错误:

类型错误:send_message() 缺少 1 个必需的位置参数:'context'

但是在send_message定义中,我已经定义了上下文

标签: pythontelegrampython-telegram-bot

解决方案


以这种方式解决:
main.py

tg_bot = TelegramBot()
tg_bot.send_message("New video!", context=tg_bot.dispatcher)

推荐阅读