Ask coding questions

← Back to all posts
How to make my bot DM
dj741 (7)

So I am making a discord bot with discord.js and I need to find out how to make it DM a user if any way please say bellow

Voters
dj741 (7)
Comments
hotnewtop
alanchen12 (31)

You can use the <user>#send method as seen in the docs

If you want to send to the author of the message, use the <user>#send method or

message.author.send()

If you want to send to a user by id, fetch a user and send using the .send() function. Make sure they are in the cache. To fetch a user, use the <user>#fetch method.
Note: change client to what you defined client as.
Code:

const user = <client>.users.cache.fetch(id);
user.send();
cookieisgud (1)

Yes you can! If you have their ID, it is very easy.

const user = client.users.cache.fetch("<USER ID>");
user.send("Hello, world!");

If you don't have the user id, don't worry, you can still do it by username, as long as they are in a server the bot is in too.

const user = client.users.cache.find(user => user.username == "<USER NAME>");
user.send("Hello, worlD!");

please mark as correct answer, thanks!

alanchen12 (31)

@cookieisgud Um, I'm not sure the first one will work because you weren't fetching from the cache.

AloegelhiPlaysR (131)

This wont work for some people. Reason: Client is not defined in all of them. My "client" is defined as "Lynx" @cookieisgud

cookieisgud (1)

well most people define it as client lol @AloegelhiPlaysR

cookieisgud (1)

ther fixed, In my use case, it was guaranteed that the user was already in one of the bot's servers so that I didn't have to fetch from the cache. Thanks for pointing it out! @alanchen12