Discord bot won't answer commands - javascript

I just created a bot, doesn't do anything special, but it just won't answer commands.
I enable intents on the dev portal, I gave him admin privileges, the bot is online. It won't give me any error. Looking for something similar but it all ends up in something to do with the intents which I feel that they are right. This is the code:
const { Client, GatewayIntentBits, Partials, ActivityType } = require("discord.js");
const fs = require("fs");
require("dotenv").config();
const mySecret = process.env['TOKEN']
const { setCommands } = require("./commands/help.js")
const { prefix } = require("./config.js");
const commands = {};
const client = new Client(
{
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
],
partials: [
Partials.Message,
Partials.User,
Partials.Channel,
Partials.GuildMember
]
});
// load commands
const commandFiles = fs.readdirSync("./commands").filter(file => file.endsWith(".js"));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands[command.name] = command;
}
setCommands(commands)
// login bot
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}`);
client.user.setActivity('Dimensions', {
type: ActivityType.Listening
})
});
client.on("message", message => {
console.log(message)
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
let cmd = commands[command];
if(cmd)
cmd.execute(message, args)
});
client.login(mySecret);
This is the comand
module.exports = {
name: "ping",
description: "Replies with 'pong'",
execute: (message) => {
message.channel.send("pong")
}
}
This is my config file
module.exports = {
prefix: "!"
}
There is a help.js too where I set up some help commands with other commands, I don't think is relevant but I'll update it if it is. Also, this is running on replit, not sure if that matters?
Thankss

You have to return the execute to execute the code:
module.exports = {
name: "ping",
description: "Replies with 'pong'",
execute: (message) => {
return message.channel.send("pong")
}
}

Related

Discord.JS bot not replying to commands nor returning a error in console regarding it

I've been struggling to get my new Discord bot's command handler to work, While it is seeing the command files (as indicated by its log entry on startup stating the amount of commands it has loaded) it either isn't sending the messages, or it isn't even executing them.
Here's my code:
const { Client, Intents, Collection } = require('discord.js');
const { token, ownerid, statuses, embedColors, prefix } = require('./cfg/config.json');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const fs = require('fs');
const { config } = require('process');
client.commands = new Collection();
const commands = [];
const cmdfiles = fs.readdirSync('./cmds').filter(file => file.endsWith('.js'));
client.once('ready', () => {
console.clear
console.log(`Ready to go, Found ${cmdfiles.length} commands and ${statuses.length} statuses!`)
setInterval(() => {
var status = Math.floor(Math.random() * (statuses.length -1) +1)
client.user.setActivity(statuses[status]);
}, 20000)
}),
client.on("error", (e) => console.log(error(e)));
client.on("warn", (e) => console.log(warn(e)));
// Command Handler
for (const file of cmdfiles) {
const command = require(`./cmds/${file}`);
commands.push(command.data);
}
client.on('messageCreate', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (!client.commands.has(command)) {
embeds: [{
title: ":x: Oopsie!",
color: config.embedColors.red,
description: `Command ${args.[0]} doesn't exist! Run ${config.prefix}help to see the avaliable commands!`,
footer: app.config.footer + " Something went wrong! :("
}];
} else {
try {
client.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
embeds: [{
title: ":x: Oopsie!",
description: "Command execution failed",
fields: [
{ name: "Error Message", value: `${e.message}` }
],
footer: app.config.footer + " Something went wrong :("
}];
}
message.channel.send
}});
client.login(token);
and the test command is
module.exports = {
name: "test",
description: "does as it implies, dingusA",
async execute(client, message, args) {
message.channel.send("This is a message!");
}
}
You need the GUILD_MESSAGES intent in order to receive messages in guilds.
Add the following intent in your code
const client = new Client({ intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES ]
})
This applies to other things as well eg. DIRECT_MESSAGES for DMs and etc.

I cant get access to the client in my command file discord.js

