☰
aiogram 中的 BackgroundType:聊天背景类型的完整数据模型与实战解析
2026/10/13 6:48:36 网站建设 项目流程
  • 后端
  • 即时通讯
  • API设计

【免费下载链接】aiogram

aiogram is a modern and fully asynchronous framework for Telegram Bot API written in Python using asyncio

项目地址:https://gitcode.com/gh_mirrors/ai/aiogram
点击查看免费下载

本篇指南聚焦 aiogram(基于 asyncio 的异步 Telegram Bot API 框架)中BackgroundType对象的完整数据模型。BackgroundType是 Telegram Bot API 中描述"聊天背景"类型的核心类型,用于表示纯色填充、JPEG 壁纸、PNG/TGV 图案以及内置聊天主题四种形态。读完本文,你将掌握BackgroundType及其四种子类型的全部字段与取值约束,理解其与BackgroundFill(背景填充方式)、ChatBackground(聊天背景容器)和Message.chat_background_set(背景设置服务消息)之间的调用关系,并能在 aiogram 事件处理中正确解析这类更新。

BackgroundType 是什么:一个多态的背景描述对象

在 Telegram 官方 Bot API 中,BackgroundType用于描述一个背景的类型。aiogram 在 aiogram/types/background_type.py 中将其建模为一个继承自TelegramObject的基类:

from .base import TelegramObject class BackgroundType(TelegramObject): """ This object describes the type of a background. Currently, it can be one of - aiogram.types.background_type_fill.BackgroundTypeFill - aiogram.types.background_type_wallpaper.BackgroundTypeWallpaper - aiogram.types.background_type_pattern.BackgroundTypePattern - aiogram.types.background_type_chat_theme.BackgroundTypeChatTheme """

从源码结构看,BackgroundType本身不携带业务字段,它充当一个多态基类:实际收到的背景数据会按type字段被解析为以下四种具体子类型之一:

子类型type取值含义
BackgroundTypeFillfill根据所选颜色自动填充的背景
BackgroundTypeWallpaperwallpaperJPEG 格式的壁纸背景
BackgroundTypePatternpatternPNG 或 TGV 图案背景,与用户选择的填充色叠加
BackgroundTypeChatThemechat_theme直接取自内置聊天主题的背景

所有相关类均已在 aiogram/types/init.py 中统一导出(BackgroundType、BackgroundTypeFill、BackgroundTypeWallpaper、BackgroundTypePattern、BackgroundTypeChatTheme、BackgroundTypeUnion),并进入包的__all__列表(见 aiogram/types/init.py),因此开发者可以直接从aiogram.types导入。

四种子类型字段详解

aiogram 中每一个BackgroundType子类型都继承自BackgroundType,字段采用 Pydantic 模型定义,并通过Literal类型将type字段限定为固定字符串常量。

BackgroundTypeFill:纯色自动填充

定义见 aiogram/types/background_type_fill.py:

字段类型必填说明
typeLiteral["fill"]是背景类型,恒为"fill"
fillBackgroundFillUnion是背景填充方式(见下文 BackgroundFill 小节)
dark_theme_dimmingint是深色主题下背景的变暗百分比,取值范围0–100

示例构造:

from aiogram.types import BackgroundTypeFill, BackgroundFillSolid bg = BackgroundTypeFill( fill=BackgroundFillSolid(color=0x1F6FEB), # RGB24 整数颜色 dark_theme_dimming=20, )

BackgroundTypeWallpaper:JPEG 壁纸

定义见 aiogram/types/background_type_wallpaper.py:

字段类型必填说明
typeLiteral["wallpaper"]是背景类型,恒为"wallpaper"
documentDocument是壁纸文件对象(aiogram.types.Document)
dark_theme_dimmingint是深色主题下的变暗百分比,0–100
is_blurredbool \| None否为True时表示壁纸被缩小到 450×450 正方形区域后以半径 12 做高斯模糊
is_movingbool \| None否为True时表示设备倾斜时背景会轻微移动(动态壁纸)

is_blurred与is_moving在官方 API 中均为可选字段,aiogram 中对应的默认值为None。

BackgroundTypePattern:PNG / TGV 图案叠加

定义见 aiogram/types/background_type_pattern.py:

字段类型必填说明
typeLiteral["pattern"]是背景类型,恒为"pattern"
documentDocument是图案文件:.PNG或.TGV(gzip 压缩的 SVG 子集,MIME 类型为application/x-tgwallpattern)
fillBackgroundFillUnion是与图案叠加的背景填充方式
intensityint是图案叠加在填充背景之上的强度百分比,0–100
is_invertedbool \| None否为True时填充色只作用于图案本身,其余像素为黑色;仅用于深色主题
is_movingbool \| None否设备倾斜时背景是否轻微移动

BackgroundTypeChatTheme:内置聊天主题

定义见 aiogram/types/background_type_chat_theme.py,是四种类型中结构最简单的一种:

字段类型必填说明
typeLiteral["chat_theme"]是背景类型,恒为"chat_theme"
theme_namestr是聊天主题名称,通常是一个 emoji

示例:

from aiogram.types import BackgroundTypeChatTheme bg = BackgroundTypeChatTheme(theme_name="🎄")

BackgroundFill:背景填充方式的底层支撑

BackgroundTypeFill与BackgroundTypePattern的fill字段都指向BackgroundFillUnion。BackgroundFill基类(aiogram/types/background_fill.py)同样是多态类型,由三种具体实现组成(见 aiogram/types/background_fill_union.py):

BackgroundFillSolid:纯色填充

定义见 aiogram/types/background_fill_solid.py:

字段类型说明
typeLiteral["solid"]恒为"solid"
colorint填充颜色,RGB24 整数格式(如0xRRGGBB)

BackgroundFillGradient:渐变填充

定义见 aiogram/types/background_fill_gradient.py:

字段类型说明
typeLiteral["gradient"]恒为"gradient"
top_colorint渐变顶部颜色,RGB24 格式
bottom_colorint渐变底部颜色,RGB24 格式
rotation_angleint填充的顺时针旋转角度,0–359 度

BackgroundFillFreeformGradient:自由形态渐变

定义见 aiogram/types/background_fill_freeform_gradient.py:

字段类型说明
typeLiteral["freeform_gradient"]恒为"freeform_gradient"
colorslist[int]用于生成自由渐变的3 或 4 个RGB24 基础色;该类渐变会在聊天中每条消息之后旋转变化

判别联合机制:type 字段如何驱动反序列化

aiogram 使用 Pydantic v2 的Discriminated Union特性实现背景类型的多态解析。核心定义在 aiogram/types/background_type_union.py:

BackgroundTypeUnion: TypeAlias = Annotated[ BackgroundTypeFill | BackgroundTypeWallpaper | BackgroundTypePattern | BackgroundTypeChatTheme, Field(discriminator="type"), ]

Field(discriminator="type")表示 Pydantic 会根据 JSON 载荷中的"type"字段值(fill/wallpaper/pattern/chat_theme)自动选择对应的具体子类完成实例化。同理,aiogram/types/background_fill_union.py 中BackgroundFillUnion也以"type"(solid/gradient/freeform_gradient)作为判别字段。这意味着在业务代码中,你可以直接借助 Pydantic 的多态反序列化能力处理任意背景载荷,无需手动判断分支:

from aiogram.types import ChatBackground # 例如从原始 payload 解析(payload 内必须包含 type 字段) background: ChatBackground = ChatBackground.model_validate(payload)

提示:TelegramObject的model_config启用了extra="allow"、frozen=True等配置(见 aiogram/types/base.py),因此解析时能容忍未来新增的未知字段,同时实例一旦创建即不可变,适合在事件流中安全传递。

在业务中如何接收背景更新:ChatBackground 与服务消息

BackgroundType通常不会单独出现,而是作为ChatBackground对象的type字段存在。ChatBackground定义于 aiogram/types/chat_background.py:

class ChatBackground(TelegramObject): type: BackgroundTypeUnion """Type of the background"""

当某个聊天更换背景时,Telegram 会下发一条服务消息,其字段chat_background_set携带该对象。aiogram 在 aiogram/types/message.py 中将其建模为:

chat_background_set: ChatBackground | None = None """*Optional*. Service message: chat background set"""

同时,aiogram/enums/content_type.py 定义了对应的内容类型枚举ContentType.CHAT_BACKGROUND_SET = "chat_background_set",而Message.content_type属性在检测到chat_background_set字段时会返回该枚举值(见 aiogram/types/message.py)。

因此在 aiogram 的事件处理中,可以直接基于ContentType或字段判空来识别"背景被设置"这一事件:

from aiogram import Router, F from aiogram.enums import ContentType from aiogram.types import Message router = Router() @router.message(F.content_type == ContentType.CHAT_BACKGROUND_SET) async def on_background_set(message: Message) -> None: bg = message.chat_background_set if bg is None: return print("背景类型:", bg.type.type) print("完整背景对象:", bg.type)

在message.chat_background_set非空的前提下,bg.type即为前文所述的BackgroundTypeUnion实例,可直接通过bg.type.type判断具体是fill、wallpaper、pattern还是chat_theme,再按各自字段(如壁纸的document、图案的intensity、主题的theme_name)提取细节,从而实现诸如"统计群内背景更换""监测动态壁纸被启用"等业务逻辑。

小结

BackgroundType是 aiogram 中完整映射 Telegram Bot API 背景体系的多态类型族:

  • 四种背景形态:BackgroundTypeFill(颜色自动填充)、BackgroundTypeWallpaper(JPEG 壁纸)、BackgroundTypePattern(PNG/TGV 图案叠加)、BackgroundTypeChatTheme(内置聊天主题,theme_name通常为 emoji);
  • 两层判别联合:BackgroundTypeUnion与BackgroundFillUnion均以type字段作为 Pydantic discriminator,实现 JSON 到具体子类的自动映射;
  • 数值约束:dark_theme_dimming、intensity取值为 0–100,rotation_angle取值为 0–359,颜色一律使用 RGB24 整数格式;
  • 接入点:通过Message.chat_background_set(ChatBackground)与ContentType.CHAT_BACKGROUND_SET在事件处理器中接收背景变更通知。

如需深入阅读源码,可依次查看 aiogram/types/background_type.py、aiogram/types/background_type_union.py、aiogram/types/chat_background.py 以及 aiogram/types/message.py,对应 API 文档页面则位于 docs/api/types/background_type.rst 及其同目录下的各子类型页面。

  • 后端
  • 即时通讯
  • API设计

【免费下载链接】aiogram

aiogram is a modern and fully asynchronous framework for Telegram Bot API written in Python using asyncio

项目地址:https://gitcode.com/gh_mirrors/ai/aiogram
点击查看免费下载

相关推荐

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询