首页 / 资讯中心 / 文章详情

aiogram 发送地点卡片完全指南:InputMediaVenue 类型详解与实战

aiogram 发送地点卡片完全指南:InputMediaVenue 类型详解与实战 ★ FEATURED ARTICLE
后端即时通讯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 中表示待发送地点venue的InputMediaVenue类型展开讲解其字段定义、在轮询媒体poll media场景中的正确用法、底层SendVenue方法的调用链以及从源码与测试用例中总结出的实战要点。读完本文你将掌握在 aiogram 3.x 中构造 venue 媒体对象、配合send_poll发送带地点插图的问卷以及独立发送地点卡片的完整方案。一、InputMediaVenue 是什么InputMediaVenue是 aiogram 中对应 Telegram Bot API 对象InputMediaVenue的类型实现源码位于 aiogram/types/input_media_venue.py。在官方 API 中InputMediaVenue表示一个待发送的地点venue即它描述的是发送动作的输入数据而不是服务端返回的已发送地点对象——后者对应的是Venue类型见 aiogram/types/venue.py。该类型的类定义与注释如下class InputMediaVenue(InputPollMedia, InputPollOptionMedia): Represents a venue to be sent. Source: https://core.telegram.org/bots/api#inputmediavenue type: Literal[InputMediaType.VENUE] InputMediaType.VENUE Type of the media, must be *venue* latitude: float Latitude of the location longitude: float Longitude of the location title: str Name of the venue address: str Address of the venue foursquare_id: str | None None *Optional*. Foursquare identifier of the venue foursquare_type: str | None None *Optional*. Foursquare type of the venue, if known. (For example, arts_entertainment/default, arts_entertainment/aquarium or food/icecream.) google_place_id: str | None None *Optional*. Google Places identifier of the venue google_place_type: str | None None *Optional*. Google Places type of the venue.从中可以提炼出几个关键事实type字段被固定为venuetype使用Literal[InputMediaType.VENUE]限定并带有默认值。也就是说实例化InputMediaVenue时无需也无法传其他类型值。InputMediaType.VENUE定义在 aiogram/enums/input_media_type.py其枚举值为字符串venue。必填字段为latitude、longitude、title、address这四个字段没有默认值缺少任何一个都会在 Pydantic 校验阶段报错。可选字段为四个第三方地点服务标识符foursquare_id、foursquare_type、google_place_id、google_place_type默认均为None。类本身继承自InputPollMedia与InputPollOptionMedia详见下文它属于哪一类媒体一节因此在类型体系上属于轮询媒体而非常规的InputMedia家族。二、它属于哪一类媒体继承关系与联合类型2.1 继承的两个基类InputMediaVenue同时继承了两个标记性基类InputPollMediaaiogram/types/input_poll_media.py表示问卷描述或测验说明中要附带的媒体内容其允许的子类型清单中包含InputMediaVenue。InputPollOptionMediaaiogram/types/input_poll_option_media.py表示轮询选项poll option中要附带的媒体内容允许的子类型同样包含InputMediaVenue。这两个基类本身只是继承自TelegramObject的空壳标记类作用是把 venue 等媒体类型归入轮询媒体体系。2.2 注意InputMediaVenue 不属于常规 InputMediaUnionaiogram 中有多个联合类型用于在类型注解层约束某个字段可以接收哪几种媒体。InputMediaVenue出现在以下两个联合中InputPollMediaUnionaiogram/types/input_poll_media_union.py包含 Animation、Audio、Document、LivePhoto、Location、Photo、Venue、Video 共 8 种InputPollOptionMediaUnionaiogram/types/input_poll_option_media_union.py包含 Animation、Link、LivePhoto、Location、Photo、Sticker、Venue、Video 共 8 种。而常规的InputMediaUnionaiogram/types/input_media_union.py只包含 Animation、Audio、Document、LivePhoto、Photo、Video 六种并不包含InputMediaVenue。同时InputMedia基类aiogram/types/input_media.py的允许清单也仅列出这六种。结论InputMediaVenue是轮询媒体的专属类型它不能用于sendMediaGroup之类的普通媒体组场景而是服务于sendPoll的explanation_media测验说明配图与media问卷描述配图字段。这一点与InputMediaLocation的地位一致。2.3 联合类型使用 Pydantic Discriminated UnionInputPollMediaUnion与InputPollOptionMediaUnion都用Annotated[... , Field(discriminatortype)]声明。这意味着 Pydantic 会根据输入数据中的type字段值自动分派到具体子类型。例如传入{type: venue, latitude: ...}时Pydantic 会实例化出InputMediaVenue。InputMediaVenue.type固定为venue因此它总是能够被正确识别。三、字段详解与参数说明下表汇总InputMediaVenue的完整字段依据源码 aiogram/types/input_media_venue.py 整理字段类型必填默认值说明typeLiteral[venue]否有默认值InputMediaType.VENUE媒体类型必须为venuelatitudefloat是—地点的纬度longitudefloat是—地点的经度titlestr是—地点名称addressstr是—地点地址foursquare_idstr \| None否NoneFoursquare 地点标识foursquare_typestr \| None否NoneFoursquare 地点类型例如arts_entertainment/default、arts_entertainment/aquarium、food/icecreamgoogle_place_idstr \| None否NoneGoogle Places 地点标识google_place_typestr \| None否NoneGoogle Places 地点类型几个值得注意的细节latitude/longitude的类型是float在 Telegram API 中要求符合 WGS 84 坐标系传入整数如3会被 Pydantic 隐式转换为3.0但推荐显式写成浮点数。foursquare_type的取值遵循 Foursquare 的分类体系官方示例形如arts_entertainment/default一级/二级分类以斜杠分隔。google_place_type的取值对应 Google Places API 的支持类型列表。关于四个第三方字段的使用约定要么只填 Foursquare 两个字段要么只填 Google 两个字段避免混用——这是 Telegram Bot API 对sendVenue/InputMediaVenue的通用约束混用可能导致地点展示异常。文章不在此展开外部链接实际使用以官方 API 文档约束为准。四、实例化与序列化InputMediaVenue继承自TelegramObject本质是一个 Pydantic 模型。因此实例化方式与普通 Pydantic 模型一致既可以用关键字参数也可以从字典构建from aiogram.types import InputMediaVenue # 关键字参数构造 venue InputMediaVenue( latitude31.2304, longitude121.4737, title上海博物馆, address上海市黄浦区人民大道201号, google_place_idChIJ..., google_place_typemuseum, ) # 从字典构造联合类型场景下由 type 字段分派 venue_from_dict InputMediaVenue.model_validate( { type: venue, latitude: 31.2304, longitude: 121.4737, title: 上海博物馆, address: 上海市黄浦区人民大道201号, } ) # 序列化回 JSON用于最终发给 Telegram API payload venue.model_dump(exclude_noneTrue) print(payload)输出大致为{ type: venue, latitude: 31.2304, longitude: 121.4737, title: 上海博物馆, address: 上海市黄浦区人民大道201号, google_place_id: ChIJ..., google_place_type: museum }源码中if TYPE_CHECKING:块内还自动生成了一份完整的__init__签名由butcher工具生成注释中明确标注 DO NOT EDIT MANUALLY!!! This section was auto-generated viabutcher。它的作用是仅为类型检查与 IDE 补全提供显式签名运行时仍走 Pydantic 的super().__init__(**__pydantic_kwargs)。因此在编辑器中InputMediaVenue(latitude..., longitude..., title..., address...)会获得完整的参数提示而无需依赖任何 IDE 插件。五、实战场景一在 sendPoll 中使用 InputMediaVenue5.1 sendPoll 的两个媒体字段在 aiogram/methods/send_poll.py 中SendPoll方法声明了两个接收轮询媒体的字段explanation_media: InputPollMediaUnion | None None Media added to the quiz explanation media: InputPollMediaUnion | None None Media added to the poll description也就是说InputMediaVenue可以作为explanation_media测验quiz说明中附带的地点插图——当用户答错或点击灯泡图标查看解释时展示media问卷描述中附带的地点插图。由于InputPollMediaUnion是带discriminatortype的联合类型直接传入InputMediaVenue实例即可正确分派无需手动标注类型。5.2 完整示例发送带地点插图的测验from aiogram import Bot from aiogram.types import InputMediaVenue, InputPollOption bot Bot(tokenYOUR_BOT_TOKEN) await bot.send_poll( chat_id123456789, question这家博物馆位于哪个城市, options[ InputPollOption(text上海), InputPollOption(text北京), ], typequiz, correct_option_id0, explanation点击查看博物馆的位置卡片。, explanation_mediaInputMediaVenue( latitude31.2304, longitude121.4737, title上海博物馆, address上海市黄浦区人民大道201号, google_place_idChIJ..., google_place_typemuseum, ), )说明options接收InputPollOptionUnionInputPollOption类型来自 aiogram/types/input_poll_option.py测验模式的正确选项通过correct_option_id指定0 起索引explanation_media接受InputPollMediaUnion其中包含InputMediaVenue因此可以直接把构造好的 venue 对象传进去。六、实战场景二独立发送地点卡片sendVenueInputMediaVenue本身是输入媒体而如果你需要直接发送一张地点卡片不依托轮询应当使用SendVenue方法其 bot 级快捷入口为Bot.send_venue见 aiogram/client/bot.py 附近。SendVenue方法类源码位于 aiogram/methods/send_venue.py核心字段如下字段类型必填说明chat_idChatIdUnion是目标会话 ID或username格式的用户名latitudefloat是地点纬度longitudefloat是地点经度titlestr是地点名称addressstr是地点地址business_connection_idstr \| None否商务连接 ID用于代表商务账号发送message_thread_idint \| None否论坛主题topic的消息线程 IDfoursquare_id/foursquare_typestr \| None否Foursquare 地点标识与类型google_place_id/google_place_typestr \| None否Google Places 地点标识与类型disable_notificationbool \| None否静默发送protect_contentbool \| Default \| None否默认Default(protect_content)继承客户端默认配置开启后禁止转发与保存allow_paid_broadcastbool \| None否付费广播允许每秒最多 1000 条消息每条 0.1 Starsmessage_effect_idstr \| None否消息特效 ID仅私聊suggested_post_parametersSuggestedPostParameters \| None否直聊中的建议帖子参数reply_parametersReplyParameters \| None否回复参数reply_markupReplyMarkupUnion \| None否内联键盘 / 自定义键盘等附加界面ephemeral_message_parametersEphemeralMessageParameters \| None否临时消息参数6.1 Bot.send_venue 用法from aiogram import Bot bot Bot(tokenYOUR_BOT_TOKEN) message: Message await bot.send_venue( chat_id123456789, latitude31.2304, longitude121.4737, title上海博物馆, address上海市黄浦区人民大道201号, google_place_idChIJ..., google_place_typemuseum, protect_contentTrue, reply_markupInlineKeyboardMarkup( inline_keyboard[ [InlineKeyboardButton(text查看路线, urlhttps://t.me/...)], ] ), )成功时返回Message对象其venue字段会填充为Venue类型包含location、title、address以及可选的 Foursquare / Google 字段。6.2 快捷方法 answer_venue / reply_venueSendVenue在 aiogram 中还有丰富的从已接收对象出发的快捷入口见 docs/api/methods/send_venue.rstMessage.answer_venue(...)/Message.reply_venue(...)在收到消息的会话中回复地点卡片ChatJoinRequest.answer_venue(...)/ChatJoinRequest.answer_venue_pm(...)ChatMemberUpdated.answer_venue(...)InaccessibleMessage.answer_venue(...)/InaccessibleMessage.reply_venue(...)。以Message.answer_venue为例实现位于 aiogram/types/message.py 附近它内部构造SendVenue(...).as_(self._bot)并复用消息自身的会话上下文因此无需再传chat_idfrom aiogram.filters import Command from aiogram.types import Message router.message(Command(venue)) async def send_venue_card(message: Message) - None: await message.answer_venue( latitude31.2304, longitude121.4737, title上海博物馆, address上海市黄浦区人民大道201号, )七、源码级佐证测试用例与调用链7.1 SendVenue 的测试覆盖仓库中 tests/test_api/test_methods/test_send_venue.py 对SendVenue提供了完整的端到端测试使用MockedBot注册SendVenue的模拟结果然后调用bot.send_venue(...)并断言返回值与预设一致。测试中使用了真实的地点数据Cupboard Under the Stairs位于哈利波特世界的 Privet Drive并同时构造了Venue(locationLocation(...), title..., address...)作为返回的Message.venue内容。该测试印证了两个事实Bot.send_venue内部将参数组装为SendVenue方法对象并通过await self(call)交给客户端发送见 aiogram/client/bot.py 附近发送地点卡片后返回的Message中venue字段是Venue类型而非InputMediaVenue——两者分工明确。7.2 消息类型映射在 tests/test_api/test_types/test_message.py 的MESSAGES_AND_COPY_METHODS表中[TEST_MESSAGE_VENUE, SendVenue]表明当收到一条 venue 类型的消息时aiogram 会将其content_type识别为VENUE并将复制该消息的操作映射到SendVenue方法。这进一步佐证了 venue 在收发两个方向上的完整类型闭环。7.3 底层调用链小结Bot.send_venue(chat_id, latitude, longitude, title, address, ...) └── SendVenue(chat_id..., latitude..., ...) # aiogram/methods/send_venue.py └── await self(call, request_timeout...) # Bot 的调用入口 └── Telegram API: POST sendVenue └── 返回 Message(venueVenue(...))对应地InputMediaVenue走的是另一条链路InputMediaVenue(latitude..., longitude..., title..., address...) └── 作为 SendPoll.explanation_media / mediaInputPollMediaUnion └── await bot.send_poll(...) └── Telegram API: POST sendPoll八、常见误区与最佳实践不要把 InputMediaVenue 用于 sendMediaGroupInputMediaUnion不包含InputMediaVenuesend_media_group的参数类型为list[InputMediaUnion]传入InputMediaVenue会在类型检查阶段直接报错。地点媒体只服务于send_poll。不要混用 Foursquare 与 Google 两组字段InputMediaVenue同时暴露四可选字段但同一地点只需提供其中一组混用属于 API 约束不推荐的做法。必填字段一个都不能少latitude、longitude、title、address为必填缺失时 Pydantic 抛ValidationError。优先使用快捷方法在事件处理器中回复地点卡片时优先用message.answer_venue(...)而非bot.send_venue(chat_idmessage.chat.id, ...)可减少样板代码并复用回复上下文。注意protect_content的默认行为它默认绑定客户端级Default(protect_content)配置即不显式传值时继承全局默认设置而非简单地默认为False。九、关联文档与进一步阅读类型定义源码aiogram/types/input_media_venue.py联合类型声明aiogram/types/input_poll_media_union.py、aiogram/types/input_poll_option_media_union.py使用方法对象aiogram/methods/send_venue.py、aiogram/methods/send_poll.pyBot 级快捷入口aiogram/client/bot.py接收侧类型aiogram/types/venue.py测试佐证tests/test_api/test_methods/test_send_venue.py、tests/test_api/test_types/test_message.pyAPI 文档docs/api/methods/send_venue.rst、docs/api/methods/send_poll.rst掌握InputMediaVenue的字段语义与适用场景你就能在 aiogram 中灵活地为问卷和测验附加地点插图并通过sendVenue体系独立、可靠地发送地点卡片。赞分享后端即时通讯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点击查看免费下载相关推荐x402 EVM 机制包深度解析x402/evm 参考实现与 Permit2、Up-To Scheme 的落地实践x402 EVM 机制包深度解析x402/evm 参考实现与 Permit2、Up To Scheme 的落地实践 导读 x402/evm 是 x402后端即时通讯API设计aiogram 发送地点消息指南SendVenue 方法全解析与实战aiogram 发送地点消息指南SendVenue 方法全解析与实战 sendVenue 是 Telegram Bot API 中用于向用户发送地点卡片后端即时通讯API设计aiogram 的 Venue 类型详解从场地消息发送到内联结果返回的完整实战指南aiogram 的 Venue 类型详解从场地消息发送到内联结果返回的完整实战指南 本篇技术指南聚焦 aiogram基于 asyncio 的全异步 Tele后端即时通讯API设计上一篇GetQzonehistory一键永久备份QQ空间说说的开源利器下一篇如何通过Hearthstone-Script实现炉石传说自动化对战创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
阅读完成 · 觉得有帮助?
咨询建站