You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AIOGram的chat_member_handler未触发如何修复?

问题原因

你的handler不触发,核心问题不是handler写法本身,是你没有主动让Telegram向你的Bot推送ChatMemberUpdated类型的更新——AIOGram默认启动轮询时,不会自动订阅群成员变动类的更新,就算你关了隐私模式、给了Bot管理员权限,Telegram不推事件,handler自然不会执行。

修复步骤
  • 对应你使用的AIOGram版本,调整启动逻辑,显式声明要接收的更新类型
  • 启动前清理残留的webhook配置,避免旧配置拦截更新
  • 重启Bot进程让配置生效
对应版本的正确代码示例

AIOGram 3.x 版本(当前主流版本)

from aiogram import Bot, Dispatcher, types
from aiogram.filters.chat_member_updated import ChatMemberUpdatedFilter, JOIN_TRANSITION, LEAVE_TRANSITION

# 初始化bot和dp的代码省略,沿用你自己的配置即可

# 精准匹配用户加入事件,无需手动判断状态
@dp.chat_member(ChatMemberUpdatedFilter(JOIN_TRANSITION))
async def user_joined_chat(update: types.ChatMemberUpdated):
    print(f"用户 {update.new_chat_member.user.full_name} 加入了群组 {update.chat.title}")

# 精准匹配用户主动退出/被管理员移出事件
@dp.chat_member(ChatMemberUpdatedFilter(LEAVE_TRANSITION))
async def user_left_chat(update: types.ChatMemberUpdated):
    print(f"用户 {update.old_chat_member.user.full_name} 退出/被移出了群组 {update.chat.title}")

if __name__ == "__main__":
    # 启动前执行:删除残留webhook,丢弃过期的待处理更新
    # await bot.delete_webhook(drop_pending_updates=True)
    # 关键配置:自动扫描所有注册handler对应的更新类型,无需手动枚举,不会遗漏事件
    dp.run_polling(bot, allowed_updates=dp.resolve_used_update_types())

AIOGram 2.x 旧版本

from aiogram import Bot, Dispatcher, types
from aiogram.utils import executor

# 初始化bot和dp的代码省略,沿用你自己的配置即可

@dp.chat_member_handler()
async def chat_member_changed(update: types.ChatMemberUpdated):
    old_status = update.old_chat_member.status
    new_status = update.new_chat_member.status
    print(f"成员状态变动:{old_status} -> {new_status}")

if __name__ == "__main__":
    # 启动轮询时显式加入chat_member更新类型
    executor.start_polling(
        dp,
        allowed_updates=["chat_member", "message"], # 可自行追加你需要的其他更新类型
        skip_updates=True
    )
额外检查项
  • 确认你在BotFather处关闭隐私模式后,已经重启过Bot进程
  • 确认Bot在群组内没有被限制读取群成员信息(管理员默认拥有该权限,普通成员状态的Bot只要群内未开特殊限制也能收到事件)
  • 不要用Bot自身的加群/退群事件测试普通用户事件,Bot自身的状态变动属于my_chat_member更新类型,需要单独注册handler处理

内容的提问来源于stack exchange,提问作者ShkiperDesna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 07:06:10