Discord.py send DM to user using their ID

Question:

I want my bot to send a message to a certain user using command msg like this: !msg userid message
I am using this code which raises an error:

@client.command(name="msg", pass_context=True)
async def msg(context, userid, message):
    user = client.get_user(userid)
    await user.send(message)

Thanks in advance.

Asked By: Ján Mačička

||

Answers:

You’re passing userid in right from Discord, meaning that it will be a string. get_user expects an int so you can just cast it.

user = client.get_user(int(userid))

You can also use a converter for this:

async def msg(context, user: discord.User, message):
    await user.send(message)

Using the above ^, Discord will try to automatically take the ID you pass and create a discord.User instance from it, so you don’t have to use get_user anymore.

Friendly reminder that saying "it raises an error" is not at all helpful to us as to figuring out your problem, though. In the future add the traceback of the error to your post.

Answered By: stijndcl
@client.command()
async def msg(ctx, user: discord.User, *, message):
   await ctx.send("Sent")
   await asyncio.sleep(2)
   await user.send(f"Dad-Bot said: `{str(message)}`")

That’s how I would write it nowadays since if you just use {message} it will ignore the string of the message and not send the full message.

Answered By: CodingSap
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.