You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用aiogram v2通过用户ID获取Telegram头像报错排查

问题分析

1. 消息处理函数参数缺失

aiogram v2中,被@dp.message_handler装饰的异步处理函数,Dispatcher会自动把当前的Message对象作为第一个参数传入。你的get_user_photo()没有定义这个参数,因此触发TypeError。

2. 同步函数调用异步方法

bot.get_user_profile_photos是异步方法,必须用await调用,但你的get_photo是普通同步函数,直接调用会返回协程对象,无法获取实际的头像数据。

3. 错误的媒体发送方式

photo_data是UserProfilePhotos类型的对象,不能直接用message.answer发送,需要提取头像的文件ID,使用专用的媒体发送方法。

修正后的代码
async def get_photo(user_id):
    # 异步方法必须用await调用
    photo_data = await bot.get_user_profile_photos(user_id, limit=1)
    return photo_data

@dp.message_handler(commands=['photo'])
async def get_user_photo(message):  # 添加message参数
    photo_data = await get_photo(367928353)  # 异步函数需要await调用
    if photo_data.total_count > 0:
        # 获取第一张头像的最大尺寸文件ID
        photo_file_id = photo_data.photos[0][-1].file_id
        await message.answer_photo(photo_file_id)
    else:
        await message.answer("该用户没有设置头像")
需要学习的内容
  • aiogram v2核心机制:了解消息/更新的处理流程,明确装饰器绑定的处理函数必须接收对应参数(如message、update等)。
  • Python异步编程:掌握async/await的使用规则,区分同步与异步代码的调用方式。
  • aiogram媒体操作:学习用户媒体(头像、文件等)的获取逻辑,以及照片、文档等媒体消息的发送方法,熟悉相关API的返回值结构。

内容的提问来源于stack exchange,提问作者Роман Лыжов

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 08:25:21