I am coding a discord bot. The commands I'm having issues with is temprole and kick.
The ping command seems to work fine.
main.js
const Discord = require('discord.js');
const client = new Discord.Client();
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('Bot is online!');
});
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 == 'temprole') {
client.commands.get('temprole').execute(message, args);
}
});
client.login('token')
temprole.js
module.exports = {
name: 'youtube',
description: "give the member a temprole",
execute(message, args) {
if (message.member.roles.cache.has('798180573998612512')) {
} else {
message.channel.send('You dont have access to this command!')
}
}
}
kick.js
module.exports = {
name: 'kick',
description: "This command kicks a member!",
execute(messages, args) {
const member = message.mentions.users.first();
if (member) {
const memberTarger = message.guild.members.cache.get(member.id);
memberTarger.kick();
message.channel, send('User has been kicked');
} else {
message.channel.send('You coundt kick that member');
}
}
}
In your temprole.js, the "name" property does not match temprole, therefore the commands collection will set the command name as "youtube". You then try to get the "temprole" command from the collection but there aren't any. The fix is to change your command name's property to "temprole".
Related
const discord = require('discord.js')
const client = new discord.Client({ intents: ["GUILDS", "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.on('ready', () => {
console.log("================");
console.log("|Bot is ready|");
console.log("================");
});
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 === 'ip'){
client.commands.get('ip').execute(message, args);
} else if (command == 'creator'){
client.commands.get('creator').execute(message, args);
} else if (command == 'rulespost'){
client.commands.get('rulespost').execute(message, args, discord);
} else if(command == 'test'){
client.commands.get('test').execute(message, args);
}
})
And with this I get an error with 'rulespost' saying TypeError: Cannot read properties of undefined (reading 'execute')
and within rulespost.js is
module.exports = {
name: 'RulesPost',
description: "Posts the rules of the server",
execute(message, args, discord) {
const newEmbed = Discord.MessageEmbed()
.setColor('#000000')
.setTitle('Official Rules for ALL Platforms')
.setDescription('...')
.addFields(
{value: 'TEXT'}
)
message.channel.send(newEmbed)
}
}
And when using the &rulespost command the bot dies and nothing else happens.
all other commands work fine with no problems but trying to use the embed command it kills the bot completely.
Note this is WRONG, however it can not be taken down as it is marked for some reason.
the syntax for the execute function is incorrect. The interpreter thinks that you are calling a function and then passing further items to the object. this can be fixed by adding the function keyword or by assigning execute to an anonymous function like so:
module.exports = {
name: 'RulesPost',
description: "Posts the rules of the server",
// Execute is the key for the anon. function
execute: function(message, args, discord) {
const newEmbed = Discord.MessageEmbed()
.setColor('#000000')
.setTitle('Official Rules for ALL Platforms')
.setDescription('...')
.addFields(
{value: 'TEXT'}
)
message.channel.send(newEmbed)
}
}
This creates the execute function that you are exporting.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Main Code:
const Discord = require("discord.js");
const client = new Discord.Client();
const prefix = ";";
client.once("ready", () => {
console.log("Online dziecino!");
client.user.setActivity("jebanie bydgoszczy", {
type: "STREAMING",
url: "https://www.twitch.tv/its_not_important",
});
});
client.on("message", (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 (command === "kick") {
client.commands.get("kick").execute(message, args);
}
});
client.login("my token is here");
Kick Command:
module.exports = {
name: "kick",
description: "This command kicks a member!",
execute(message, args) {
const target = message.mentions.users.first();
if (target) {
const memberTarget = message.guild.members.cache.get(target.id);
memberTarget.kick();
message.channel.send("User has been kicked");
} else {
message.channel.send('You coudn\'t kick that member!');
}
},
};
Error:
TypeError: Cannot read property 'get' of undefined
at Client.<anonymous> (C:\Users\kubak\Desktop\Discord Bot\main.js:82:18)
at Client.emit (events.js:315:20)
You need command handler:
Add this to your code:
client.commands= new Discord.Collection();
const commandFiles = readdirSync(join(__dirname, "commands")).filter(file => file.endsWith(".js"));
for (const file of commandFiles) {
const command = require(join(__dirname, "commands", `${file}`));
client.commands.set(command.name, command);
}
And add this before the "Token" :
client.on("message", async message => {
if(message.author.bot) return;
if(message.channel.type === 'dm') return;
if(message.content.startsWith(prefix)) {
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if(!client.commands.has(command)) return;
try {
client.commands.get(command).run(client, message, args);
} catch (error){
console.error(error);
}
}
})
Add a folder with the name "commands" to your bot's directory.
Put kick command in commands folder.
const Discord = require('discord.js');
module.exports = {
name: "kick",
description: "This command kicks a member!",
async run (client, message, args) {
const target = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if(!args[0]) return message.channel.send('Error, write target');
target.kick(reason)
.catch(err => {
if(err) return message.channel.send('Error.')
})
}
}
The following line throws the error:
if (!client.commands.has(command)) return;
I'm following this tutorial= Tutorial
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.on('message', 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 (message.content === `${prefix}serverinfo`) {
message.channel.send(message.guild.name)
message.channel.send(`Total Members: ${message.guild.memberCount}`)
} else if (message.content === `${prefix}me`) {
message.channel.send(`Username: ${message.author.username}`)
message.channel.send(`ID: ${message.author.id}`)
} else if (message.content === `${prefix}boi`) {
message.channel.send('BOI')
}
});
if (!client.commands.has(command)) return;
You can't return in the top scope, return must be inside a function.
You may either put the logic inside an if statement
if (client.commands.has(command)) {
const command = client.commands.get(command);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply("There was an issue executing that command!")
}
client.login(token);
}
Or wrap the logic inside a function, an IIFE may be a good choice:
(() => {
if (!client.commands.has(command)) return;
const command = client.commands.get(command);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply("There was an issue executing that command!")
}
client.login(token);
})();
Trying to make a "mute command" comes up with TypeError: Cannot read property 'add' of undefined If you could help me Thanks :)
module.exports = {
name: 'mute',
description: 'f',
execute(message, args) {
const taggedUser = message.mentions.users.first();
const mutedRole = "800612654234337281"
if (!message.mentions.users.size) {
return message.reply(`Oh, thats unexpected you haven't tagged anyone.`);
}
message.channel.send(`${taggedUser} has been muted`);
taggedUser.roles.add(mutedRole);
},
};
Here is the "main file" if there is an issue with this
const fs = require('fs');
const Discord = require('discord.js');
const client = new Discord.Client();
const { prefix, token } = require('./config.json');
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 => {
const args = message.content.slice(prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();
if (!client.commands.has(command)) return;
try {
client.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
client.login(token);
This will not work because discord user and guild member both are completely different methods. You cannot add roles to discord user in any guild (unless your bot is in the said guild), you can only add roles to guild member.
replace:
message.mentions.users.first()
with:
message.mentions.members.first()
Learn more about:
Discord User
Guild Member
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) {
...
}