Code:
const config = require('../../config.json');
const Discord = require('discord.js');
module.exports = async(guild, bannerURL, client) => {
const logChannel = await client.channels.cache.get(config.log_channel_id);
if (!logChannel) return;
const embed = new Discord.MessageEmbed()
.setAuthor({ name: guild.name, iconURL: guild.iconURL() })
.setDescription(`**${guild.name} has banner now!**`)
.setImage(bannerURL)
.setColor(config.colour)
.setTimestamp()
return logChannel.send({ embeds: [embed] })
}
When adding a banner to the server it gives the error Unhandled Rejection: TypeError: Cannot read properties of undefined (reading 'channels')
The other logging files have the exact same line of code const logChannel = await client.channels.cache.get(config.log_channel_id); and it works fine
Adding console.log(client) before const logChannel returns undefined
This code below works after we troubleshot the issue.
banner.js
module.exports = {
name: 'banner',
description: 'emit update',
devs: true,
run: async (guild, message) => {
guild.emit('guildBannerAdd', message.member);
message.channel.send('Done ...');
},
};
guildBannerAdd.js
const config = require('../../config.json')
const Discord = require('discord.js')
module.exports = async (client, member) => {
const guild = client.guilds.cache.get(config.serverID)
const logChannel = client.channels.cache.get(config.log_channel_id);
if (!logChannel) return;
const embed = new Discord.MessageEmbed()
.setAuthor({
name: guild.name,
iconURL: guild.iconURL()
})
.setDescription(`**${guild.name} has banner now!**`)
.setImage(guild.bannerURL())
.setColor(config.colour)
.setTimestamp();
return logChannel.send({
embeds: [embed]
});
}
Related
I'm kinda new to coding and i cannot figure this out. im trying to add permission handler and when i run a slash command, it responds within the error given below.
error:
D:\VS Code\######\events\interactionCreate.js:9
command.run(client, inter)
^
TypeError: command.run is not a function
code (interactionCreate):
const { MessageEmbed, Message, Interaction } = require("discord.js")
const client = require("../index").client
client.on('interactionCreate', async inter => {
if(inter.isCommand()) {
const command = client.commands.get(inter.commandName);
if(!command) return;
command.run(client, inter)
if (command.help?.permission) {
const authorPerms = inter.channel.permissionsFor(inter.member);
if (!authorPerms || !authorPerms.has(command.permission)) {
const noPerms = new MessageEmbed()
.setColor('RED')
.setDescription(`bruh no perms for ya: ${command.permission}`)
return inter.editReply({embeds: [noPerms], ephemeral: true})
.then((sent) =>{
setTimeout(() => {
sent.delete()
}, 10000)
})
return;
}
}
}
}
)
this is how one of my command file looks like, its a handler which goes "commands > moderation > ban.js"
const { MessageEmbed, Message } = require("discord.js")
module.exports.run = async (client, inter) => {
const user = inter.options.getUser('user')
let BanReason = inter.options.getString('reason')
const member = inter.guild.members.cache.get(user.id)
if(!BanReason) reason = 'No reason provided.'
const existEmbed = new MessageEmbed()
.setColor('#2f3136')
.setDescription('<:pending:961309491784196166> The member does not exist in the server.')
const bannedEmbed = new MessageEmbed()
.setColor('#46b281')
.setDescription(`<:success:961309491935182909> Successfully banned **${user.tag}** from the server with the reason of: **${BanReason}**.`)
const failedEmbed = new MessageEmbed()
.setColor('#ec4e4b')
.setDescription(`<:failed:961309491763228742> Cannot ban **${user.tag}**. Please make sure I have permission to ban.`)
if(!member) return inter.reply({ embeds: [existEmbed]})
try {
await inter.guild.members.ban(member, { reasons: BanReason })
} catch(e) {
return inter.reply({ embeds: [failedEmbed]})
}
inter.reply({ embeds: [bannedEmbed]})
}
module.exports.help = {
name: 'ban',
permission: 'BAN_MEMBERS'
}
btw inter = interaction
i have been trying to make a leaveserver code for my bot, but i always get the error message Cannot read properties of undefined (reading 'send') I really wanna know why it always says the error messages! Please help me! Thanks!
const Discord = require("discord.js")
const rgx = /^(?:<#!?)?(\d+)>?$/;
var self = this
const OWNER_ID = require("../../config.json").OWNER_ID;
module.exports = {
name: "leaveserver",
description: "leavs a server",
run: async (client, message, args) => {
if (!OWNER_ID)
return message.channel.send("This command is Owner Only")},
async run(message, args) {
const guildId = args[0];
if (!rgx.test(guildId))
return message.channel.send("Please Provide a valid server id!")
const guild = message.client.guild.cache.get(guildId);
if (!guild) return message.channel.send(message, 0, 'Unable to find server, please check the provided ID');
await guild.leave();
const embed = new MessageEmbed()
.setTitle('Leave Guild')
.setDescription(`I have successfully left **${guild.name}**.`)
.setFooter(message.member.displayName, message.author.displayAvatarURL({ dynamic: true }))
.setTimestamp()
.setColor(message.guild.me.displayHexColor);
message.channel.send({embeds: [embed]});
}
}
Try this code
const {
MessageEmbed
} = require("discord.js")
const rgx = /^(?:<#!?)?(\d+)>?$/;
const OWNER_ID = require("../../config.json").OWNER_ID;
module.exports = {
name: "leaveserver",
description: "leaves a server",
run: async (client, message, args) => {
const guildId = args[0];
const guild = message.client.guilds.cache.get(guildId);
if (!OWNER_ID) return message.channel.send("This command is Owner Only");
if (!rgx.test(guildId)) return message.channel.send("Please Provide a valid server id!")
if (!guild) return message.channel.send(message, 0, 'Unable to find server, please check the provided ID');
await guild.leave();
const embed = new MessageEmbed()
.setTitle('Leave Guild')
.setDescription(`I have successfully left **${guild.name}**.`)
.setFooter({
text: message.member.displayName,
iconURL: message.author.displayAvatarURL({
dynamic: true
})
})
.setTimestamp()
.setColor(message.guild.me.displayHexColor)
message.channel.send({
embeds: [embed]
})
}
}
Removed the duplicated async run(message, args) {
Try to do this:
const client = new Discord.Client({intents:
["GUILDS", "GUILD_MESSAGES"]});
client.on("message" , msg => {
await guild.leave();
const embed = new MessageEmbed()
.setTitle('Leave Guild')
.setDescription(`I have successfully left **${guild.name}**.`)
.setFooter(msg.member.displayName, msg.author.displayAvatarURL({ dynamic: true }))
.setTimestamp()
.setColor(msg.guild.me.displayHexColor);
msg.channel.send({embeds: [embed]});
})
I want to make a poll command, where the bot send an embed with the poll and afterwards reacts to it with some emojis. I added the reaction Intent to my index.js but still get an error everytime I call the command. This is my code:
const { SlashCommandBuilder } = require('#discordjs/builders')
const { MessageEmbed } = require('discord.js')
module.exports = {
data: new SlashCommandBuilder()
.setName("poll")
.setDescription("Create a quick poll.")
.addStringOption(option => option.setName("question").setDescription("The question").setRequired(true)),
async execute(interaction) {
const question = interaction.options.getString("question")
const message = await interaction.reply({embeds: [
new MessageEmbed()
.setColor('GREEN')
.setTitle(`Discord Poll`)
.setAuthor(`Requested by ${interaction.member.user.tag}`, interaction.member.user.avatarURL())
.setDescription(question)
.setThumbnail('https://pngimg.com/uploads/question_mark/question_mark_PNG126.png')
.setTimestamp()
.setFooter('Bot by Iuke#4681', 'https://cdn.discordapp.com/emojis/912052946592739408.png?size=96')
]})
message.react(':check:')
.then(() => message.react(':neutral:')
.then(() => message.react(':xmark:')))
}
}
And get this error:
TypeError: Cannot read properties of undefined (reading 'react')
You will need to fetch the reply. You can use the fetchReply option and set it to true.
module.exports = {
data: new SlashCommandBuilder()
.setName('poll')
.setDescription('Create a quick poll.')
.addStringOption((option) =>
option
.setName('question')
.setDescription('The question')
.setRequired(true),
),
async execute(interaction) {
const question = interaction.options.getString('question');
const message = await interaction.reply({
embeds: [
new MessageEmbed()
.setColor('GREEN')
.setTitle(`Discord Poll`)
.setAuthor(
`Requested by ${interaction.member.user.tag}`,
interaction.member.user.avatarURL(),
)
.setDescription(question)
.setThumbnail(
'https://pngimg.com/uploads/question_mark/question_mark_PNG126.png',
)
.setTimestamp()
.setFooter(
'Bot by Iuke#4681',
'https://cdn.discordapp.com/emojis/912052946592739408.png?size=96',
),
],
fetchReply: true,
});
// you could use await to react in sequence instead of then()s
await message.react(':check:');
await message.react(':neutral:');
await message.react(':xmark:');
},
};
According to the docs you need to add the fetchReply option on interaction.reply like this:
const message = await interaction.reply({ content: 'Pong!', fetchReply: true });
I am trying to code in / commands into my discord bot. But I keep on getting this error:
Cannot read property 'commands' of undefined
Below I have attached my main.js file, as well as the part that just keeps giving me the error:
Part that gives me the error
const getApp = (guildID) => {
const app = client.api.applications(client.user.id)
if (guildID) {
app.guilds(guildID)
}
}
client.once('ready', async() => {
client.user.setActivity('FALLBACK BOT, USE THE MAIN CHECKPOINT BOT INSTEAD. THIS IS FOR DEVELOPMENT PURPOSES')
const commands = await getApp(guildID).commands.get()
console.log(commands)
await getApp(guildID).commands.post({
data: {
name: 'ping',
description: 'Shows your current ping.',
},
})
});
Here is the full script
// Just grabbing some librarys
const Discord = require('discord.js');
require('dotenv').config();
const client = new Discord.Client({ partials: ["MESSAGE", "CHANNEL", "REACTION" ]});
const mongoose = require('mongoose');
// Defining the guildID
const guildID = (process.env.guildID);
// Filtering the command folder so it only includes .js files
const { join } = require('path');
const fs = require('fs');
require('./dashboard/server');
client.commands = new Discord.Collection();
client.events = new Discord.Collection();
const getApp = (guildID) => {
const app = client.api.applications(client.user.id)
if (guildID) {
app.guilds(guildID)
}
}
client.once('ready', async() => {
client.user.setActivity('FALLBACK BOT, USE THE MAIN CHECKPOINT BOT INSTEAD. THIS IS FOR DEVELOPMENT PURPOSES')
const commands = await getApp(guildID).commands.get()
console.log(commands)
await getApp(guildID).commands.post({
data: {
name: 'ping',
description: 'Shows your current ping.',
},
})
});
['command_handler', 'event_handler'].forEach(handler =>{
require(`./handlers/${handler}`)(client, Discord);
})
mongoose.connect(process.env.MONGODB_SRV, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
}).then(()=> {
console.log('Connected to Database')
}).catch((err) =>{
console.log(err);
})
// Logging into the bot (THIS INCLUDES THE TOKEN SO DONT INCLUDE IT WHEN SENDING MESSAGES)
client.login(process.env.DISCORD_TOKEN);
Note: I am quite new to JS so. keep that in mind
Your getApp() function doesn't return anything so you are trying to read commands property from undefined value.
You have to return you app.guilds(guildId) so you can read property from it.
const getApp = (guildID) => {
const app = client.api.applications(client.user.id)
if (guildID) {
app.guilds(guildID)
}
return app;
}
client.once('ready', async() => {
client.user.setActivity('FALLBACK BOT, USE THE MAIN CHECKPOINT BOT INSTEAD. THIS IS FOR DEVELOPMENT PURPOSES')
const app = getApp(guildID);
if (app === null) {
console.error('error');
return;
}
const commands = await app.commands.get()
console.log(commands)
await app.commands.post({
data: {
name: 'ping',
description: 'Shows your current ping.',
},
})
});
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) {
...
}