I have a function that send messages, but it doesn't work because it's not inside
client.on('message', msg => {
How can I do?
You can send messages from outside client.on('message'..., All you need is channel ID and then you can simply do:
const myChannel = client.channels.get('CHANNEL_ID');
myChannel.send(`your message here!`);
EDIT
You can use this inside a function by passing it as a parameter:
const myChannel = client.channels.get('CHANNEL_ID');
function myFunc(channel) {
channel.send('MESSAGE');
}
Now you can call your function using myChannel:
myFunc(myChannel);
client.on("message") is an event that will trigger each time a new message is sent in a channel the bot can see. (DMs included.)
To send a message to a channel id, first you have to find the channel using the client.channels collection.
const Discord = require("discord.js");
const Client = new Discord.Client(); // Creating a new Discord Client.
Client.on("ready", () => {
const Channel = Client.channels.get("your channel id"); // Searching the channel in the collection channels.
if (!Channel) {
return console.error("No channel found!"); // If the channels does not exist or the bot cannot see it, it will return an error.
} else {
return Channel.send("Your message to send here!"); // We found the channel. Sending a message to it.
};
}); // Making sure the client is ready before sending anything.
Client.login("your bot token here"); // Logging into Discord with the bot's token.
Related
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');
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
I am making bot to manage my multiple Discord guilds. And I'd like to make confirmation system, like:
User does X thing,
Bot sends message in sufficient channel,
Bot waits for user to react with :thumbdsup: or :thumbsdown: up to 60 seconds
If thumbs up, do A, else - do B. If time is up, do C action
How can I build system like that, due to I have no idea.
Adding and Setting Up the Event Listener
First we start by defining discord.js & adding an event listener:
const Discord = require('discord.js'); //defining discord
const client = new Discord.Client(); //getting your bot
client.on('message', async message => { //when a user sends a message
});
Then you would need to tell the bot what it does after that:
const Discord = require('discord.js'); //defining discord
const client = new Discord.Client(); //getting your bot
client.on('message', async message => { //when a user sends a message
if (message.author.bot) return; //If a bot sent the message we want to ignore it.
if (message.content.toLowerCase() === 'what message your looking for' { //what your looking for (make sure this string is all in lower case)
//what you want the bot to do after the message you are looking for has been sent
}
});
Now, if you want the bot to add the reaction to the message you will do the following:
const Discord = require('discord.js'); //defining discord
const client = new Discord.Client(); //getting your bot
client.on('message', async message => { //when a user sends a message
if (message.author.bot) return; //If a bot sent the message we want to ignore it.
if (message.content.toLowerCase() === 'what message your looking for' { //what your looking for (make sure this string is all in lower case)
await message.react('👍'); //reacting to the message with a thumbs up emoji
await message.react('👎'); //reacting to the message with a thumbs down emoji
}
});
If you wanted the bot to reply to the message use:
const Discord = require('discord.js'); //defining discord
const client = new Discord.Client(); //getting your bot
client.on('message', async message => { //when a user sends a message
if (message.author.bot) return; //If a bot sent the message we want to ignore it.
if (message.content.toLowerCase() === 'what message your looking for' { //what your looking for (make sure this string is all in lower case)
message.channel.send('The bots message here') //what you want the bot to reply with
}
});
Awaiting Reactions
Here it all depends on if you want to await reactions on the bot's message or the user's message.
If you would like to await reactions from the bot's message use:
const Discord = require('discord.js'); //defining discord
const client = new Discord.Client(); //getting your bot
client.on('message', async message => { //when a user sends a message
if (message.author.bot) return; //If a bot sent the message we want to ignore it.
if (message.content.toLowerCase() === 'what message your looking for' { //what your looking for (make sure this string is all in lower case)
message = await message.channel.send('The bots message here') //waiting for the message to be sent
const filter = (reaction, user) => { //filtering the reactions from the user
return (
['👎', '👍'].includes(reaction.emoji.name) && user.id === message.author.id
);
}
message.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] }) //awaiting the reactions - remember the time is in milliseconds
.then((collected) => {
const reaction = collected.first();
if (reaction.emoji.name === '👍') { //if the reaction was a thumbs up
//A action
reaction.users.remove(message.author.id) //If you wanted to remove the reaction
} else { //if the reaction was a thumbs down
//B action
reaction.users.remove(message.author.id) //If you wanted to remove the reaction
}
}).catch((collected) => { //when time is up
//C action
});
}
});
If you wanted to await message from the user's message you would do the same thing except change:
if (message.content.toLowerCase() === 'what message your looking for' { //what your looking for (make sure this string is all in lower case)
message.channel.send('The bots message here') //sending the message but not awaiting reactions from it
bot.on('channelCreate', async channel => {
if (!channel.guild) return;
const fetchedLogs = await channel.guild.fetchAuditLogs({
limit: 1,
type: 'CHANNEL_CREATE',
});
const logbook = channel.guild.channels.cache.get("ChannelID")
const deletionLog = fetchedLogs.entries.first();
if (!deletionLog) return logbook.send(`A channel was updated but no relevant autid logs were found`);
const { executor, user } = deletionLog;
if (user.id) {
logbook.send(`${executor.tag} created a channel`);
} else {
logbook.send(`A channel was created but idk who did.`);
}
});
I am a newbie when it comes to fetching actions through Discord Audit Logs; so I am experimenting and somehow came up with this code. However, when I create a channel, it does not send any messages saying that a channel has been created by #user. I have no idea what my next step will be. All I wanted to do was to know who created the channel.
Discord.JS: v12.2.0
client.on("channelCreate", async channel => {
if (!channel.guild) return false; // This is a DM channel.
const AuditLogFetch = await channel.guild.fetchAuditLogs({limit: 1, type: "CHANNEL_CREATE"}); // Fetching the audot logs.
const LogChannel = client.channels.cache.get("722052103060848664"); // Getting the loggin channel. (Make sure its a TextChannel)
if (!LogChannel) return console.error(`Invalid channel.`); // Checking if the channel exists.
if (!AuditLogFetch.entries.first()) return console.error(`No entries found.`);
const Entry = AuditLogFetch.entries.first(); // Getting the first entry of AuditLogs that was found.
LogChannel.send(`${Entry.executor.tag || "Someone"} created a new channel. | ${channel}`) // Sending the message to the logging channel.
});
If the code I provided is not working, please make sure the bot has access to view AuditLogs.
When a user joins the server, the bot sends a welcome message, i want to take that welcome message's ID and make the bot delete it if the users leaves after he joins. I tried to save the message's id in a variable and make the bot delete the message when the user leaves but without success. I already took a look at the docs, but I really can't understand how to make it.
Define an object to hold the welcome messages by guild and user. You may want to use a JSON file or database (I'd highly recommend the latter) to store them more reliably.
When a user joins a guild...
Send your welcome message.
Pair the the message's ID with the user within the guild inside of the object.
When a member leaves the guild...
Fetch their welcome message.
Delete the message from Discord and the object.
Example setup:
const welcomeMessages = {};
client.on('guildMemberAdd', async member => {
const welcomeChannel = client.channels.get('channelIDHere');
if (!welcomeChannel) return console.error('Unable to find welcome channel.');
try {
const message = await welcomeChannel.send(`Welcome, ${member}.`);
if (!welcomeMessages[member.guild.id]) welcomeMessages[member.guild.id] = {};
welcomeMessages[member.guild.id][member.id] = message.id;
} catch(err) {
console.error('Error while sending welcome message...\n', err);
}
});
client.on('guildMemberRemove', async member => {
const welcomeChannel = client.channels.get('channelIDHere');
if (!welcomeChannel) return console.error('Unable to find welcome channel.');
try {
const message = await welcomeChannel.fetchMessage(welcomeMessages[member.guild.id][member.id]);
if (!message) return;
await message.delete();
delete welcomeMessages[member.guild.id][member.id];
} catch(err) {
console.error('Error while deleting existing welcome message...\n', err);
}
});
To do this you would have to store the id of the welcome message and the user that it is tied to (ideally put this in an object). And when the user leaves you would use those values to delete that message.
Example code:
const Discord = require('discord.js');
const client = new Discord.Client();
const welcomeChannel = client.channels.find("name","welcome"); // Welcome is just an example
let welcomes = [];
client.on('message', (message) => {
if(message.channel.name === 'welcome') {
const welcomeObj = { id: message.id, user: message.mentions.users.first().username };
welcomes.push(welcomeObj);
}
});
client.on('guildMemberRemove', (member) => {
welcomes.forEach(welcome, () => {
if(welcome.user === member.user.username) {
welcomeChannel.fetchMessage(welcome.id).delete();
}
});
});
This only works if the welcome message includes a mention to the user so make sure that's in the welcome message.
Also I can't test this code myself at the moment so let me know if you encounter any problems.
I've spent 3 hours building and tweaking a Node.js web scraper and over 4 hours trying to find a freaking way to broadcast a message to a channel on Discord. I have lost all hope at this time...
This is the code I have, and some parts work, like replying to a message. But I can't find any possible way to just send a message, without that message being a reply.
const discord = require('discord.js');
const bot = new discord.Client();
const cfg = require('./config.json')
bot.on('ready', () => {//this works
console.log(`Logged in as ${bot.user.tag}(${bot.user.id}) on ${bot.guilds.size} servers`)
});
bot.on('message', (msg) => {
switch (msg.content) {
case '/epicinfo':
msg.channel.send('w00t'); //this works
}
});
console.log(bot.users.get("id", "504658757419270144")) //undefined
console.log(bot.channels.get("name", "testbot")) //undefined
console.log(bot.users.find("id", "504658757419270144")) //undefined
console.log(bot.channels.find("name", "testbot")) //undefined
console.log(bot.guilds.get("504658757419270144")); //undefined
console.log(bot.channels.get(504658757419270144)) //undefined
bot.send((discord.Object(id = '504658757419270144'), 'Hello')) //discord.Object is not a function
bot.login(cfg.token);
That might be caused by the fact that you're running your code before the bot is logged in.
Every action has to be made after the bot has emitted the ready event, the only thing you can do outside the ready event is defining other event listeners.
Try putting that part of your code inside the ready event listener, or inside a function called by that event:
client.on('ready', () => {
console.log("Your stuff...");
});
// OR
function partA () {...}
function partB () {...}
client.on('ready', () => {
partA();
console.log("Your stuff...");
partB();
});
// OR
function load() {...}
client.on('ready', load);
In your situation:
client.on('ready', () => { // once the client is ready...
let guild = client.guilds.get('guild id here'); // ...get the guild.
if (!guild) throw new Error("The guild does not exist."); // if the guild doesn't exist, exit.
let channel = guild.channels.get('channel id here'); // if it does, get the channel
if (!channel) throw new Error("That channel does not exist in this guild."); // if it doesn't exist, exit.
channel.send("Your message here.") // if it does, send the message.
});
client.login('your token here')
Try:
bot.channels.find(channel => channel.id === '504658757419270144').send('Your-message');
also, if the channel you are trying to send the message to is in the bots guild, you can use:
bot.on('message' (msg) => {
msg.guild.channels.find(channel => channel.name === 'your-channel-name').send('your-message');
});