Python Telegram Bot如何接受频道/群组的待处理成员加入请求?
在Python Telegram Bot中接受频道/群组待处理加入请求的方法
当然有对应的方法,你可以通过approve_chat_join_request来批准待处理的加入请求,这个方法是Telegram Bot API提供的,python-telegram-bot库已经封装到了Bot类中。
核心方法说明
approve_chat_join_request需要两个必填参数:
chat_id: 目标频道/群组的ID(格式和你代码中的一致,频道需带-100前缀)user_id: 提交加入请求的用户ID
结合现有代码的实现示例
你可以在获取待处理请求的基础上,添加一键批准的交互逻辑,比如用Inline按钮:
from telegram import InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import CallbackQueryHandler def get_pending_requests(update: Update, context: CallbackContext): try: chat_id = -1001138138008 bot = context.bot pending_requests = bot.get_chat_join_requests(chat_id) if not pending_requests: update.message.reply_text("当前没有待处理的加入请求。") return response = "待处理请求:\n" keyboard = [] for request in pending_requests: username = request.from_user.username or "无用户名" user_info = f"- {request.from_user.first_name} (@{username})" response += user_info + "\n" # 生成批准按钮,回调数据包含频道ID和用户ID keyboard.append([InlineKeyboardButton( f"批准 {request.from_user.first_name}", callback_data=f"approve_{chat_id}_{request.from_user.id}" )]) reply_markup = InlineKeyboardMarkup(keyboard) update.message.reply_text(response, reply_markup=reply_markup) except Exception as e: update.message.reply_text(f"发生错误:{e}") # 处理按钮回调逻辑 def handle_join_request_actions(update: Update, context: CallbackContext): query = update.callback_query query.answer() if query.data.startswith("approve_"): # 解析回调数据中的频道ID和用户ID _, chat_id, user_id = query.data.split("_") chat_id = int(chat_id) user_id = int(user_id) try: context.bot.approve_chat_join_request(chat_id=chat_id, user_id=user_id) query.edit_message_text(text=f"已批准用户ID {user_id}的加入请求") except Exception as e: query.edit_message_text(text=f"批准失败:{e}") # 记得在Bot的dispatcher中注册回调处理器 # dispatcher.add_handler(CallbackQueryHandler(handle_join_request_actions))
额外补充:拒绝加入请求
如果需要拒绝请求,可以使用decline_chat_join_request方法,参数和批准方法完全一致,只需替换方法名即可。
注意事项
- 你的Bot必须是目标频道/群组的管理员,且拥有「管理成员」的权限,否则会触发权限错误。
- 确保使用正确的频道ID(带
-100前缀),群组ID可以直接使用负数形式。
内容的提问来源于stack exchange,提问作者poria bagheri
相关产品推荐
相关产品推荐

