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.
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.
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!
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With