我试图在不等待用户响应的情况下使用 Python-Telegram-Bot 发送消息,但无法让它工作,而且我没有收到任何错误。
Code:
def echo(context):
context.bot.send_message(chat_id=-516017547, text='test')
#chat_id is the group id I found by going to:
#https://api.telegram.org/bot<MY_API>/getUpdates
def main():
updater = Updater(API)
dp = updater.dispatcher
echo_handler = MessageHandler(Filters.text & (~Filters.command), echo)
dp.add_handler(echo_handler)
updater.start_polling()
updater.idle()
main()
在
python-telegram-bot
中,处理程序在那里处理传入的更新 - 而不是别的。但是,要调用 bot 方法,您只需要一个 telegram.Bot
的实例。在您的 echo
函数中,它可以用作 context.bot
。但是,它也可以在 main
中用作 updater.bot
或 updater.dispatcher.bot
。请注意,您也可以使用完全没有 Updater
的机器人实例:
from telegram import Bot
bot = Bot(TOKEN)
bot.send_message(...)
PS:如果你想使用
echo
作为 MessageHandler
的回调,它必须完全接受参数 update
和 context
.
更新:这个回复是为 PTB <= v13.x. Since v20.0, PTB is based on the
asyncio
框架写的,这使得上面的代码片段无效。请查看 PTBs wiki,了解它现在是如何工作的。
免责声明:我目前是
python-telegram-bot
.的维护者