aiogram 类处理器之 PollHandler:基于类的轮询(Poll)事件处理完整指南
aiogram 类处理器之 PollHandler:基于类的轮询(Poll)事件处理完整指南
在 aiogram 中,除了函数式处理器(async def 回调),你还可以用**类(class)**来组织事件处理逻辑。PollHandler 就是专为 Telegram Poll(轮询/投票) 事件而生的类基处理器(class-based handler):它把 Poll 事件对象、上下文数据以及常用字段别名封装在一个可继承的类里,让你通过继承与复用获得更整洁、可扩展的处理器结构。本文将从 PollHandler 的导入与基本用法出发,剖析其继承体系、question/options 两个便捷属性的底层实现,并结合仓库源码与测试用例,为你展示如何在 aiogram 项目中落地类式投票处理。
一、什么是 PollHandler:从事件到类的桥接
在 aiogram 的分发(Dispatcher)架构中,每一个 Telegram 更新类型都对应一个事件观察器(TelegramEventObserver)。在 aiogram/dispatcher/router.py 中可以看到,Router 初始化了两个与投票相关的观察器:
self.poll = TelegramEventObserver(router=self, event_name="poll")
self.poll_answer = TelegramEventObserver(router=self, event_name="poll_answer")
并在 self.observers 字典中登记了 "poll": self.poll 与 "poll_answer": self.poll_answer。也就是说,当你使用 @router.poll() 装饰器注册处理器时,实际注册到的是 Router.poll 这个 TelegramEventObserver 实例。
PollHandler 就是专门用来承接 poll 事件(用户收到或更新一条投票消息)的类基处理器。它定义于 aiogram/handlers/poll.py,声明为:
class PollHandler(BaseHandler[Poll], ABC):
"""
Base class for poll handlers
"""
注意两点:
- 泛型参数是
Poll:事件类型被固定为 aiogram/types/poll.py 中定义的Poll对象(TelegramObject的子类,对应 Bot API 的Poll对象)。 - 继承
ABC:PollHandler是抽象基类,不能直接实例化,你必须创建自己的子类并实现handle()方法。
与 PollHandler 相关联的还有 PollAnswer 事件(用户投票后的回执),它由 router.poll_answer 观察器分发,但本文聚焦于 PollHandler 本身。
二、简单用法:最小可运行示例
原文档给出了 PollHandler 的最小用法,直接继承即可:
from aiogram.handlers import PollHandler
...
@router.poll()
class MyHandler(PollHandler):
async def handle(self) -> Any: ...
这里的关键点:
@router.poll()装饰器接收的是类而非函数。aiogram 会把这个类当作处理器回调使用——由于BaseHandler实现了__await__(见 aiogram/handlers/base.py),实例可以直接被await,因此类处理器与函数处理器在分发链中的行为是一致的。- 必须实现
async def handle(self) -> Any。这是BaseHandler中声明的抽象方法(aiogram/handlers/base.py),也是你编写业务逻辑的唯一入口。 self.event就是当前分发的Poll事件对象,你可以直接访问self.event.id、self.event.question、self.event.options、self.event.total_voter_count、self.event.is_closed、self.event.type等字段(完整字段见 aiogram/types/poll.py)。
一个更完整的实际示例:
from typing import Any
from aiogram import Router
from aiogram.handlers import PollHandler
router = Router()
@router.poll()
class PollWatcher(PollHandler):
async def handle(self) -> Any:
# self.event 是 aiogram.types.Poll 实例
print(f"收到投票:{self.question}")
for option in self.options:
print(f" - {option.text}: {option.voter_count} 票")
if self.event.is_closed:
print("该投票已关闭")
三、继承体系:BaseHandler 提供的通用能力
PollHandler 是 BaseHandler 的子类,后者是整个类处理器体系的根基,定义在 aiogram/handlers/base.py。理解 BaseHandler 有助于你写出更地道的类处理器:
3.1 默认初始化器与属性
BaseHandler 的初始化器是现成的,不需要重写:
def __init__(self, event: T, **kwargs: Any) -> None:
self.event: T = event
self.data: dict[str, Any] = kwargs
它接收事件对象和上下文数据,分别暴露为:
self.event:本次分发的事件(对PollHandler而言就是Poll);self.data:上下文字典(包含bot、update、event_update等键),由分发流程注入。
3.2 便捷属性:bot 与 update
BaseHandler 还提供了两个非常实用的属性:
self.bot:从self.data<a href="https://link.gitcode.com/i/5af90bc87dd95a4a6d546ae61ac09d64" target="_blank">"bot"]中取回Bot实例;若上下文不存在 bot 会抛出RuntimeError([aiogram/handlers/base.py)。这意味着在handle()里可以直接用self.bot.send_message(...)回复用户,无需把 bot 作为参数传入。self.update:返回当前Update对象(aiogram/handlers/base.py)。
3.3 可 await 的处理器
def __await__(self) -> Any:
return self.handle().__await__()
正是这个 __await__ 让 MyHandler(event) 这样的实例可以直接被 await,从而无缝接入 aiogram 的分发机制。这也解释了为什么装饰器可以接受类:分发时 aiogram 构造实例并 await 它,实际执行的就是你的 handle()。
四、PollHandler 的两个扩展属性
PollHandler 在原文档中明确提供了两个别名属性,全部实现在 aiogram/handlers/poll.py:
@property
def question(self) -> str:
return self.event.question
@property
def options(self) -> list[PollOption]:
return self.event.options
self.question:等价于self.event.question,即投票问题的文本(Bot API 限制为 1–300 字符)。self.options:等价于self.event.options,是list<a href="https://link.gitcode.com/i/151b17a71ce2970942cbae4a26c8c71f" target="_blank">PollOption]列表。PollOption定义于 [aiogram/types/poll_option.py,核心字段包括persistent_id(选项持久化 ID)、text(选项文本,1–100 字符)、voter_count(投票人数,可能为 0 表示未知),以及可选的text_entities、media、added_by_user、added_by_chat、addition_date(后四者用于支持动态增删选项的场景)。
这种“属性即别名”的设计与同类处理器一致:例如 CallbackQueryHandler 也把 from_user、message、callback_data 暴露为属性(见 aiogram/handlers/callback_query.py),MessageHandler 同样提供 from_user、chat(见 aiogram/handlers/message.py)。好处是:子类中的业务代码更短、可读性更高,同时保留了完整的类型提示(question 返回 str,options 返回 list[PollOption],IDE 可直接推断)。
五、测试验证:别名行为的正确性
仓库中 tests/test_handler/test_poll.py 专门验证了这两个别名的行为:
class MyHandler(PollHandler):
async def handle(self) -> Any:
assert self.event == event
assert self.question == self.event.question
assert self.options == self.event.options
return True
assert await MyHandler(event)
测试构造了一个完整的 Poll 实例(包含 id、question、options、is_closed、is_anonymous、type、allows_multiple_answers、allows_revoting、members_only、total_voter_count 等字段),并断言:
self.event与传入的事件一致;self.question == self.event.question;self.options == self.event.options;- 实例可以被
await(即handle()被执行)。
这说明文档承诺的别名行为有测试兜底,你可以放心直接使用 self.question 与 self.options。
六、进阶:在 handle 中做实际业务
结合前面所有机制,一个完整的类式投票处理器可以是:
from typing import Any
from aiogram import Bot, Router
from aiogram.handlers import PollHandler
router = Router()
@router.poll()
class QuizResultHandler(PollHandler):
async def handle(self) -> Any:
# 仅处理 quiz 类型投票
if self.event.type != "quiz":
return
correct = self.event.correct_option_ids or []
# self.bot 由 BaseHandler 从上下文提供
await self.bot.send_message(
chat_id=self.data.get("event_chat_id"), # 上下文数据视分发配置而定
text=(
f"问题:{self.question}\n"
f"正确选项 ID:{correct}\n"
f"参与人数:{self.event.total_voter_count}"
),
)
提示:类处理器与函数处理器一样,也可以配合过滤器使用,例如
@router.poll(F.text.contains("问答")),把过滤逻辑与业务逻辑分离。
七、小结:何时使用 PollHandler
- 当你的投票业务逻辑较复杂、需要跨多个回调共享状态或复用代码时,用
PollHandler继承 + mixin 组合是更优解; - 当业务很简单、只有一个函数时,函数式处理器(
@router.poll()直接接async def)依然完全可用; PollHandler本身只解决poll事件的类式分发;如果需要处理用户投票回执(PollAnswer),请使用router.poll_answer观察器(aiogram/dispatcher/router.py)。
核心参考文件: