【问题标题】:how to send message when start private chat with python telegram bot与python电报机器人开始私人聊天时如何发送消息
【发布时间】:2020-03-31 18:52:46
【问题描述】:

我想写一个电报机器人。我希望我的机器人在任何用户开始与我的机器人私聊时发送消息。

这是我的代码

def start_chat(update: Update, context: CallbackContext):
    context.bot.send_message(
        chat_id=update.effective_chat.id,
        text=f"Welcome, nice to meet you{os.linesep}"
             f"/what would you like me to do?{os.linesep}"
    )
bot = Updater(token=token, use_context=True)
bot.dispatcher.add_handler(MessageHandler(Filters.text, start_chat))

是否有过滤器或处理程序可以仅在私人聊天的第一条消息中提醒我?

【问题讨论】:

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


    【解决方案1】:

    当用户启动机器人时,/start 命令将从用户发送到机器人。因此,您必须添加CommandHandler 而不是MessageHandler

    这是你修改后的代码:

    def start_chat(update: Update, context: CallbackContext):
        context.bot.send_message(
            chat_id=update.effective_chat.id,
            text=f"Welcome, nice to meet you{os.linesep}"
                 f"/what would you like me to do?{os.linesep}"
        )
    bot = Updater(token=token, use_context=True)
    bot.dispatcher.add_handler(CommandHandler('start', start_chat))
    

    或者您也可以使用MessageHandlerFilters.regex('^/start$') 来捕获/start 命令。

    bot.dispatcher.add_handler(MessageHandler(Filters.regex('^/start$'), start_chat))
    

    【讨论】:

      猜你喜欢
      • 2018-01-09
      • 1970-01-01
      • 2020-10-21
      • 2021-09-03
      • 2017-03-19
      • 1970-01-01
      • 2018-10-07
      • 1970-01-01
      • 2019-10-30
      相关资源
      最近更新 更多