Python3中Telegram Bot如何通过chat_id向点击Inline按钮的用户发送私信
问题修正:你当前获取的ID是错误的
你代码中写的Chat_id = query.message.chat.id拿到的是按钮消息所在的群组ID,不是点击按钮的用户ID,你需要先替换为正确的用户ID获取逻辑:
user_id = query.from_user.id
私信发送实现
直接调用context.bot.send_message方法即可实现给指定用户发私信,完整的button函数修改后如下:
def button(update: Update, context: CallbackContext) -> None: """Parses the CallbackQuery and show the alert.""" query = update.callback_query query.answer(text=f"Thanks for responding", show_alert=True) # 获取点击按钮的用户ID user_id = query.from_user.id # 发送私信 context.bot.send_message( chat_id=user_id, text="Text of the message will be here..." )
注意事项
- 要保证用户此前主动给你的Bot发送过至少一条消息(比如触发过/start指令),否则Telegram会禁止Bot主动给用户发私信,抛出403权限错误
- 如果需要处理用户未和Bot对话过的场景,可以引导用户先点击Bot对话框发送任意消息再操作
内容的提问来源于stack exchange,提问作者Raja Anss
相关产品推荐
相关产品推荐