My reaction role file:
module.exports = {
name: "rr",
desc: "make a reaction role --> <",
async run(message, client) {
const jsEmoji = "🍏";
const pythonEmoji = "🍍";
let embedMessage = await message.channel.send("react for a role");
embedMessage.react(jsEmoji);
embedMessage.react(pythonEmoji);
client.on("messageReactionAdd", (user, reaction) => {
console.log("he reacted");
});
},
};
my bot file:
const intents = new Discord.Intents(32767);
I initialized my client here
const client = new Discord.Client({ intents: intents });
const fs = require("fs");
const commandFolders = fs.readdirSync("./Commands");
client.commands = new Discord.Collection();
commandFolders.forEach((folder) => {
const commandFiles = fs
.readdirSync(`./Commands/${folder}`)
.filter((file) => file.endsWith(".js"));
commandFiles.forEach((file) => {
const command = require(`./Commands/${folder}/${file}`);
client.commands.set(command.name, command);
});
});
client.on("messageCreate", (message) => {
if (message.author.bot || !message.content.startsWith(config.prefix)) return;
const [command, ...args] = message.content
.substring(config.prefix.length)
.split(/\s+/);
I tried getting access to the client here and passing it into the run function but that didnt work.
client.commands.forEach((cmd) =>
command === cmd.name
? client.commands.get(cmd.name).run(message, args, client)
: null
);
});
client.login(config.token);
My Error:
client.on("messageReactionAdd", (user, reaction) => {
^
TypeError: client.on is not a function
Is there another way to get access to my client?
your arguments are wrong on command file.
You should use async run(client, message, args)
Here's a full code for you:
module.exports = {
name: "rr",
desc: "make a reaction role --> <",
async run(client, message, args) {
const jsEmoji = "🍏";
const pythonEmoji = "🍍";
let embedMessage = await message.channel.send("react for a role");
embedMessage.react(jsEmoji);
embedMessage.react(pythonEmoji);
client.on("messageReactionAdd", (user, reaction) => {
console.log("he reacted");
});
},
};

Discord not loading slash commands

I am trying to make a slash command system for my discord.js bot, but it does not show up in the app
Here is the code I am using
const {
Client,
Collection,
Intents
} = require('discord.js');
const client = new Client({
intents: [Intents.FLAGS.GUILDS]
});
const fs = require('fs');
const {
Routes
} = require('discord-api-types/v9');
const { REST } = require('#discordjs/rest');
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
const commands = [];
// Creating a collection for commands in client
client.commands = new Collection();
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
client.commands.set(command.data.name, command);
}
client.on('ready', () => {
console.log(`Ready! Logged in as ${client.user.tag}`)
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
// Set a new item in the Collection
// With the key as the command name and the value as the exported module
console.log(`Loaded slash command /${command.data.name}.`)
}
const CLIENT_ID = client.user.id;
const rest = new REST({
version: '9'
}).setToken("myToken");
(async () => {
try {
await rest.put(
Routes.applicationCommands(CLIENT_ID), {
body: commands
},
);
console.log('Successfully registered all application commands globally');
} catch (error) {
if (error) console.error(error);
}
})();
})
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
const { options } = interaction
try {
await command.execute(interaction, options, client);
} catch (error) {
console.error(error);
await interaction.reply({
content: `ERROR: There was a problem executing the **${command.name}** command. Please try again later.`,
ephemeral: true
});
}
});
client.login("myToken")
This is my command file (My ping.js file)
const { SlashCommandBuilder } = require("#discordjs/builders");
module.exports = {
data: new SlashCommandBuilder()
.setName("ping")
.setDescription("Ping Pong!"),
async execute(interaction, options, client) {
interaction.reply("Pong!")
}
}
Whenever I launch my bot, no slash commands appear. All the strings are logged to the console though.
I have given the bot application.commands scope.

How do I ping someone in a reply to a command in Discord.js

How I want my bot to ping people
I want to make it so that my bot pings people whenever it replies to a command, like how I'm replying in the image, with the #ON and not actually including a mention in the message.
I tried declaring it in the client options in the index.js file, but it doesn't seem to work.
My index.js file:
const fs = require('fs');
const { Discord, Client, Collection, Intents, MessageEmbed } = require('discord.js');
const bottoken = process.env.token
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES], allowedMentions: { repliedUser: true } });
client.commands = new Collection();
const eventFiles = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args, client));
} else {
client.on(event.name, (...args) => event.execute(...args, client, MessageEmbed));
}
}
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.login(bottoken);
The command that I'm testing with (this is my only command, I want to make sure that stuff like these options work before adding more commands):
module.exports = {
name: 'ping',
description: 'Replies with Pong!',
async execute(interaction) {
await interaction.reply({ content: 'Pong!' });
},
};
CommandInteraction.reply only replies to the Interaction. You need to use Message.reply.
client.on('messageCreate', message => {
if (message.author.bot) return false;
if (message.content === 'reply') {
message.reply({
content: 'This is a reply.'
})
}
});

