簡體   English   中英

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM