☰
aiogram GiveawayCreated 类型详解:捕获 Telegram 定时抽奖创建服务消息
2026/10/13 12:14:02 网站建设 项目流程
  • 后端
  • 即时通讯
  • 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 框架中的GiveawayCreated类型展开,讲解其在 Telegram Bot API 中代表的消息语义(定时抽奖创建的服务消息)、唯一字段prize_star_count的含义与取值约束,并给出在 aiogram 的 Message、Dispatcher 与过滤器体系中识别与处理该事件的最佳实践,帮助读者在基于 asyncio 的全异步机器人中完整实现抽奖活动从创建到开奖的监控链路。

一、GiveawayCreated 是什么

GiveawayCreated是 aiogram 中对应 Telegram Bot APIGiveawayCreated对象的类型,官方语义为"This object represents a service message about the creation of a scheduled giveaway",即"关于已排定的抽奖活动创建的服务消息"。

从源码结构看,它定义于 aiogram/types/giveaway_created.py:

class GiveawayCreated(TelegramObject): """ This object represents a service message about the creation of a scheduled giveaway. Source: https://core.telegram.org/bots/api#giveawaycreated """ prize_star_count: int | None = None """*Optional*. The number of Telegram Stars to be split between giveaway winners; for Telegram Star giveaways only""" if TYPE_CHECKING: # DO NOT EDIT MANUALLY!!! # This section was auto-generated via `butcher` # Is needed only for type checking and IDE support without any additional plugins def __init__( __pydantic__self__, *, prize_star_count: int | None = None, **__pydantic_kwargs: Any ) -> None: # DO NOT EDIT MANUALLY!!! # This method was auto-generated via `butcher` # Is needed only for type checking and IDE support without any additional plugins super().__init__(prize_star_count=prize_star_count, **__pydantic_kwargs)

几点关键结论:

  • 它继承自 aiogram/types/base.py 中的TelegramObject,即 PydanticBaseModel的子类,因此具备model_config中配置的行为:frozen=True(实例不可变)、extra="allow"(容忍额外字段)、populate_by_name=True、validate_assignment=True等。当 Telegram 服务端未来在对象中追加新字段时,extra="allow"可以保证兼容性,不会因未知字段抛错。
  • prize_star_count是int | None,默认None。它仅在Telegram Star 抽奖(以 Telegram Stars 作为奖品的抽奖)中出现,表示将在中奖者之间分配的通告(Stars)总数。普通实物/礼物类抽奖中该字段为None。
  • TYPE_CHECKING分支中的__init__由butcher自动生成,仅服务于类型检查与 IDE 提示,运行时 Pydantic 会以默认方式完成实例化与校验。

二、prize_star_count 字段详解

字段类型默认值说明
prize_star_countint \| NoneNone仅在 Telegram Star 抽奖中出现;表示分配给抽奖获胜者的 Telegram Stars 总数量

使用注意:

  1. 条件性字段:只有奖品为 Telegram Stars 的抽奖(Star giveaway)才会携带该字段;普通抽奖(实物奖品、Telegram Premium 订阅等)不携带,此时值为None。
  2. 与 ChatBoostSourceGiveaway 联动:在 aiogram/types/chat_boost_source_giveaway.py 中同样存在prize_star_count,注释指出 Telegram Star 抽奖带来的加成(boost)次数约为prize_star_count / 500次、持续一年。这说明抽奖创建事件与频道加成机制直接关联——若你的机器人需要统计群组加成来源,可以据此关联处理。
  3. 历史版本:根据 CHANGES.rst,prize_star_count字段是在 3.13.0(2024-09-08)版本中随 Telegram Bot API 的更新一并加入到GiveawayCreated、Giveaway、GiveawayWinners与ChatBoostSourceGiveaway的。如果你的部署环境使用更早的 aiogram 版本,需要先升级才能读取该字段。

三、GiveawayCreated 在 Message 中的位置

GiveawayCreated不是独立事件,而是作为Message对象上的一个可选字段存在。在 aiogram/types/message.py 中:

giveaway_created: GiveawayCreated | None = None """*Optional*. Service message: a scheduled giveaway was created"""

也就是说,当频道/群组管理员在 Telegram 客户端中创建一个定时抽奖时,机器人收到的Message的giveaway_created字段即被填充,同时该消息没有普通文本内容(text为None),from_user通常也为空(服务消息)。

content_type 识别

aiogram 为每种消息内容定义了枚举,见 aiogram/enums/content_type.py:

GIVEAWAY_CREATED = "giveaway_created" GIVEAWAY = "giveaway" GIVEAWAY_WINNERS = "giveaway_winners" GIVEAWAY_COMPLETED = "giveaway_completed"

Message.content_type属性(aiogram/types/message.py)按顺序检查各字段并返回对应枚举值:

if self.giveaway_created: return ContentType.GIVEAWAY_CREATED if self.giveaway: return ContentType.GIVEAWAY if self.giveaway_completed: return ContentType.GIVEAWAY_COMPLETED if self.giveaway_winners: return ContentType.GIVEAWAY_WINNERS

因此,判断"这条消息是不是抽奖创建通知"既可以直接检查message.giveaway_created is not None,也可以用message.content_type == ContentType.GIVEAWAY_CREATED。测试用例 tests/test_api/test_types/test_message.py 与 tests/test_api/test_types/test_message.py 构造了带GiveawayCreated(prize_star_count=42)的 Message 并断言其content_type为ContentType.GIVEAWAY_CREATED,验证了上述行为。

四、在 Dispatcher 中注册处理函数

aiogram 3.x 的典型用法是使用Router.message()装饰器配合内容类型过滤。Message字段名与ContentType枚举值一致(giveaway_created),可以直接作为过滤参数:

from aiogram import Router, types from aiogram.enums import ContentType router = Router() @router.message(ContentType.GIVEAWAY_CREATED) async def on_giveaway_created(message: types.Message) -> None: giveaway_created = message.giveaway_created # 此时 giveaway_created 一定非 None if giveaway_created.prize_star_count is not None: print(f"Star 抽奖已创建,奖品总量 {giveaway_created.prize_star_count} Stars") else: print("普通抽奖已创建(无 Star 奖品)")

也可以不依赖ContentType,直接对Message的字段做过滤:

@router.message(lambda message: message.giveaway_created is not None) async def on_giveaway_created_v2(message: types.Message) -> None: ...

两种方式均可工作:前者由框架在分发时根据message.content_type与过滤值匹配,后者则是自定义过滤器。参考 aiogram/filters/command.py 中Command过滤器的实现风格,aiogram 的过滤器体系会按注册顺序依次调用并支持组合(and_f、or_f、invert_f,见 aiogram/filters/init.py)。

五、抽奖事件全链路:GiveawayCreated 与相关类型

仅处理"创建"事件往往不够。一个完整的抽奖监控机器人通常会同时关注以下四个阶段:

阶段aiogram 类型Message 字段说明
抽奖被创建(定时)GiveawayCreatedmessage.giveaway_created服务消息,标记定时抽奖已排定
抽奖消息本身Giveawaymessage.giveaway展示奖品、参与条件等具体信息的消息,见 aiogram/types/giveaway.py
开奖(公开中奖者)GiveawayWinnersmessage.giveaway_winners公布中奖用户列表
开奖(未公开中奖者)GiveawayCompletedmessage.giveaway_completed无公开名单的完成通知

Giveaway类型还包含chats(需加入才能参与的聊天列表)、winners_selection_date(开奖时间戳)、winner_count(中奖人数)、only_new_members、has_public_winners、prize_description、country_codes、prize_star_count、premium_subscription_month_count等字段,是理解抽奖规则细节的关键对象,可与GiveawayCreated配合使用。

一个覆盖四类事件的示例:

from aiogram import Router, types from aiogram.enums import ContentType router = Router() @router.message(ContentType.GIVEAWAY_CREATED) async def giveaway_created(message: types.Message) -> None: print("抽奖已排定:", message.giveaway_created) @router.message(ContentType.GIVEAWAY) async def giveaway_announced(message: types.Message) -> None: giveaway = message.giveaway print(f"开奖时间: {giveaway.winners_selection_date}, 中奖人数: {giveaway.winner_count}") @router.message(ContentType.GIVEAWAY_WINNERS) async def giveaway_winners(message: types.Message) -> None: print("抽奖已开奖:", message.giveaway_winners) @router.message(ContentType.GIVEAWAY_COMPLETED) async def giveaway_completed(message: types.Message) -> None: print("抽奖已完成:", message.giveaway_completed)

注意:copy_message/copy_messages方法明确禁止复制服务消息与抽奖类消息(见 aiogram/methods/copy_message.py 与 aiogram/methods/copy_messages.py 的文档说明:"Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied")。因此不要尝试转发或复制这类事件消息,收到后直接读取字段做业务处理即可。

六、实战:Star 抽奖创建后的自动化通知

结合以上内容,一个典型的实战场景是:当频道创建了以 Stars 为奖品的抽奖时,机器人立即向运营群发送摘要。完整代码示例:

import asyncio from aiogram import Bot, Dispatcher, Router, types from aiogram.enums import ContentType from aiogram.filters import CommandStart BOT_TOKEN = "YOUR_BOT_TOKEN" ADMIN_CHAT_ID = -1001234567890 router = Router() @router.message(ContentType.GIVEAWAY_CREATED) async def notify_star_giveaway(message: types.Message, bot: Bot) -> None: giveaway_created = message.giveaway_created if giveaway_created is None or giveaway_created.prize_star_count is None: return # 非 Star 抽奖,忽略或另行处理 chat_title = message.chat.title or str(message.chat.id) text = ( f"🎁 频道 {chat_title} 创建了 Star 抽奖!\n" f"奖品总额: {giveaway_created.prize_star_count} ⭐" ) await bot.send_message(ADMIN_CHAT_ID, text) @router.message(CommandStart()) async def start(message: types.Message) -> None: await message.answer("抽奖监控机器人已启动") async def main() -> None: bot = Bot(BOT_TOKEN) dp = Dispatcher() dp.include_router(router) await dp.start_polling(bot) if __name__ == "__main__": asyncio.run(main())

代码要点:

  • 通过ContentType.GIVEAWAY_CREATED过滤,避免对普通消息做无谓解析;
  • 用prize_star_count is not None区分 Star 抽奖与普通抽奖;
  • message.chat为Chat对象,可直接读取title等信息(见 aiogram/types/chat.py);
  • 整体保持异步风格,与 aiogram "fully asynchronous framework ... using asyncio" 的设计一致。

七、小结

  • GiveawayCreated表示"定时抽奖已被创建"的服务消息,位于Message.giveaway_created字段;
  • 唯一字段prize_star_count仅存在于 Telegram Star 抽奖中,值为int,否则为None;
  • 可用message.content_type == ContentType.GIVEAWAY_CREATED或message.giveaway_created is not None识别该事件;
  • 抽奖监控应同时关注Giveaway、GiveawayWinners、GiveawayCompleted三类相关消息,形成完整的事件链路;
  • 服务消息与抽奖消息不可复制/转发(copy_message、copy_messages的限制),处理时直接读取字段即可。

更深入的内容可继续阅读仓库中的以下文件:

  • GiveawayCreated 源码
  • Message 类型定义与 content_type 实现
  • ContentType 枚举
  • Giveaway 类型(抽奖详情)
  • 对应测试用例
  • 后端
  • 即时通讯
  • 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
点击查看免费下载
上一篇:告别单调对话:Chatpad AI如何重新定义ChatGPT用户体验
下一篇:如何使用html5lib-python:Python中最强大的HTML解析库完整指南

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

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

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

立即咨询