Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In discord.js, Can I send DirectMessage to user With DiscordBot?

I want to send private messages to a User with a Discord Bot.

The user is not in the same server as the bot.

If I can use author.sendMessage, how can I initialize(find) author variable?

Can I find the user with User id?

Thank you for reading.

like image 654
inhoLee Avatar asked Mar 19 '18 07:03

inhoLee


People also ask

Can Discord bots DM users?

Bots need to have at least 1 common server with a user to be able to send a direct message. If the user is on the same server as the bot, only then you can send a DM, using any of the other methods on this post.


3 Answers

For anyone interested in how to do this with Discord.js v12, here's how:

client.users.cache.get('<id>').send('<message>');

Hope this helps someone!

like image 104
Billy Lardner Avatar answered Oct 19 '22 15:10

Billy Lardner


These answers are good, but you cannot guarantee that a user is cached with client.users.cache.get, especially with intents updates which limits the amount of data Discord sends to you.

A full proof solution is this (assuming environment is async):

const user = await client.users.fetch("<id>").catch(() => null);

if (!user) return message.channel.send("User not found:(");

await user.send("message").catch(() => {
    message.channel.send("User has DMs closed or has no mutual servers with the bot:(");
});

Not only this answer does the job, but it will attempt to fetch the user from the cache first if they exist, and if they do not, the library will attempt to fetch the user from the Discord API which completely shuts down cache from sabotaging everything. I have also added some .catch statements to prevent unhandled rejections and give much better responses!

Similar with sending a DM to a message author (assuming the message object is named as 'message'):

await message.author.send("message").catch(() => {
    message.channel.send("User has DMs closed or has no mutual servers with the bot:(");
});

Please do not rely on cache as much nowadays (except when fetching guilds and channels since they are always cached by the library), and as other answers have already stated, the bot must have at least one mutual server with the user and the user must have their DMs open and have the bot unblocked.

like image 22
Epic Speedy Avatar answered Oct 19 '22 15:10

Epic Speedy


And The user is not in the same server with bot.

And

I make a mistake, I want to send Privatemessage to User who isn't in same server with bot I added.. [source]

That is not possible to do.
Bots need to have at least 1 common server with a user to be able to send a direct message.
If the user is on the same server as the bot, only then you can send a DM, using any of the other methods on this post.
client.users.get("someID").send("someMessage");

like image 15
André Avatar answered Oct 19 '22 15:10

André