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.
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.
@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.
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.
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.
@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.