aiogram CommunityChatAdded 类型详解:处理"被加入社群"服务消息的完整指南

原创2026-10-14 09:09:471,619 阅读
文章标签:Web框架异步编程后端即时通讯

aiogram CommunityChatAdded 类型详解:处理"被加入社群"服务消息的完整指南

CommunityChatAdded 是 aiogram 中用于表示"某个会话(chat)或机器人被添加到一个社群(community)"的服务消息对象,它与 aiogram.types.Message 的 community_chat_added 字段直接对应。本文将从对象结构与字段语义、底层源码实现、事件分发与内容类型判定、实战过滤与处理、以及测试验证五个层面展开,帮助你完整掌握该类型的解析方式与实际应用。

一、CommunityChatAdded 是什么:对象定义与字段说明

在 Telegram Bot API 中,"社群"(Community)是一个由多个会话组成的群体。当某个会话或机器人被加入这样的社群时,Telegram 会向 Bot 推送一条类型为 CommunityChatAdded 的服务消息。aiogram 在 aiogram/types/community_chat_added.py 中实现了该类型,其核心结构如下:

class CommunityChatAdded(TelegramObject):
    """
    Describes a service message about a chat or a bot being added to a community.

    Source: https://core.telegram.org/bots/api#communitychatadded
    """

    community: Community
    """The new community to which the chat or the bot belongs"""

可以看到,CommunityChatAdded 继承自 aiogram 所有 Telegram 对象共同的基类 TelegramObject(定义于 aiogram/types/base.py),并且只包含一个必填字段:

字段 类型 必填 说明
community Community 是 会话或机器人所属的新社群对象

该字段描述了"被添加进了哪个社群",是处理此类服务消息时的关键数据入口。

关联的 Community 对象

字段 community 的类型为 Community,其定义位于 aiogram/types/community.py,同样继承自 TelegramObject,由两个字段构成:

  • id: int:社群的唯一标识符。该数字可能超过 32 个有效位,某些编程语言在解释时可能出现困难或静默缺陷;但它最多有 52 个有效位,因此使用有符号 64 位整数(int64)或双精度浮点数(double)存储都是安全的。
  • name: str:社群的名称。

这个 id 字段的"52 位有效位"说明在 aiogram 中它被建模为普通的 Python int,但在跨语言传输(例如通过 JSON 传递给其他系统)时,需要注意避免使用 32 位整数类型导致精度丢失。

二、CommunityChatAdded 在 Message 中的位置与配套服务消息

在 aiogram 中,CommunityChatAdded 不是独立推送的事件,而是作为 Message 对象的一个可选字段出现。在 aiogram/types/message.py 中可以看到,Message 同时声明了三个与社群相关的字段:

community_chat_added: CommunityChatAdded | None = None
"""*Optional*. Service message: chat or bot added to a :class:`aiogram.types.community.Community`"""

community_chat_removed: CommunityChatRemoved | None = None
"""*Optional*. Service message: chat or bot removed from a :class:`aiogram.types.community.Community`"""

community_chat_joined: CommunityChatJoined | None = None
"""*Optional*. Service message: chat was joined by a user from a :class:`aiogram.types.community.Community`"""

与之配套的另外两个类型分别是:

  • CommunityChatRemoved(aiogram/types/community_chat_removed.py):描述"会话或机器人被从社群中移除"的服务消息,目前不包含任何字段,是一个空对象。
  • CommunityChatJoined(aiogram/types/community_chat_joined.py):描述"某个用户从社群加入了会话"的服务消息,结构与 CommunityChatAdded 相同,仅有一个 community 字段,但语义是"会话从哪个社群被加入"。

三者共同构成了 aiogram 对 Telegram 社群相关服务消息的完整建模,且均为 Message 上的可选字段,同一时间最多只有一个会被填充。

构造签名与类型提示支持

与 aiogram 中其他类型一致,CommunityChatAdded 的 __init__ 构造函数由 butcher 工具自动生成(见 aiogram/types/community_chat_added.py),仅用于类型检查与 IDE 提示,运行时仍由 Pydantic 基类完成初始化:

def __init__(
    __pydantic__self__, *, community: Community, **__pydantic_kwargs: Any
) -> None:
    super().__init__(community=community, **__pydantic_kwargs)

这保证了你可以在不依赖额外插件的情况下获得完整的 IDE 自动补全与类型检查支持。

三、事件分发:content_type 与消息类型判定

在实际收到更新时,aiogram 通过 Message.content_type 属性判断一条消息属于哪种内容类型。在 aiogram/types/message.py 中,content_type 的判定逻辑将社群相关的三种服务消息逐一映射:

if self.community_chat_added:
    return ContentType.COMMUNITY_CHAT_ADDED
if self.community_chat_removed:
    return ContentType.COMMUNITY_CHAT_REMOVED
if self.community_chat_joined:
    return ContentType.COMMUNITY_CHAT_JOINED
return ContentType.UNKNOWN

也就是说,只要 Message.community_chat_added 字段被填充,message.content_type 就会返回 ContentType.COMMUNITY_CHAT_ADDED。该枚举值定义于 aiogram/enums/content_type.py:

COMMUNITY_CHAT_ADDED = "community_chat_added"
COMMUNITY_CHAT_REMOVED = "community_chat_removed"
COMMUNITY_CHAT_JOINED = "community_chat_joined"

从源码结构看,这一判定是顺序短路求值:如果 community_chat_added 非空,就直接返回对应枚举,不再继续检查后续字段。因此,只要收到这类服务消息,content_type 的判定一定是唯一且可预期的。

