TypeError: Cannot read properties of undefined (reading 'GUILDS') - discord

I have looked over all over and I know there are similar threads here but I can't seam to figure it out. I have made a discord bot but it has problem with guilds and get the error in name.
const { Client, GatewayIntentBits, Collection, MessageEmbed } = require('discord.js');
const { getVoiceConnection } = require("#discordjs/voice");
const client = new Client(clientSettingsObject());
client.deploySlash = {
enabled: true,
guild: false,
}
client.config = require("./config/config.json");
client.commands = new Collection();
client.slashCommands = new Collection();
client.queues = new Collection();
require("./util/musicUtils.js")(client);
require("./util/handler.js")(client);
client.login(client.config.token);
function clientSettingsObject() {
return {
shards: "auto",
allowedMentions: {
parse: ["roles", "users", "everyone" ],
repliedUser: false,
},
failIfNotExists: false,
partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
GatewayIntentBits: [
GatewayIntentBits.FLAGS.GUILDS,
GatewayIntentBits.FLAGS.GUILD_MESSAGES,
GatewayIntentBits.FLAGS.GUILD_VOICE_STATES
]
}
}
I would expect it to work but have no clue, sorry for inconvenience but I am new to programing and is trying to learn, would be much appreciated

Related

how to fix cannot read properties of undefined (reading 'push') in mongodb with djs

const { Client, CommandInteraction, EmbedBuilder, Permissions, ApplicationCommandType } = require("discord.js");
const { Formatters } = require('discord.js');
const blacklistedWords = require("../../Collection/index.js");
const Schema = require('../../models/blacklist.js')
module.exports = {
name: "blacklist_add",
description: "add a word to blacklist so that the members of the server cannot use the word",
userPerms: ['Administrator'],
type: ApplicationCommandType.ChatInput,
options: [{
name: 'word',
description: 'word to be added to the blacklist',
type: 3,
required: true
}],
/**
*
* #param {Client} client
* #param {CommandInteraction} interaction
* #param {String[]} args
*/
run: async (client, interaction, args) => {
const sword = interaction.options.getString('word');
console.log(sword)
const word = sword.toLowerCase();
const guild = { Guild: interaction.guild.id }
Schema.findOne(guild, async(err, data) => {
if(data) {
if(data.Words.includes(word)) return interaction.followUp(`The word already exists in the blacklist did you mean to remove it if so please use /blacklist-remove ${word} to remove the word from blacklist`)
data.Words.push(word)
data.save();
blacklistedWords.get(interaction.guild.id).push(word);
}else {
new Schema({
Guild: interaction.guild.id,
Words: word
}).save();
blacklistedWords.set(interaction.guild.id, [ word ])
}
const embed = new EmbedBuilder()
.setTitle('<:donetick:951395881607893062> Blacklist system')
.setColor('GREEN')
.setDescription('Word added- A new word has been added to the blacklist')
.addField('Word', `${word}`, false)
.addField('How do I remove the word from the blacklist?', `/blacklist-remove ${word}`, false)
interaction.reply({ embeds: [embed] })
});
},
};
this is the code but it used to work with djs v13 idk now why is it giving this error
the error image in console
can you please help I am new to djs v14 so I think that is an error caused by upgrading to v14 correct me if wrong

DiscordJS Roles Won't Add

const { SlashCommandBuilder } = require("#discordjs/builders");
const { Permissions } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("mute")
.setDescription("Mute a user on the server")
.addUserOption((option) =>
option
.setName("user")
.setDescription("The user you want to mute")
.setRequired(true)
),
execute: async (interaction) => {
const user = interaction.options.getUser("user");
if (!interaction.member.permissions.has(Permissions.FLAGS.MANAGE_ROLES)) {
return interaction.editReply({
content: `:x: | Manage Roles Permission is required to perform that action!`,
ephemeral: true,
});
}
user.roles.add(member.guild.roles.cache.get("958443243836702859"));
return interaction.editReply("Muted!")
},
};
TypeError: Cannot read properties of undefined (reading 'add')
It won't let me add a roles to a user please help!
You are calling user.roles.add() in the middle of the hash definition of module_exports.
Read through your code again. It's a syntax error.
The issue stems from this, roles is an element of a member which is the parent of a user. user does not contain the element of roles. The code was trying to add roles to a user rather than a member.
This will help you out.
const { SlashCommandBuilder } = require("#discordjs/builders");
const { Permissions } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("mute")
.setDescription("Mute a user on the server")
.addUserOption((option) =>
option
.setName("user")
.setDescription("The user you want to mute")
.setRequired(true)
),
execute: async (interaction) => {
const user = interaction.options.getUser("user");
if (!interaction.member.permissions.has(Permissions.FLAGS.MANAGE_ROLES)) {
return interaction.editReply({
content: `:x: | Manage Roles Permission is required to perform that action!`,
ephemeral: true,
});
}
//adding the below line
const member2mute = interaction.guild.members.cache.get(user.id)
//changing the below line
member2mute.roles.add("958443243836702859");
return interaction.editReply("Muted!")
},
};

DiscordAPIError: Cannot send an empty message (discord.js v13)

