I'm trying to code a discord bot that send a message to all users in a list. I am having problems using the client.users.fetch(); method on discord.js. The error message says something about DiscordAPIError: Unknown user, Unhandled promise rejection, and DiscordAPIError: Cannot send messages to this user, even though I am in the same guild as the bot.Here is the code I have so far:
const Discord = require('discord.js');const client = new Discord.Client();const ownerId = 'YOUR-ID'const users = ['YOUR-ID']client.on('ready', () => {console.log('Bot is online!');});client.on('message', async message => {if (message.content.includes("test")) {if (message.author.id == ownerId) {message.channel.send("ok!")var userIDvar userfor (let i = 0; i < users.length; i++) {userID = users[i];user = client.users.fetch(userID.toString(), true);client.user.send('works');}}}});client.login('YOUR-TOKEN');
Best Answer
There are several issues in your code.
Firstly, client.users.fetch(...)
is an asynchronous function therefore it requires an await
.
Secondly, client.user.send(...)
will actually send a message to the bot which is impossible. So you'll want to replace it with either message.channel.send(...)
which will send the message in the same channel the message was received in or message.author.send(...)
which will send a message to the author of the message.
Below is an example fix:
const Discord = require('discord.js'); // Define Discordconst client = new Discord.Client(); // Define clientconst ownerId = 'your-discord-user-id';const users = [] // Array of user ID'sclient.on('ready', () => { // Ready event listenerconsole.log('Bot is online!'); // Log that the bot is online});client.on('message', async message => { // Message event listenerif (message.content.includes("test")) { // If the message includes "test"if (message.author.id == ownerId) { // If the author of the message is the bot ownermessage.channel.send("ok!"); // Send a message// Define variableslet userID;let user;for (let i = 0; i < users.length; i++) { // Loop through the users arrayuserID = users[i]; // Get the user ID from the arrayuser = await client.users.fetch(userID.toString()); // Await for the user to be fetchedmessage.channel.send('works'); // Send a message to tell the message author the command worked}}}});client.login('YOUR-TOKEN'); // Login your bot