module.export and getting user information - javascript

I'm trying to display client.user.avatarURL in a command file through module.export using:
...
icon_url: client.user.avatarURL;
...
but when I call the command through the bot I have this error in the console:
TypeError: Cannot read property 'avatarURL' undefined
I've tried getting the value of the client on a const and pass it true the command handler but didn't solve it as well. If you delete that line everything works fine, so I guess is just a wrong way to pass client informations.
main.js
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.commands = new Discord.Collection();
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.once('ready', () => {
console.log('Online!');
});
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const commandName = args.shift().toLowerCase();
if (!client.commands.has(commandName)) return;
const command = client.commands.get(commandName);
if (command.args && !args.length) {
let reply = `You didn't provide enough arguments, ${message.author}!`;
if (command.usage) {
reply += `\nThe proper usage would be: \n\`${prefix}${command.name} ${command.usage}\``;
}
return message.channel.send(reply);
}
try {
command.execute(message, args, client);
}
catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
client.login(token);
and the command file:
module.exports = {
name: 'help',
description: 'Help file',
execute(message, client) {
message.channel.send({ embed: {
color: 0xf7da66,
author: {
name: 'Bot',
icon_url: client.user.avatarURL,
},
title: 'commands guide',
description: 'This is an discord bot.',
fields: [{
name: 'Command',
value: 'Type: example.',
},
],
timestamp: new Date(),
footer: {
icon_url: client.user.avatarURL,
text: '© Bot',
} } });
},
};

You are doing: command.execute(message, args, client); but then execute(message, client) { wich means that in your command file client is now actually the array args.
You need to do: execute(message, args, client) {

You need to use module.exports = (client, message, args) => { instead.

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 API error : cannot send an empty message

I was following a YouTube tutorial on how to program a discord bot, and I came across the infamous error "cannot send an empty message" while trying to send an embed. Here is my code :
main.js :
const Discord = require('discord.js');
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const prefix = '!';
const fs = require('fs');
client.commands = new Discord.Collection();
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.once('ready', () => {
console.log('Picobot is ready for use!');
});
client.on('message', message =>{
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'ping') {
client.commands.get('ping').execute(message, args);
} else if(command === 'pong') {
client.commands.get('pong').execute(message, args);
} else if(command === 'permissions') {
client.commands.get('permissions').execute(message, args);
}
if (command === 'embed') {
client.commands.get('command').execute(message, args, Discord);
}
});
embed.js :
module.exports = {
name: 'embed',
description: 'Embeds',
execute(message, args, Discord) {
const newEmbed = new Discord.MessageEmbed()
.setColor('#304281')
.setTitle('Rules')
.setURL('https://www.youtube.com/watch?v=dQw4w9WgXcQ')
.setDescription('This is a test embed')
.addFields(
{name: 'Rule 1', value: 'Placeholder 1'},
{name: 'Rule 2', value: 'Placeholder 2'},
{name: 'Rule 3', value: 'Placeholder 3'},
)
.setImage('https://images.radio-canada.ca/q_auto,w_960/v1/ici-info/16x9/rick-astley-videoclip-never-gonna-give-you-up.png');
message.channel.send({ newEmbed:newEmbed });
}
}
I have seen a number of other people having this error, the only solutions I've found and tried so far were to change message.channel.send({ newEmbed:newEmbed }) to message.channel.send(newEmbed), but the same error still pops up. I haven't seen any answered problems about this error in 2021, so I figured I'd shoot my shot here, thanks in advance.
Transitioning from v12 to v13 we have encountered another weary change that makes no sense to some users
// message.channel.send(newEmbed) does not work anymore
message.channel.send({
embeds: [newEmbed]
});
// The above is the way to go!
Another change: the message event listener:
client.on("message", () => {})
is depreciated and has been changed to messageCreate.
In v13 sending embeds is structured as such:
message.channel.send({ embeds: [newEmbed] });
Embeds - Discord.JS

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