四、实战:如何在 Bot 中过滤并处理被加入社群的消息

基于上述机制,可以用两种常见方式过滤 CommunityChatAdded 消息。

方式一:使用 MagicFilter(F 表达式)

aiogram 在包顶层导出了全局的 F 过滤器对象(见 aiogram/init.py),它可以按字段路径直接匹配事件对象:

from aiogram import F
from aiogram import Router

router = Router()

@router.message(F.community_chat_added)
async def on_chat_added_to_community(message: types.Message) -> None:
    community = message.community_chat_added.community
    await message.answer(
        f"本会话已被加入社群:{community.name}(id={community.id})"
    )

F.community_chat_added 的过滤机制基于 magic_filter 库实现,aiogram 在 aiogram/utils/magic_filter.py 中对它做了扩展,支持 as_() 等操作,可在过滤的同时将结果注入 handler 上下文。此外,也可以借助内容类型过滤:

from aiogram.enums import ContentType

@router.message(F.content_type == ContentType.COMMUNITY_CHAT_ADDED)
async def on_chat_added_to_community(message: types.Message) -> None:
    ...

方式二:通过 content_type 属性自行判断

如果你使用 without_dispatcher.py 这类手动轮询模式(参考 examples/without_dispatcher.py),可以在拿到 Message 后直接判断:

if message.community_chat_added is not None:
    community = message.community_chat_added.community
    # 处理"被加入社群"事件

由于 Message.content_type 会将其判定为 ContentType.COMMUNITY_CHAT_ADDED,你也可以写成 if message.content_type == ContentType.COMMUNITY_CHAT_ADDED:。两种写法的判定结果等价,前者直接访问字段、后者走内容类型映射。

取出社群信息后的典型用途

拿到 community 后,通常可以:

  • 记录该会话所属的社群 id 与名称,用于后续跨会话的权限或分组管理;
  • 在机器人被加入新社群时,向管理员发送通知或初始化会话配置;
  • 结合 F 过滤器的 as_() 将 community 注入 handler 参数,实现"仅当属于特定社群时才响应"的业务规则。

五、测试验证:仓库如何保证该类型的正确性

aiogram 在 tests/test_api/test_types/test_message.py 中为该类型提供了完整的测试覆盖,包括构造、内容类型映射与复制方法映射三层验证。

构造与服务消息样例

测试先构造了三类社群服务消息的标准样例(tests/test_api/test_types/test_message.py):

TEST_MESSAGE_COMMUNITY_CHAT_ADDED = Message(
    message_id=42,
    date=datetime.datetime.now(),
    chat=Chat(id=42, type="private"),
    from_user=User(id=42, is_bot=False, first_name="Test"),
    community_chat_added=CommunityChatAdded(
        community=Community(id=42, name="Test community"),
    ),
)

TEST_MESSAGE_COMMUNITY_CHAT_REMOVED = Message(
    message_id=42,
    date=datetime.datetime.now(),
    chat=Chat(id=42, type="private"),
    from_user=User(id=42, is_bot=False, first_name="Test"),
    community_chat_removed=CommunityChatRemoved(),
)

TEST_MESSAGE_COMMUNITY_CHAT_JOINED = Message(
    message_id=42,
    date=datetime.datetime.now(),
    chat=Chat(id=42, type="private"),
    from_user=User(id=42, is_bot=False, first_name="Test"),
    community_chat_joined=CommunityChatJoined(
        community=Community(id=42, name="Test community"),
    ),
)

注意 CommunityChatRemoved() 的构造不需要任何参数,与"目前不含字段"的源码定义一致。

内容类型映射测试

在 MESSAGES_AND_CONTENT_TYPES 映射表(tests/test_api/test_types/test_message.py)中,三种消息分别被断言映射到对应枚举:

[TEST_MESSAGE_COMMUNITY_CHAT_ADDED, ContentType.COMMUNITY_CHAT_ADDED],
[TEST_MESSAGE_COMMUNITY_CHAT_REMOVED, ContentType.COMMUNITY_CHAT_REMOVED],
[TEST_MESSAGE_COMMUNITY_CHAT_JOINED, ContentType.COMMUNITY_CHAT_JOINED],

复制方法映射测试

在 MESSAGES_AND_COPY_METHODS 表(tests/test_api/test_types/test_message.py)中,三类社群服务消息均映射为 None,即它们没有对应的复制发送方法——这符合直觉:服务消息无法通过 copy_message 等 API 复制,只能被动接收并处理。

六、小结:使用要点速查

要点 说明
触发场景 会话或 Bot 被添加到一个社群(community)时收到
承载位置 Message.community_chat_added(可选字段,见 aiogram/types/message.py)
唯一必填字段 community: Community,含 id(最多 52 个有效位的整数)与 name
内容类型 ContentType.COMMUNITY_CHAT_ADDED,见 aiogram/enums/content_type.py
推荐过滤方式 F.community_chat_added 或 F.content_type == ContentType.COMMUNITY_CHAT_ADDED
可复制性 不支持复制发送(copy_methods 映射为 None)
配套类型 CommunityChatRemoved(空对象)、CommunityChatJoined(同结构、不同语义)

掌握了 CommunityChatAdded 的结构、content_type 判定链路与过滤写法,你就可以在 aiogram 中准确识别并响应"被加入社群"这一服务消息,并将其纳入自己的会话管理与事件处理逻辑。

登录后查看全文
aiogram