I'm having issues in Discord.js with functions like client.users.cache.size

Whenever I try to use a function like client.users.cache.size or client.guilds.size, they keep giving me an error like "TypeError: Cannot read property 'guilds' of undefined" or "TypeError: Cannot read property 'cache' of undefined".
I was also trying to use let guilds = client.guilds.cache.array().join('\n') but it also throws the same error.
Command's code:
const Discord = require('discord.js');
module.exports = {
name: 'stats',
description: 'Views the bot\'s stats',
execute(client, message) {
const embed = new Discord.MessageEmbed
.setDescription(`In ${client.guilds.size} servers`)
.setTimestamp()
.setFooter(message.member.user.tag, message.author.avatarURL());
message.channel.send(embed)
}
}
Bot's main file:
const path = require('path');
const fs = require("fs");
const { token, prefix } = require('./config.json');
const Discord = require('discord.js');
const db = require ('quick.db');
const client = new Discord.Client
client.commands = new Discord.Collection();
const isDirectory = source => fs.lstatSync(source).isDirectory();
const getDirectories = source => fs.readdirSync(source).map(name => path.join(source, name)).filter(isDirectory);
getDirectories(__dirname + '/commands').forEach(category => {
const commandFiles = fs.readdirSync(category).filter(file => file.endsWith('.js'));
for(const file of commandFiles) {
const command = require(`${category}/${file}`);
client.commands.set(command.name, command);
}
});
client.on("ready", () => {
console.log(`ready!.`);
console.log(token);
// Activities
const activities_list = [
`Serving Tacos | .help`,
`Preparing Orders | .help`
];
setInterval(() => {
const index = Math.floor(Math.random() * (activities_list.length - 1) + 1);
client.user.setActivity(activities_list[index]);
}, 10000);
});
//Joined Guild
client.on("guildCreate", (guild) => {
const EmbedJoin = new Discord.MessageEmbed()
.setColor('#FFFF33')
.setTitle(`Joined Guild: ${guild.name}!`)
.setTimestamp()
console.log(`Joined New Guild: ${guild.name}`);
client.channels.cache.get(`746423099871985755`).send(EmbedJoin)
});
//Left Guild
client.on("guildDelete", (guild) => {
const EmbedLeave = new Discord.MessageEmbed()
.setColor('#FFFF33')
.setTitle(`Left Guild: ${guild.name}.`)
.setTimestamp()
console.log(`Left Guild: ${guild.name}`);
client.channels.cache.get(`746423099871985755`).send(EmbedLeave)
});
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName)
|| client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return;
if (command.guildOnly && message.channel.type === 'dm') {
return message.reply('I can\'t execute that command inside DMs!');
}
if (command.args && !args.length) {
let reply = `${message.author}, wrong usage`;
if (command.usage) {
reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
}
return message.channel.send(reply);
}
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
process.on("error", () => {
console.log("Oops something happened!");
});
client.login(token);
In your code, client.guilds returns a manager, so you have to use client.guilds.cache.size. The rest of the code works fine.
const Discord = require('discord.js');
module.exports = {
name: 'stats',
description: 'Views the bot\'s stats',
execute(message, args, client) {
const embed = new Discord.MessageEmbed
.setDescription(`In ${client.guilds.cache.size} servers`)
.setTimestamp()
.setFooter(message.member.user.tag, message.author.avatarURL());
message.channel.send(embed)
}
}
In your main bot file you're only passing the message and the args (in this order) to command.execute(). You can add the client too, and update the parameters in your command's code to match this order.
try {
command.execute(message, args, client);
} catch (error) {
...
}

Categories