使用python telegram bot开始私人聊天时如何发送消息

时间:2020-03-31 08:52:37

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

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

这是我的代码

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))

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

1 个答案:

答案 0 :(得分:0)

当用户启动漫游器时,/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))