python-telegram-bot自定义过滤器失效,如何过滤群管理员消息?
问题分析与解决方案
错误原因
你的自定义过滤器失效的核心问题有两个:
- 同步方法不被调用:python-telegram-bot v21.x版本要求自定义过滤器的
filter方法必须是异步函数(使用async def声明),同步的filter方法会被库忽略,导致过滤器逻辑完全不执行,消息直接通过。 - 未实现正确的权限判断逻辑:你当前的
filter方法固定返回False,即使方法被调用也无法满足过滤管理员/群主的需求。
正确的自定义过滤器实现
要过滤掉群主(OWNER)和管理员(ADMINISTRATOR)的消息,需要在异步的filter方法中获取用户的聊天成员状态,再判断是否允许消息通过。
完整代码示例:
from telegram import Update, ChatMemberStatus from telegram.ext import Application, CallbackContext, MessageHandler, filters TOKEN = "你的机器人令牌" async def handle_message(update: Update, context: CallbackContext): user_status = await context.bot.get_chat_member(update.effective_chat.id, update.effective_user.id) status_message = f"用户 {update.effective_user.mention_html()} 在本群的状态:{user_status.status}" await context.bot.send_message(chat_id=update.effective_chat.id, text=status_message, parse_mode='HTML') class NotPrivilegedUserFilter(filters.BaseFilter): async def filter(self, update: Update, context: CallbackContext) -> bool: # 获取当前用户在聊天中的成员状态 user_status = await context.bot.get_chat_member( chat_id=update.effective_chat.id, user_id=update.effective_user.id ) # 返回True表示消息通过过滤器(非管理员/群主),False则过滤该消息 return user_status.status not in [ChatMemberStatus.ADMINISTRATOR, ChatMemberStatus.OWNER] if __name__ == "__main__": application = Application.builder().token(TOKEN).build() my_filter = NotPrivilegedUserFilter() application.add_handler(MessageHandler(filters=my_filter, callback=handle_message)) application.run_polling()
关键说明
- 异步方法要求:必须用
async def声明filter方法,这是v21版本异步架构的强制要求,否则方法不会被执行。 - 权限判断逻辑:通过
context.bot.get_chat_member()异步获取用户状态,判断是否属于需要过滤的权限角色,返回True则允许消息触发回调,False则拦截。 - 权限注意事项:机器人需要拥有查看聊天成员的权限,否则
get_chat_member会抛出权限异常,建议根据实际场景添加异常处理逻辑。
内容的提问来源于stack exchange,提问作者Евгений Крючков
相关产品推荐
相关产品推荐