I am coding a bot with the below command and it throws an error, but i don't know where is the error
i tried my best
const Discord = require("discord.js");
const client = new Discord.Client({
allowedMentions: {
parse: ["roles", "users", "everyone"],
},
intents: [
Discord.Intents.FLAGS.GUILDS,
Discord.Intents.FLAGS.GUILD_MESSAGES,
Discord.Intents.FLAGS.DIRECT_MESSAGES
]
});
const config = require("../config.json");
module.exports = {
name: "quar",
run: async (client, message, args) => {
if (!message.member.permissions.has("ADMINISTRATOR")) return;
let role = message.guild.roles.cache.find(role => role.name === "Quarantined" || role.name === "Quarantine")
let member = message.mentions.members.first() || message.guild.members.cache.get(args[0])
let reason = message.content.split(" ").slice(2).join(" ")
if(!reason) reason = "No reason given."
if(!role) return message.channel.send("❌ This server doesn't have a quarantine role!")
if(!member) return message.channel.send("❌ You didn't mention a member!")
if(member.roles.cache.has(role.id)) return message.channel.send(`❌ That user already quarantined!`)
member.roles.add(role)
.then (() => {
const embed = new Discord.MessageEmbed()
.setTitle(`✅ ${member.user.tag} was quarantined!`)
.setColor("RANDOM")
.setTimestamp()
embed.setFooter(`Requested by ${message.author.username}`)
message.channel.send(embed)
member.send(`You were quarantined in \`${message.guild.name}\`. Reason: ${reason} `).catch(error => {
message.channel.send(`❌ Can't send DM to ${member.user.tag}!`);
});
})
}
}
If I have made a mistake, please help me out
Sorry I don't speak English well
Try the below code out, I made notes along the way to explain as well as improved a small bit of code. I assume this is a collection of 2 separate files which is why they are separated. If they aren't 2 separate files, you do not need the top section, just the bottom.
const {
Client,
Intents,
MessageEmbed
} = require("discord.js");
const client = new Client({
allowedMentions: {
parse: ["roles", "users", "everyone"],
},
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.DIRECT_MESSAGES
]
});
const config = require("../config.json");
const {
MessageEmbed,
Permissions
} = require("discord.js");
module.exports = {
name: "quar",
run: async (client, message, args) => {
if (!message.member.permissions.has(Permissions.FLAGS.ADMINISTRATOR)) return;
let role = message.guild.roles.cache.find(role => role.name === "Quarantined" || role.name === "Quarantine")
let member = message.mentions.members.first() || message.guild.members.cache.get(args[0])
let reason = message.content.split(" ").slice(2).join(" ")
if (!reason) reason = "No reason given."
if (!role) return message.channel.send("❌ This server doesn't have a quarantine role!")
if (!member) return message.channel.send("❌ You didn't mention a member!")
if (member.roles.cache.has(role.id)) return message.channel.send(`❌ That user already quarantined!`)
member.roles.add(role)
.then(() => {
const embed = new MessageEmbed()
.setTitle(`✅ ${member.user.tag} was quarantined!`)
.setColor("RANDOM")
.setTimestamp()
.setFooter({
text: `Requested by ${message.author.username}`
})
// author and footer are now structured like this
// .setAuthor({
// name: 'Some name',
// icon_url: 'https://i.imgur.com/AfFp7pu.png',
// url: 'https://discord.js.org',
// })
// .setFooter({
// text: 'Some footer text here',
// icon_url: 'https://i.imgur.com/AfFp7pu.png',
// })
message.channel.send({
embeds: [embed]
}) //embeds must be sent as an object and this was the actual line that was causing the error.
member.send(`You were quarantined in \`${message.guild.name}\`. Reason: ${reason} `).catch(() => { // if error is not used, it is not required to be stated
message.channel.send(`❌ Can't send DM to ${member.user.tag}!`);
});
})
}
}

TypeError: Cannot read property '0' of undefined (discord.js)

const data = suggestedEmbed.embeds[0];
Hi, I'm having this error and I don't know why it is saying that the code above is the problem. Any solutions for this problem? Thank you for reading.
Code:
module.exports = {
category: "Utility",
description: "Accept valid suggestions!",
expectedArgs: "<messageID> <Reason>",
minArgs: 2,
guildOnly: true,
ownerOnly: true,
callback: ({message, args}) => {
const messageID = args[0]
const acceptQuery = args.slice(1).join(" ");
try{
const suggestionChannel = message.guild.channels.cache.get('834459599699443782');
const suggestedEmbed = suggestionChannel.messages.fetch(messageID);
console.log(suggestedEmbed)
const data = suggestedEmbed.embeds[0];
const acceptEmbed = new Discord.MessageEmbed()
.setAuthor(data.author.name, data.author.iconURL())
.setColor('GREEN')
.setDescription(data.description)
.addField("📊 Status ✅ Accepted! Expect this coming soon!", acceptQuery);
suggestedEmbed.edit(acceptEmbed);
const user = client.users.cache.find((u) => u.tag === data.author.name);
user.send("Your suggestion has been accepted! Thank you for this suggestion, expect this coming soon!")
} catch(err) {
console.log(err)
}
}
}

discord.js-commando TypeError: RichEmbed is not a constructor

I want to send embed with discord.js-commando but when I send the command it says me this:
An error occurred while running the command: TypeError: RichEmbed is not a constructor
You shouldn't ever receive an error like this.
here is my code
const { Command } = require('discord.js-commando');
const { RichEmbed } = require('discord.js');
module.exports = class EmbedCommand extends Command {
constructor(client) {
super(client, {
name: 'embed',
group: 'util',
memberName: 'embed',
description: 'Embeds the text you provide.',
examples: ['embed Embeds are cool.'],
args: [
{
key: 'text',
prompt: 'What text would you like the bot to embed?',
type: 'string'
}
]
});
}
run(msg, args) {
const { text } = args;
const embed = new RichEmbed()
.setDescription(text)
.setAuthor(msg.author.username, msg.author.displayAvatarURL)
.setColor(0x00AE86)
.setTimestamp();
return msg.embed(embed);
}
};
If you’re using discord.js v12+ it’s Discord.MessageEmbed()
RichEmbed is called MessageEmbed in newest Versions. Renaming it should be fine.

Resources