"AttributeError: 'Context' object has no attribute 'user'" when running a command Discord.py

"AttributeError: 'Context' object has no attribute 'user'" when running a command Discord.py

我在频道中得到了我的代码的回溯。该命令应该将我选择的 dm 发送给用户,但它只是用下面的回溯错误回复我的消息!有人可以帮忙吗?

源代码:

@client.command(aliases=["dm"])
async def DM(ctx, user: discord.User, *, message=None,):
    message = message or "This Message is sent via DM"
    try:
        await ctx.user.send(f"{message}.\n\nRegards,\Real_IceyDev")
        await ctx.channel.send(f"{ctx.user.mention}, check your DMs.")
    except Exception as jsonError:
        await ctx.channel.send(f"{ctx.author.mention}, an error ocurred!\nDeveloper Details:\n```fix\n{repr(jsonError)}\n```\nRecommended fixes: **enable your DMs if you haven't**.")

回溯:AttributeError("'Context' object has no attribute 'user'")

试试这个:

@client.command(aliases=["dm"])
async def DM(ctx, user: discord.User, *, message=None,):
    message = message or "This Message is sent via DM"
    try:
        await user.send(f"{message}.\n\nRegards,\Real_IceyDev")
        await ctx.channel.send(f"{ctx.author.mention}, check your DMs.")
    except Exception as jsonError:
        await ctx.channel.send(f"{ctx.author.mention}, an error ocurred!\nDeveloper Details:\n```fix\n{repr(jsonError)}\n```\nRecommended fixes: **enable your DMs if you haven't**.")

您只需使用 user.send 而不是 ctx。user.send 因为它不存在。

首先,这是一个 self-explained 错误。第二件事你没有阅读文档。

基本上,ctx 没有 user 对象。现在,如果你想 mention/DM 被调用的用户,使用这个:

@client.command(aliases=["dm"]) #Don't use nornmal command, use / command instead
async def DM(ctx, user: discord.User, *, message=None,):
    message = message or "This Message is sent via DM"
    try:
        await user.send(f"{message}.\n\nRegards,\Real_IceyDev") #DM the user in the command
        await ctx.channel.send(f"{user.mention}, check your DMs.") #Mention the user in the command
    except Exception as jsonError: #Not always error about json but work same so...
        await ctx.channel.send(f"{ctx.author.mention}, an error ocurred!\nDeveloper Details:\n```fix\n{repr(jsonError)}\n```\nRecommended fixes: **enable your DMs if you haven't**.")