与 python 电报机器人开始私人聊天时如何发送消息

how to send message when start private chat with 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))

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

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