So, I have been making a suggestions command in discord.js and I keep getting the following error:
Cannot read property 'channels' of undefined
Here is my code, I have tried changing it in many ways but it doesn't work.
module.exports = {
name: "suggestion",
aliases: ['suggest', 'suggestion'],
permissions: [],
description: "suggetion command",
execute(message, args, cmd, client, discord) {
let channel = message.guild.channels.cache.get("865868649839460353");
if (!channel)
return message.reply('A suggestions channel does not exist! Please create one or contact a server administrator.')
.then(message => {
message.delete(6000)
})
.catch(error => {
console.error;
});
}
}
1st idea: The channel you're executing in is not a guild.
By fixing this, you can do:
if(!message.guild){
return
}
2nd idea: You may have specify the wrong channel in the wrong server. Do the following:
let guild = client.guilds.cache.get(`YourGuildId`)
let channel = guild.channels.cache.get(`ChannelId`)
or
let guild = client.guilds.cache.get(`${message.guild.id}`)
let channel = guild.channels.cache.get(`ChannelId`)
I hope these idea helped you! <3
Related
I want to change the name of a discord bot and I have read numerous tutorials and Stack Overflow posts and I still cannot get it. The code is primarily taken from open source bot code, so I know it works (something with my bot setup maybe?)
As I understand it, this code loops through each guild the bot is a member of and sets the nickname.
I found the botId by right clicking the bot in the channel and copying ID.
const { guildId } = require('../config');
module.exports = (client, botId, nickname) => {
client.guilds.cache.forEach((guild) => {
const { id } = guild;
client.guilds.cache
.get(id)
.members.cache.get(botId)
.setNickname(nickname);
});
};
The bot shows up in the channel (after using oauth2 url), so I'm assuming that means they are a member of the guild.
However, when running this code the bot is not found. I've tried several things from other posts like guild.array() to try and see a full list of the members in the guild, but nothing has worked.
const guild = client.guilds.cache.get('943284788004012072');
const bot = guild.members.cache.get('956373150864642159')
if (!bot) return console.log('bot not found');
Here is the full bot
require('dotenv').config();
const { Client, Intents } = require('discord.js');
const eventBus = require('../utils/events/eventBus');
const setNickname = require('../utils/setNickname');
const getPrice = require('../modules/statsGetters/getPriceDEX');
const { bots } = require('../config');
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
});
client.once('ready', async () => {
console.log('DEX Price Watch Bot Ready');
client.user.setPresence({
activities: [{ name: 'DEX Price', type: 'WATCHING' }],
status: 'online',
});
const price = await getPrice();
setNickname(client, bots.priceDEX, price);
eventBus.on(drip.update, async () => {
const price = await getPrice();
setNickname(client, bots.priceDEX, price); //update price in config file
});
});
client.login(process.env.DISCORD_PRICE_DEX);
This is the sample of changing bot's nickname for every guild that bot joined
client.guilds.cache.forEach((guild) => { //This is to get all guild that the bot joined
const nickname = args.slice(0).join(" ") //You wanted to change nickname
guild.me.setNickname(nickname); //setting the nickname of your bot
});
I believe you're doing it wrong.
Docs: https://discord.js.org/#/docs/discord.js/stable/class/GuildMember?scrollTo=setNickname
I would suggest using this module code:
const { guildId } = require('../config');
module.exports = (client, nickname) => {
client.guilds.cache
.get(guildId).me.setNickname(nickname);
};
And use it in this way in your main bot code: setNickname(client, price)
Edit:
Oh wait, I just realised you didn't use the correct intents (guild members), so you definitely need to use guild.me (as written above by me) or use guild.members.fetch() as it fetches members which aren't cached.
More info: https://discord.js.org/#/docs/discord.js/stable/class/GuildMemberManager?scrollTo=fetch
I can't understand why doesn't send the welcome message
Here's Code from index.js
client.on('guildMemberAdd', (member) => {
let chx = db.get(`welchannel_${member.guild.id}`);
if (chx === null) {
return;
}
client.channels.cache.get(chx).send(`Welcome to ${message.guild.name}`);
});
Here's Code From channel.js
module.exports = {
name: "channel",
description: "Help Command",
category: "Help",
execute(client, message, args, Discord) {
const db = require("quick.db")
let channel = message.mentions.channels.first() //mentioned channel
if(!channel) { //if channel is not mentioned
return message.channel.send("Please Mention the channel first")
}
db.set(`welchannel_${message.guild.id}`, channel.id)
const embed = new Discord.MessageEmbed()
.setColor('#b5b5b5')
.setTitle(`Channel set: ${channel.name} `)
message.channel.send({ embeds: [embed] });
}
}
EDIT: I found out the problem i didn't have a intent flag GUILD_MEMBERS
and also thanks UltraX that helped also
Basically, the reason is simple, you need to go to your dev portal then after choosing your bot/application just go to bot and you need to enable member intents Server Member Intent after that it should work, if it didn't just give it a 10 minute, then try again!
The best way to ensure you get a channel object within the event is to use the guild property off the emitted member.
client.on("guildMemberAdd", (member) => {
const { guild } = member;
let chx = db.get(`welchannel_${member.guild.id}`);
if(chx === null) {return}
const channel = guild.channels.cache.get(chx);
if (!channel) return;
channel.send(`Welcome to ${message.guild.name}`)
.catch(console.error);
})
You will need the Guild Member's intent enabled as stated in This Answer for the event to emit.
So I don't wanna make a mess out of my Main.js so I try to make every possible command through module.exports in other documents.js
Basically I need that if I send a command, the bot will delete my message and post a comment+embed on a specific channel.
This is what I have (making it simple):
module.exports = {
name: 'chtest',
execute(message, args, Discord) {
let chComment = 'Normal comment';
chComment += '\nLine2';
message.channel.send(chComment)
const chEmbed = blablaEmbedCode
message.channel.send(chEmbed)
message.delete();
},s
};
I've read another Questions and they use
client.channels.cache.get(`Channel_ID`).send('Text')
I tried using it but I got an error ReferenceError: client is not defined
I added Client to my execute line:
execute(client, message, args, Discord) {
And now I have another error TypeError: Cannot read property 'cache' of undefined
And... I don't know what to do now. Any solutions?
Thank you in advance.
Try this using the Message class' client property. Here are the docs for it.
module.exports = {
name: 'chtest',
execute(message, args, Discord) {
let channel = message.client.channels.cache.get('CHANNEL_ID');
//channel is now the channel, unless it could not be found.
channel.send('Message');
/*let chComment = 'Normal comment';
chComment += '\nLine2';
message.channel.send(chComment)
const chEmbed = blablaEmbedCode
message.channel.send(chEmbed)
message.delete();*/
},
};
I want to add few moderation commands to the bot, but I get stuck with "mute" command:
module.exports = {
name: 'mute',
description: 'command to mute members',
execute(message, args){
if(message.member.roles.cache.some(r => r.name === "Siren")){
const role = message.guild.roles.cache.find(r => r.name === "Muted");
const user = message.mentions.members.first().id;
user.roles.add(role);
}
}
}
I keep getting error:
TypeError: Cannot read property 'add' of undefined
I've been reading various guides and going through documentation and I keep failing on finding where I have made a mistake or what even causes this error.
At the first you try add role to member id, not a member. If no members mention in message, you will get empty mention collection and try get id of undefined, because message.mentions.members.first() of empty collection return undefined.
Second, try not use role names, use role ID for this, its more secure. And change your if code from if (statment) then do something to if (!statment) return reject reason this will help avoid unnecessary nesting of code.
module.exports = {
name: 'mute',
description: 'command to mute members',
execute(message, args){
if(!message.member.roles.cache.has('2132132131213')) return message.reply('You can`t use mute command')
const role = message.guild.roles.cache.get('21321321312');
if (!role) return message.reply('can`t get a role')
const member = message.mentions.members.first()
if (!member) return message.reply('Pls mention a member')
member.roles.add(role).then(newMember => {
message.channel.send(`successfully muted member ${member.user}`)
})
}
}
Ok, so I just started working on a discord bot and implemented a command handler, and I immediately ran into some problems.
const Discord = require("discord.js");
module.exports = {
name: "kick",
description: "Kicks the mentioned user",
execute(message, args) {
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
try {
const kickEmbed = new Discord.RichEmbed()
.setTitle("You were Kicked")
.setDescription("You were kicked from Bot Testing Server.");
user.send({ kickEmbed }).then(() => {
member.kick();
});
} catch (err) {
console.log("failed to kick user");
}
}
}
};
when i execute the kick command in my server, I get the following error
UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send an empty message
I can't seem to find anything wrong with the code so, where's the error
When sending an embed that uses the Discord Rich Embed builder you don't need to use the curly brackets.
Instead of user.send({ kickEmbed }) you should do user.send(kickEmbed). I ran into that issue before and it helped in my case.