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

如何在aiogram 3中将Serverless事件转换为types.Update类型

问题解决:Serverless架构下Telegram机器人转换Update对象报错

错误原因

  1. 你错误地将Serverless的event完整对象传给了types.Update,但实际应该使用Telegram Webhook发送的请求体数据(也就是event['body']解析后的内容)。
  2. types.Update是基于Pydantic的模型,它的构造函数要求传入关键字参数,或者使用parse_obj方法加载字典数据,直接传位置参数会触发__init__() takes exactly 1 positional argument (2 given)错误。

修正后的代码

async def handler(event, context):
    await process_event(event, dp)
    return {'statusCode': 200, 'body': 'ok'}

async def process_event(event, dp: Dispatcher):
    # 解析Telegram Webhook的请求体数据
    update_data = json.loads(event['body'])
    # 使用parse_obj方法将字典转换为types.Update对象
    update = types.Update.parse_obj(update_data)
    # 或者使用关键字参数传入:update = types.Update(**update_data)
    bot = Bot(token=TOKEN)
    await dp.feed_update(bot, update)

额外注意事项

  • 确保已通过BotFather将你的Serverless函数URL设置为机器人的Webhook地址。
  • 建议将Dispatcher和Bot的初始化逻辑放在函数外部,避免每次请求都重复初始化,优化Serverless冷启动后的性能。
  • 必须返回200状态码给Telegram,否则Telegram会重复发送请求。

内容的提问来源于stack exchange,提问作者Vyrex

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 19:22:07