【问题标题】:How to make Python-Telegram_bot send a message without getting a commad?如何让 Python-Telegram Bot 在没有命令的情况下发送消息?
【发布时间】:2020-12-17 23:49:01
【问题描述】:

我正在使用 Python-Telegram-bot 制作一个电报机器人。我想让它向一个特定的用户(在这种情况下是我自己)发送一条消息以选择一个选项。之后,它应该将该选项作为命令并照常工作。但 30 分钟后......它应该向我发送相同的消息,让我像以前一样选择一个选项。我怎样才能让我工作?

def start(update: Update, context: CallbackContext) -> None:
    user = update.message.from_user.username
    print(user)
    context.bot.send_message(chat_id=update.effective_chat.id, text= "Choose an option. ('/option1' , '/option 2', '/...')")


def main():

    updater = Updater("<MY-BOT-TOKEN>", use_context=True)

    updater.dispatcher.add_handler(CommandHandler('start', start))

    updater.start_polling()
    updater.idle()


if __name__ == '__main__':
    main()

我希望它在不获取 /start 命令(更新)的情况下运行。但在此之后......会有正常的功能会得到更新,30分钟后我想再次运行这个“开始”功能而不得到更新。

【问题讨论】:

  • 您已将您的私人 BOT 令牌放入问题中。我删除了它,但它仍然在历史记录中可见。考虑在@botFather 更新令牌以防止其他人滥用它!
  • 我在stackoverflow.com/a/64681056/9095551 已经回答了类似的问题。您使用polling 走在正确的轨道上,您需要在第一次交互期间获取并存储chat_id,然后您可以从您的应用中触发消息(在后台线程中 - 即每 30 分钟一次)
  • @BeppeC 如果我想每 30 分钟运行一次 start() 怎么办?它要求缺少的参数。
  • @BeppeC 当您第一次运行它时...将更新和上下文保存在一个变量中。然后每 30 分钟将其作为参数传递一次。确保从同一个聊天中保存更新。

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


【解决方案1】:

您可以从更新程序或调度程序获取bot 对象:

updater = Updater('<bot-token>')
updater.bot.sendMessage(chat_id='<user-id>', text='Hello there!')

# alternative:
updater.dispatcher.bot.sendMessage(chat_id='<user-id>', text='Hello there!')

【讨论】:

    猜你喜欢
    • 2018-09-07
    • 1970-01-01
    • 2018-09-24
    • 2018-04-20
    • 1970-01-01
    • 2020-12-29
    • 2019-05-21
    • 2018-09-21
    • 1970-01-01
    相关资源
    最近更新 更多