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

aiogram开发Telegram机器人时无法获取user id问题求助

aiogram无法获取用户ID问题修复方案

核心错误点

  • 参数名拼写错误:回调函数参数错写为massage,实际应为message
  • 类型标注错误:使用了小写types.message(该值为aiogram的message模块,不是消息对象类),正确的消息实例类型是大写开头的types.Message
  • 变量名冲突:额外导入了from aiogram.types import message,函数内调用message.from_user.id时实际指向导入的模块,而非用户触发的消息实例,因此无法获取用户ID

优化建议

无需手动调用bot.send_message传递用户ID,直接使用消息实例的answer方法即可向触发用户发送消息,代码更简洁不易出错。

修正后代码

from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor
import os

bot = Bot(token=os.getenv('TOKEN'))
dp = Dispatcher(bot)

@dp.message_handler(commands = ['start', 'help'])
async def commands_start(message : types.Message):
    # 推荐写法:直接调用answer方法
    await message.answer("Hello, who are you?")
    # 原写法修正后也可正常运行
    # await bot.send_message(message.from_user.id, "Hello, who are you?")

if __name__ == "__main__":
    executor.start_polling(dp, skip_updates=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 17:36:03