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 userID var user for (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');
Advertisement
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 Discord const client = new Discord.Client(); // Define client const ownerId = 'your-discord-user-id'; const users = [] // Array of user ID's client.on('ready', () => { // Ready event listener console.log('Bot is online!'); // Log that the bot is online }); client.on('message', async message => { // Message event listener if (message.content.includes("test")) { // If the message includes "test" if (message.author.id == ownerId) { // If the author of the message is the bot owner message.channel.send("ok!"); // Send a message // Define variables let userID; let user; for (let i = 0; i < users.length; i++) { // Loop through the users array userID = users[i]; // Get the user ID from the array user = await client.users.fetch(userID.toString()); // Await for the user to be fetched message.channel.send('works'); // Send a message to tell the message author the command worked } } } }); client.login('YOUR-TOKEN'); // Login your bot