Python开发Discord机器人async def方法内调用字段报错如何解决
Discord.py 命令获取用户信息报错的排查修复方案
核心问题定位
你出现报错的根本原因是discord.ext.commands框架的命令函数参数定义错误:
- 命令函数的第一个参数
ctx是固定的上下文对象,已经包含了命令触发的消息、用户、频道等所有关联信息 - 你额外定义的第二个
message参数属于命令的位置输入参数,用户调用命令时没有传入对应内容就会参数缺失,就算传入了也是字符串类型,不存在.author属性,调用自然抛出异常
修复代码
直接从ctx对象提取用户信息即可,不需要额外定义message参数:
@bot.command() async def create(ctx): # 直接从上下文获取触发命令的用户ID和用户名,无需额外调用get_user user_id = ctx.author.id user_name = ctx.author.name # 如果你确实需要通过ID获取用户对象,写法如下,注意要取name属性才是用户名 # user_obj = bot.get_user(user_id) # user_name = user_obj.name if user_obj else "未知用户" # 后续你的档案存储逻辑,用user_id作为唯一键 db[str(user_id)] = { "username": user_name # 其他档案字段可自行扩展 }
额外注意事项
- 如果你使用的是discord.py v2.0及以上版本,需要开启
members意图否则get_user可能返回空,初始化bot时按以下配置:import discord from discord.ext import commands intents = discord.Intents.default() intents.members = True bot = commands.Bot(command_prefix="你的命令前缀", intents=intents) - Replit环境运行时不要硬编码Bot Token,建议通过
os.getenv("TOKEN")读取环境变量中存储的Token - 如果需要支持创建其他用户的档案,可以配置可选的提及用户参数,框架会自动解析@的用户对象:
@bot.command() async def create(ctx, target_user: discord.User = None): # 没指定用户就默认是命令触发者 target_user = target_user or ctx.author user_id = target_user.id user_name = target_user.name # 后续存储逻辑
内容的提问来源于stack exchange,提问作者Ggblocks20
相关产品推荐
相关产品推荐

