This question already has answers here:
message event listener not working properly
(2 answers)
Closed 1 year ago.
I have been trying to set up a discord bot and by following the docs, I have been able to set up a slash command but have not been able to get the bot to reply to messages on the server.
Here is the code I used to set up slash command from docs.
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const commands = [{
name: 'ping',
description: 'Replies with Pong!'
}];
const rest = new REST({ version: '9' }).setToken('token');
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID),
{ body: commands },
);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
After this I set up the bot with this code:
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
client.once('ready', () => {
console.log('Ready!');
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('interactionCreate', async interaction => {
// console.log(interaction)
if (!interaction.isCommand()) return;
if (interaction.commandName === 'ping') {
await interaction.reply('Pong!');
// await interaction.reply(client.user + '💖');
}
});
client.login('BOT_TOKEN');
Now I am able to get a response of Pong! when I say /ping.
But after I added the following code from this link I didn't get any response from the bot.
client.on('message', msg => {
if (msg.isMentioned(client.user)) {
msg.reply('pong');
}
});
I want the bot to reply to messages not just slash commands. Can someone help with this. Thanks!!🙂
First of all you are missing GUILD_MESSAGES intent to receive messageCreate event.
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
Secondly the message event is deprecated, use messageCreate instead.
client.on("messageCreate", (message) => {
if (message.mentions.has(client.user)) {
message.reply("Pong!");
}
});
At last, Message.isMentioned() is no logner a function, it comes from discord.js v11. Use MessageMentions.has() to check if a user is mentioned in the message.
Tested using discord.js ^13.0.1.
Related
Im using the lastest Discord.js 14 and trying to create a new channel in the support category.
I manually created the category so I know it exists.
There are no channels in this category at present and this new channel the bot is trying to create will be the first one.
When I run this code console.log(supportCategory) the terminal shows undefined
Why?
// Require the necessary discord.js classes
const { Client, Events, GatewayIntentBits, ChannelTypes } = require('discord.js');
const { token } = require('./config.json');
// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
// When the client is ready, run this code (only once)
// We use 'c' for the event parameter to keep it separate from the already defined 'client'
client.once(Events.ClientReady, c => {
console.log(`Ready! Logged in as ${c.user.tag}`);
});
client.on('ready', async () => {
console.log(`Logged in as ${client.user.tag}!`);
const guild = client.guilds.cache.first();
const supportCategory = guild.channels.cache.find(channel => channel.type === 'GUILD_CATEGORY' && channel.name === 'Support');
console.log(supportCategory) //this produces undefined
try {
const channel = await guild.channels.create('new-channel-name', {
type: 'GUILD_TEXT',
parent: supportCategory.id,
permissionOverwrites: [
{
id: guild.roles.everyone.id,
deny: ['VIEW_CHANNEL'],
},
],
});
console.log(`Channel created: ${channel.name}`);
} catch (error) {
console.error(error);
}
});
// Log in to Discord with your client's token
client.login(token);
You need to use the ChannelType enum to check a channel's category.
const supportCategory = guild.channels.cache.find(channel => channel.type === ChannelType.GuildCategory && channel.name === 'Support');
I am trying to use WOKcommands to create a kick command in discord.js, but whenever I run the command I get this error:
Error: A client is required
Here is my code
const { Client, GatewayIntentBits } = require('discord.js')
const Commands = require("wokcommands")
require('dotenv/config')
const client = new Client({
partials: ["MESSAGE", "REACTION"],
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
]
})
client.on('ready', () => {
console.log('Bee-bot has started')
client.user.setActivity('The commands')
new Commands(client, { commandsDir: "commands"})
})
client.on('messageCreate', message => {
if (message.content === 'bee help') {
message.reply('Welcome the to Bee-bot Help pane.\nThe prefix is "bee" and it is case sensitive.\nbee help: displays the help pane.\nbee ban: bans a user')
}
})
client.on('messageCreate', message => {
if (message.content === 'bee ban') {
if (message.member.permissions.has("BAN_MEMBERS")) {
if (message.members.mentions.first()) {
try {
MessageChannel.members.mentions.first().ban();
} catch {
message.reply("I do not have permissions to ban" + message.members.mentions.first());
}
} else {
message.reply("You do not have permissions to ban" + message.members.mentions.first());
}
}
}
})
client.login(process.env.TOKEN)
I tried changing the variable name but it came up with the same error
In wokcommands, you actually need to pass in one object which has the client property in it, but you are passing the client outside of the object which raised the error as it was unable to find a client property in the object. You can check the docs for wokcommands here
I'm trying to make my bot in discord on javascript, the bot goes online, shows in the console, but does not respond to messages
const Discord = require("discord.js")
const TOKEN = "MY TOKEN"
const client = new Discord.Client({
intents: [
"Guilds",
"GuildMessages"
]
})
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}`)
})
client.on("message", message => {
if (message.content.includes('ping'))
if (userCooldown[message.author.id]) {
userCooldown[message.author.id] = false;
message.reply('Pong');
setTimeout(() => {
userCooldown[message.author.id] = true;
}, 5000) // 5 sec
}
})
client.login(TOKEN)
Alright, there are a few issues at play here. Before I start, I should say that discord bots are moving away from reading message content and towards slash commands. If you have the opportunity to, please move towards slash commands. If you're looking for an up-to-date tutorial check out https://discordjs.guide.
With that being said, let me go through each issue one by one.
You're not asking for the MessageContent intent. You will not be able to check if the user's message contains ping
const client = new Discord.Client({
intents: [
"Guilds",
"GuildMessages",
"MessageContent"
]
})
I don't know if this is because this code has been shortened or not, but you're not defining userCooldown anywhere.
const userCooldown = {}
message doesn't exist as an event anymore. Use messageCreate instead
Your cooldown logic doesn't really work. I would flip the boolean around
client.on("messageCreate", message => {
if (message.content.includes('ping')) {
if (!userCooldown[message.author.id]) {
userCooldown[message.author.id] = true;
message.reply('Pong');
setTimeout(() => {
userCooldown[message.author.id] = false;
}, 5000) // 5 sec
}
}
})
You might have forgotten to enable this in the discord developer portal.
The complete code I used to make it work is below. I wish you luck on your discord developer journey.
const Discord = require("discord.js")
const TOKEN = "TOKEN_HERE"
const client = new Discord.Client({
intents: [
"Guilds",
"GuildMessages",
"MessageContent"
]
})
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}`)
})
const userCooldown = {}
client.on("messageCreate", message => {
if (message.content.includes('ping')) {
if (!userCooldown[message.author.id]) {
userCooldown[message.author.id] = true;
message.reply('Pong');
setTimeout(() => {
userCooldown[message.author.id] = false;
}, 5000) // 5 sec
}
}
})
client.login(TOKEN)
lately, I started working on a discord bot and added slash commands.
I noticed that I have a ping(replies with pong) command that I didn't create or I did and I can't get rid of it.
Here is my interactionHandler.js
const { REST } = require("#discordjs/rest");
const { Routes } = require("discord-api-types/v9");
module.exports = async (err, files, client) => {
if (err) return console.error(err);
client.interactionsArray = [];
files.forEach((file) => {
const interaction = require(`./../interactions/${file}`);
client.interactions.set(interaction.data.name, interaction);
client.interactionsArray.push(interaction.data.toJSON());
});
const rest = new REST({ version: "9" }).setToken(process.env.DISCORD_TOKEN);
(async () => {
try {
// console.log("Refreshing slash command list");
// const guildIds = await client.guilds.cache.map((guild) => guild.id);
// const clientId = await client.user.id;
// guildIds.forEach(async (guildId) => {
// await rest.put(Routes.applicationGuildCommands(clientId, guildId), {
// body: client.interactionsArray,
// });
// });
await rest.put(
Routes.applicationGuildCommands("934895917453168653", "967384688069066852"),
{ body: client.interactionsArray},
);
console.log("Successfully refreshed slash command list");
} catch (error) {
console.error(error);
}
})();
};
Is there a way to delete the command because I cant find a way.
I was thinking of getting the ID of the command but I don't know how.
Thanks for all the helpers :)
Discord.js v13
These commands may not be refreshing because of 2 reasons:
These commands may be global commands to change that to refreshing global (instead of guild) commands replace Routes.applicationGuildCommands to Routes.applicationCommands
These commands may be from a different guild which in the case you should change the guild ID
To figure out the problem you should do client.application.commands.fetch() to get all your commands and then console.log() the result.
Example
//This will fetch all your slash commands
const commands = await client.application.commands.fetch();
//Returns a collection of application commands
console.log(commands);
This is the code, I want it to write user's name and then auction word (p.s I am new to this)
const Discord = require('discord.js')
const client = new Discord.Client()
const { MessageEmbed } = require('discord.js');
const channel = client.channels.cache.get('889459156782833714');
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.on("message", msg => {
var message = new Discord.MessageEmbed()
.setColor('#FF0000')
.setTitle() // want user's name + "Auction"
.addField('Golden Poliwag', 'Very Pog', true)
.setImage('https://graphics.tppcrpg.net/xy/golden/060M.gif')
.setFooter('Poliwag Auction')
if (msg.content === "d.test") {
msg.reply(message)
}
})
You can access the user's username by using msg.author.tag. So. the way to use the user's tag in an embed would be:
const { MessageEmbed, Client } = require("discord.js");
const client = new Client();
const channel = client.channels.cache.get("889459156782833714");
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("message", (msg) => {
var message = new Discord.MessageEmbed()
.setColor("#FF0000")
.setTitle(`${msg.author.tag} Auction`)
.addField("Golden Poliwag", "Very Pog", true)
.setImage("https://graphics.tppcrpg.net/xy/golden/060M.gif")
.setFooter("Poliwag Auction");
if (msg.content === "d.test") {
msg.reply(message);
}
});
I suggest you to read the discord.js documentation, almost all you need to interact with Discord API is from there.
You can't control the bot if you don't login to it. Get the bot's token from Developer Portal and login to your bot by adding client.login('<Your token goes here>') in your project.
You can't get the channel if it's not cached in the client. You need to fetch it by using fetch() method from client's channels manager:
const channel = await client.channels.fetch('Channel ID goes here');
P/s: await is only available in async function
message event is deprecated if you are using discord.js v13. Please use messageCreate event instead.
You are able to access user who sent the message through msg object: msg.author. If you want their tag, you can get the tag property from user: msg.author.tag, or username: msg.author.username or even user ID: msg.author.id. For more information about discord message class read here.
The reply options for message is not a message. You are trying to reply the message of the author with another message which is wrong. Please replace the reply options with an object that includes embeds:
msg.reply({
embeds: [
// Your array of embeds goes here
]
});
From all of that, we now have the final code:
const { Client, MessageEmbed } = require('discord.js');
const client = new Client();
client.on("ready", () => {console.log(`Logged in as ${client.user.tag}!`)});
client.on("messageCreate", async (msg) => {
const channel = await client.channels.fetch('889459156782833714');
const embed = new Discord.MessageEmbed()
.setColor('#FF0000')
.setTitle(`${msg.author.tag} Auction`)
.addField('Golden Poliwag','Very Pog',true)
.setImage('https://graphics.tppcrpg.net/xy/golden/060M.gif')
.setFooter('Poliwag Auction');
if (msg.content === "d.test") {
msg.reply({
embeds: [ embed ],
});
}
});
client.login('Your bot token goes here');
Now your bot can reply to command user with an rich embed.