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
相关产品推荐
相关产品推荐

