如何用Python aiogram实现点击Inline按钮添加机器人至目标聊天?
用aiogram实现引导添加机器人至指定聊天的Inline按钮
要实现你需要的功能,需使用aiogram 3.x版本(依赖Telegram Bot API 6.0+的request_chat特性,aiogram 2.x不支持),核心是通过带request_chat参数的Inline按钮触发聊天选择窗口,再处理用户选中后的聊天信息完成机器人入群操作,具体实现如下:
核心实现代码
from aiogram import Bot, Dispatcher, types from aiogram.filters import CommandStart from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton, ChatShared from aiogram import Router import asyncio # 替换为你的机器人令牌 API_TOKEN = 'YOUR_BOT_TOKEN' router = Router() # 发送带功能按钮的欢迎消息 @router.message(CommandStart()) async def send_welcome(message: types.Message): # 配置聊天请求按钮 add_to_chat_btn = InlineKeyboardButton( text="添加我到你的聊天", request_chat=types.KeyboardButtonRequestChat( request_id=1, # 自定义请求ID,用于区分不同的聊天请求 chat_is_channel=False, # 不允许选择频道,仅开放群聊/超级群 user_admin_rights=types.ChatAdministratorRights( can_invite_users=True # 要求用户在目标聊天拥有邀请权限 ), bot_admin_rights=types.ChatAdministratorRights( # 按需设置机器人入群后需要的权限 can_invite_users=True, can_delete_messages=True, can_manage_chat=True ) ) ) markup = InlineKeyboardMarkup(inline_keyboard=[[add_to_chat_btn]]) await message.answer("点击下方按钮将我添加到你的聊天:", reply_markup=markup) # 处理用户选中聊天后的回调 @router.message() async def handle_chat_shared(message: types.Message, bot: Bot): if message.chat_shared and message.chat_shared.request_id == 1: chat_id = message.chat_shared.chat_id try: # 尝试加入目标聊天 await bot.join_chat(chat_id) await message.answer(f"已成功添加到聊天(ID:{chat_id})") except Exception as e: await message.answer(f"添加失败:{str(e)}") # 启动机器人 async def main(): bot = Bot(token=API_TOKEN) dp = Dispatcher() dp.include_router(router) await dp.start_polling(bot) if __name__ == '__main__': asyncio.run(main())
关键参数说明
KeyboardButtonRequestChat核心配置:request_id:自定义标识,用于区分多个不同的聊天请求场景。chat_is_channel:控制是否允许用户选择频道,设为False则仅支持群聊/超级群。user_admin_rights:指定用户必须拥有的聊天权限,确保用户能邀请机器人入群。bot_admin_rights:声明机器人入群后需要的管理员权限,用户选择聊天时会看到权限申请提示。
注意事项
- 需在BotFather中开启机器人的
groups/supergroups权限(通过/setprivacy等命令配置)。 - 若目标聊天为私有群,用户必须是该群管理员且拥有邀请权限,机器人才能成功加入。
- 部分聊天可能设置了机器人加入限制,此时会抛出异常,需做好错误捕获处理。
内容的提问来源于stack exchange,提问作者freezy
相关产品推荐
相关产品推荐

