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

5.1k Views Asked by At

I'm getting traceback with my code in the channel. The command is supposed to send a dm of my choice to a user, YET it just replies to my message with that traceback error below! Can anyone help?

Source code:

@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**.")

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

2

There are 2 best solutions below

0
On BEST ANSWER

First thing, this is a self-explained error. Second thing you didn't read the docs.

Basically, ctx don't have user object. Now, if you want to mention/DM the invoked user, use this:

@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**.")
0
On

Try this:

@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**.")

You would just use user.send instead of ctx.user.send because that does not exist.