资讯动态

aiogram 入门实战:用完全异步的 Python 框架快速构建 Telegram Bot

发布时间:2026/10/14 18:00:23 来源:尧图企业网站定制
后端即时通讯API设计【免费下载链接】aiogramaiogram is a modern and fully asynchronous framework for Telegram Bot API written in Python using asyncio项目地址https://gitcode.com/gh_mirrors/ai/aiogram点击查看免费下载aiogram是一个基于 Python 3.10 与asyncio、aiohttp构建的现代全异步 Telegram Bot API 框架。本文以官方文档首页docs/index.rst为核心骨架完整解析其中收录的“简单用法”与“不使用 Dispatcher 的用法”两个官方示例并深入仓库源码揭示事件分发、Bot 会话与默认属性的底层原理。读完本文你将掌握从零搭建一个可用 Telegram Bot、并理解其内部运行机制的全部技能。框架概览aiogram 是什么以下内容摘自官方文档首页即 README.rst由 docs/index.rst 通过.. include::指令直接引入aiogramis a modern and fully asynchronous framework for Telegram Bot API written in Python 3.10 usingasyncioandaiohttp。官方文档首页开宗明义aiogram 是专为 Telegram Bot API 设计的全异步框架底层基于 Python 标准库asyncio与高性能 HTTP 客户端aiohttp。这意味着所有网络请求与事件处理都在同一个事件循环内协作调度天然适合高并发消息场景。核心特性异步原生基于asyncioPEP 492 语法全程async/await编写类型提示完备提供完整类型标注PEP 484可直接与mypy等静态检查工具配合支持 PyPy不仅限于 CPython 运行时紧跟 Bot API 更新当前支持 Telegram Bot API 10.3并随官方 API 迭代快速同步自动生成集成代码Bot API 集成代码由tg-codegen自动生成API 更新时可轻松重新生成更新路由Blueprints基于 Router/Dispatcher 的事件路由体系内置有限状态机FSM支持复杂对话流程编排强大的 magic filters声明式过滤器简化事件筛选中间件机制同时支持入站更新与 API 调用两层中间件Webhook 内回复支持 Telegram 官方推荐的 Webhook 响应式回复Replies into Webhook集成 I18n/L10n基于 GNU Gettext或 Fluent的多语言支持。注意官方文档明确提示使用 aiogram 前最好具备asyncio的基础经验。快速起步安装在运行示例代码前需要先安装框架。根据官方安装文档 docs/install.rst# 从 PyPI 安装推荐始终为最新稳定版 pip install -U aiogramArch Linux 用户也可以从系统仓库安装但官方文档特别警告该仓库包可能过时建议优先使用 PyPI 版本# Arch Linux 系统仓库可能不是最新版 pacman -S python-aiogram需要体验最新开发版特性时可直接从 GitHub 的dev-3.x分支安装pip install https://github.com/aiogram/aiogram/archive/refs/heads/dev-3.x.zip简单用法官方 echo_bot 完整剖析docs/index.rst通过.. literalinclude:: ../examples/echo_bot.py将 examples/echo_bot.py 全文引入文档这是 aiogram 官方推荐的入门第一课——一个“回声机器人”把收到的消息原样返回。下面逐段深入讲解。导入与 Token 获取import asyncio import logging import sys from os import getenv from aiogram import Bot, Dispatcher, html from aiogram.client.default import DefaultBotProperties from aiogram.enums import ParseMode from aiogram.filters import CommandStart from aiogram.types import Message # Bot token can be obtained via https://t.me/BotFather TOKEN getenv(BOT_TOKEN)关键点Bot封装了与 Telegram Bot API 交互的客户端aiogram/client/bot.py 中的Bot类Dispatcher事件分发器负责接收并路由 updatesaiogram/dispatcher/dispatcher.pyhtmlHTML 文本装饰工具从 aiogram/utils/text_decorations.py 导出的html_decoration实例在 aiogram/init.py 中注册为顶层导出htmlCommandStart预置的/start命令过滤器aiogram/filters/command.pyToken 通过环境变量BOT_TOKEN传入可用 BotFather 创建机器人获取。注册路由Dispatcher 与装饰器dp Dispatcher() dp.message(CommandStart()) async def command_start_handler(message: Message) - None: This handler receives messages with /start command await message.answer(fHello, {html.bold(message.from_user.full_name)}!)这段代码展示了 aiogram 的核心编程范式——装饰器式事件注册创建Dispatcher实例用dp.message(CommandStart())注册处理函数只有当消息触发CommandStart过滤器即用户发送/start命令时才会调用该 handler。从源码看CommandStart是Command的子类构造时固定绑定命令名start、前缀/还额外支持deep_link深链参数、ignore_case、ignore_mention等选项aiogram/filters/command.py处理函数签名接收Message对象返回None。message.answer(...)是Message对象提供的方法快捷别名。从 aiogram/types/message.py 的源码注释可以看到它是aiogram.methods.send_message.SendMessage的 shortcut调用时会自动填充chat_id、message_thread_id、business_connection_id等字段因此无需再手动指定聊天 ID——这正是“在事件上下文中回复”的便利之处。html.bold(...)会将文本包裹为b.../b标签。从 aiogram/utils/text_decorations.py 的实现看bold通过_tag(self.BOLD_TAG, value)生成 HTML 标签该文件还提供italic、code、pre、underline、strikethrough、spoiler、quote、link等系列装饰方法。需要说明的是HTML 标签只有配合ParseMode.HTML才生效这正是下文DefaultBotProperties(parse_modeParseMode.HTML)的用途。通用消息处理器echo 逻辑dp.message() async def echo_handler(message: Message) - None: Handler will forward receive a message back to the sender By default, message handler will handle all message types (like a text, photo, sticker etc.) try: # Send a copy of the received message await message.send_copy(chat_idmessage.chat.id) except TypeError: # But not all the types is supported to be copied so need to handle it await message.answer(Nice try!)dp.message()不带任何过滤器表示匹配所有消息类型文本、图片、贴纸等。处理逻辑优先调用message.send_copy(chat_idmessage.chat.id)将收到的消息“原样拷贝”发回。注意 aiogram/types/message.py 源码明确指出send_copy并不调用Bot API 中名为copyMessage的方法而是 aiogram 在 API 提供该能力之前就实现的历史方法它按消息类型分发到对应的SendAnimation、SendAudio、SendPhoto、SendVideo、SendMessage等 17 种发送方法之一并返回发送出的消息对象由于并非所有消息类型都支持拷贝如部分特殊内容捕获TypeError后回一句Nice try!兜底。主函数启动轮询async def main() - None: # Initialize Bot instance with default bot properties which will be passed to all API calls bot Bot(tokenTOKEN, defaultDefaultBotProperties(parse_modeParseMode.HTML)) # And the run events dispatching await dp.start_polling(bot) if __name__ __main__: logging.basicConfig(levellogging.INFO, streamsys.stdout) asyncio.run(main())这段启动代码包含两个重要概念1Bot与默认属性Bot(token..., defaultDefaultBotProperties(parse_modeParseMode.HTML))。从 aiogram/client/bot.py 的构造逻辑可以看到token会先经过validate_token(token)校验格式非法时抛出TokenValidationErrorsession未显式传入时自动创建AiohttpSession()default未传入时自动取DefaultBotProperties()空实例若在kwargs中传入旧的parse_mode、disable_web_page_preview、protect_content参数会直接抛出TypeError并提示改用defaultDefaultBotProperties(...)——这是 3.7.0 版本引入的破坏性变更。DefaultBotPropertiesaiogram/client/default.py是一个 dataclass承载会被传播到所有 API 调用的默认属性包括字段说明parse_mode消息默认解析模式ParseMode.HTML/ParseMode.MARKDOWN_V2等disable_notification静默发送消息用户收到通知但不发声protect_content禁止内容被转发/复制allow_sending_without_reply允许无回复目标时仍发送link_preview/link_preview_is_disabled/link_preview_prefer_small_media/link_preview_prefer_large_media/link_preview_show_above_text链接预览相关配置__post_init__会自动将这些散列字段合并为LinkPreviewOptions对象show_caption_above_media媒体消息的说明文字是否显示在媒体上方ParseMode枚举定义于 aiogram/enums/parse_mode.py。2start_polling轮询启动器await dp.start_polling(bot)是长轮询入口。从 aiogram/dispatcher/dispatcher.py 的签名可见其丰富可调参数polling_timeout: int 10长轮询单次等待超时秒handle_as_tasks: bool True每个事件独立创建asyncio.Task并发处理backoff_config指数退避重试配置默认DEFAULT_BACKOFF_CONFIGallowed_updates接收哪些更新类型默认UNSET时由resolve_used_update_types()根据已注册 handlers 自动解析aiogram/dispatcher/dispatcher.pyhandle_signals: bool True自动注册SIGINT/SIGTERM信号处理器Windows 平台不支持信号处理源码中add_signal_handler的NotImplementedError被显式抑制见 aiogram/dispatcher/dispatcher.pyclose_bot_session: bool True停机时关闭 bot 会话tasks_concurrency_limit并发处理 updates 的上限仅handle_as_tasksTrue时生效None表示不限制。start_polling内部还会用self._running_lock防止重复启动、启动前触发emit_startup即 router 的 startup 事件钩子、随后为每一个传入的 bot 创建一个_polling任务。因此该 API 天然支持多机器人同时轮询start_polling(bot1, bot2, ...)。另外注意一个使用细节源码规定 bot 实例必须以位置参数传入aiogram/dispatcher/dispatcher.py若以dp.start_polling(botbot)形式传bot关键字会抛出ValueError。运行方式BOT_TOKEN你的机器人Token python examples/echo_bot.py程序会打印INFO级别日志启动后向你的机器人发送任意消息即可看到回声效果发送/start会收到Hello, b姓名/bHTML 加粗渲染发送其他消息则被原样拷贝返回。不使用 Dispatcher 的用法纯 API 调用docs/index.rst引入的第二个示例是 examples/without_dispatcher.py官方注释点明其用途只与 Bot API 交互而不处理任何事件。当你的程序只需要“发消息”而不需要接收/响应更新时这种轻量模式最合适。完整示例代码import asyncio from argparse import ArgumentParser from aiogram import Bot from aiogram.client.default import DefaultBotProperties from aiogram.enums import ParseMode def create_parser() - ArgumentParser: parser ArgumentParser() parser.add_argument(--token, helpTelegram Bot API Token) parser.add_argument(--chat-id, typeint, helpTarget chat id) parser.add_argument(--message, -m, helpMessage text to sent, defaultHello, World!) return parser async def main() - None: parser create_parser() ns parser.parse_args() token ns.token chat_id ns.chat_id message ns.message async with Bot( tokentoken, defaultDefaultBotProperties( parse_modeParseMode.HTML, ), ) as bot: await bot.send_message(chat_idchat_id, textmessage) if __name__ __main__: asyncio.run(main())核心要点1无需 Dispatcher仅用 Bot这个示例只导入Bot完全绕开了Dispatcher的事件路由体系。因为没有事件需要分发也就不存在 handler、过滤器与轮询任务。2async with上下文管理器管理会话生命周期async with Bot(tokentoken, defaultDefaultBotProperties(parse_modeParseMode.HTML)) as bot: await bot.send_message(chat_idchat_id, textmessage)Bot实现了异步上下文管理器协议aiogram/client/bot.py进入async with时返回自身退出时调用await self.session.close()关闭底层AiohttpSession。这意味着 HTTP 会话会被自动、干净地释放避免资源泄漏。3直接调用 API 方法await bot.send_message(chat_idchat_id, textmessage)直接调用Bot实例上的send_message方法定义于 aiogram/client/bot.py。这里必须手动传入chat_id因为没有事件上下文可以自动填充。这正是与上文message.answer()别名的主要区别别名方法自动填参直接方法需显式传参。运行方式python examples/without_dispatcher.py \ --token 你的机器人Token \ --chat-id 你的用户ID \ --message Hello, aiogram! # 不带 --message 时使用默认文本 Hello, World!该示例适合的典型场景定时任务推送、CI 构建通知、监控告警等“只发不收”的自动化脚本。注意它使用的是单次调用即退出的模式与长驻轮询的 echo_bot 形成鲜明对比。两种模式对比与选型建议维度echo_botDispatcher 模式without_dispatcher纯 Bot 模式导入对象BotDispatcher 过滤器/类型仅Bot事件处理通过dp.message()等装饰器注册 handler不处理事件启动方式dp.start_polling(bot)长轮询常驻async with Bot(...)单次执行即退出传参方式message.answer()自动填充chat_idbot.send_message()手动传chat_id典型场景交互式聊天机器人定时/告警推送脚本会话管理由start_polling的close_bot_session参数控制async with自动关闭选型建议需要接收并响应用户消息时使用 Dispatcher 模式只需主动发送消息时使用纯 Bot 模式代码更精简且不引入额外开销。更进一步文档导航与生态官方文档首页末尾通过toctree组织了完整的文档体系docs/index.rst可作为后续深入学习的路线图安装指南PyPI / Arch / 开发版安装2.x 到 3.x 迁移指南老版本用户升级必读API 参考全部 types / methods / enums 的完整文档Dispatcher 指南Router、FSM、中间件、过滤器等事件分发核心机制工具模块格式化、deep linking 等辅助工具更新日志 与 贡献指南。仓库中还包含大量可直接运行的示例如 examples/finite_state_machine.pyFSM 状态机、examples/echo_bot_webhook.pyWebhook 模式、examples/error_handling.py错误处理等均可在 examples 目录下找到。小结本文以官方文档首页收录的两个官方示例为骨架完整还原了 aiogram 的两种典型用法Dispatcher 驱动的轮询事件处理与纯 Bot 的轻量 API 调用并从 aiogram/client/bot.py、aiogram/dispatcher/dispatcher.py、aiogram/client/default.py、aiogram/types/message.py 等源码层面揭示了start_polling参数、DefaultBotProperties默认属性传播、answer/send_copy快捷别名、async with会话管理等底层机制。掌握这两条路径后你就已经具备构建生产级 Telegram Bot 的坚实基础。赞分享后端即时通讯API设计【免费下载链接】aiogramaiogram is a modern and fully asynchronous framework for Telegram Bot API written in Python using asyncio项目地址https://gitcode.com/gh_mirrors/ai/aiogram点击查看免费下载相关推荐aiogram 3.x构建 Telegram Bot 的全异步 Python 框架——核心特性、架构解析与快速上手aiogram 3.x构建 Telegram Bot 的全异步 Python 框架——核心特性、架构解析与快速上手 aiogram 是一个完全基于 async后端即时通讯API设计aiogram stopPoll 方法实战用 Python 异步框架优雅结束 Telegram 投票aiogram stopPoll 方法实战用 Python 异步框架优雅结束 Telegram 投票 导读 stopPoll 是 Telegram Bot A后端即时通讯API设计Sanic框架快速入门指南构建高性能Python异步Web应用Sanic框架快速入门指南构建高性能Python异步Web应用 前言 Sanic是一个基于Python的异步Web框架专为快速HTTP响应而设计。它采用现代后端Web框架创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价 →
↑