ReferenceError: Cannot access ' ' before initialization - discord.js

My code;
const mentionMember = message.mentions.members.first();
let reason = args.slice(1).join(" ");
if (!reason) return message.channel.send(banEmbederrormessage);
banEmbederrormessage
let banEmbederrormessage = new discord.MessageEmbed()
.setColor(0xdb2727)
.setDescription(`
Bir hata oluştu.
**[KULLANIM]** +ban #mention sebep
`);
Terminal error;
(node:3248) UnhandledPromiseRejectionWarning: ReferenceError: Cannot access 'banEmbederrormessage' before initialization
at Object.run (C:\Users\gtaplus bot\commands\ban.js:13:50)
I am developing ban command. Terminal returns this error after using the ban command.

You need to place the definition first.
let banEmbederrormessage = new discord.MessageEmbed()
.setColor(0xdb2727)
.setDescription(`
Bir hata oluştu.
**[KULLANIM]** +ban #mention sebep
`);
const mentionMember = message.mentions.members.first();
let reason = args.slice(1).join(" ");
if (!reason) return message.channel.send(banEmbederrormessage);

Related

Cannot read properties of null (reading 'hasPermission') discord.js

I have coded a discord bot but i have a problem, when i execute my command it shows me a error.
Error:
if (!message.member.hasPermission("ADMINISTRATOR"))
TypeError: Cannot read properties of null (reading 'hasPermission')
Code where the error comes up:
if (command === "add") {
if (!message.member.hasPermission("ADMINISTRATOR"))
return message.reply("Desoler, vous ne pouvez pas effectuer cette commande car vous n'ette pas administrateur");
var fs = require("fs");
let messageArray = message.content.split(" ");
let args = messageArray.slice(1);
var account = args[0]
var service = args[1]
const filePath = __dirname + "/" + args[1] + ".txt";
fs.appendFile(filePath, os.EOL + args[0], function (err) {
if (err) return console.log(err);
message.channel.send("Terminer !")
});
I already tried to replace hasPermission with permissions.has but it still does not work.
Define your client like that
const { Client } = require('discord.js');
const client = new Client({ intents: 32767 });
Also make sure intents are enabled in the developer portal and use GuildMember#permissions.has

When using a variable inside an embed I get [object Object] returned not the value (discord.js)

I am attempting to create a kick command for a bot and its working fine however when the bot logs the embed it doesn't display the data in the variable but [object Object]
The Embed Output
My code is as following
exports.run = async (client, message, args) => {
const username = message.mentions.members.first().user.username; //gets the first mentioned users username
let member = message.mentions.members.first();
if(!member) return message.reply("Please mention a valid member of this server");
if(!member.kickable) return message.reply("I cannot kick this member!");
const reason = args.slice(1).join(' ');
const kickedmessage = new MessageEmbed() //embed to send to a logs channel
.setColor('#1773BA')
.setTitle('User Kicked')
.setDescription({username} + "had been kicked for " + {reason})
;
client.channels.cache.get("771835493305286688").send(kickedmessage)//output the embed
member.kick(reason);
I am using discord.js v12
exports.run = async (client, message, args) => {
const username = message.mentions.members.first().user.username; //gets the first mentioned users username
let member = message.mentions.members.first();
if (!member) return message.reply("Please mention a valid member of this server");
if (!member.kickable) return message.reply("I cannot kick this member!");
const reason = args.slice(1).join(" ");
const kickedmessage = new MessageEmbed() //embed to send to a logs channel
.setColor("#1773BA")
.setTitle("User Kicked")
.setDescription(username + "had been kicked for " + reason);
client.channels.cache.get("771835493305286688").send(kickedmessage); //output the embed
member.kick(reason);
};

send error message or without permission on the channel

My bot is having some problems with some servers, the problem is Missing Permissions, it happens when the bot tries to do a function that it does not have permission on the server, and to alert the users of the bot that it does not have permission to execute the command on the server, I put 2 functions so that it warns the member that it does not have enough permission, but it is not advancing because the bot does not send the message on the channel saying that it does not have permission
The first function where he tells the member that he is not allowed to create the invitation is
in if (!message.guild.member(bot.user).hasPermission('CREATE_INSTANT_INVITE')) { return message.channel.send('I am not allowed to create invitations.');}
And the second is
in } catch (e) { console.log(e) return message.reply(`The following error occurred :( \`${e.message}\` add the required permission \`MANAGE_INVITES\`.`);
const ms = require('parse-ms')
const { DiscordAPIError, MessageEmbed } = require("discord.js");
const { invalid } = require("moment");
module.exports = {
name: "jogar",
description: "Set the prefix of the guild!",
category: "economia",
run: async (bot, message, args) => {
if (!message.guild.member(bot.user).hasPermission('CREATE_INSTANT_INVITE')) { return message.channel.send('Eu não\ tenho permissão para fazer isso!');
}
const { chunk } = require('../../functionsss');
let guild = bot.guilds.cache.get("759003907858104350");
let emoji = guild.emojis.cache.find(emoji => emoji.name === 'loading');
let emoji2 = guild.emojis.cache.find(emoji => emoji.name === 'check');
if(!message.member.voice.channel) return message.reply(`Você precisa está conectado ao um canal de voz para procurar partida!`)
const voiceChannels = message.guild.channels.cache.filter(c => c.type === 'voice');
let count = 0;
const vo = message.member.voice.channel.members.size
for (const [id, voiceChannel] of voiceChannels) count += voiceChannel.members.size;
let membro = message.author;
let newInfo = args.join(' ');
if (!newInfo) return message.reply('Insira o codigo da sala do among! **a!jogar BCETYJ**');
if (newInfo.length > 6) return message.channel.send(`**Max \`6\` Caracteres permitidos!**`);
let newsInfo = chunk(newInfo, 42).join('\n');
let embed = new Discord.MessageEmbed();
try {
let channel = message.member.voice.channel;
channel.createInvite({
maxAge: 3600, // 0 = infinite expiration
maxUses: 10 // 0 = infinite uses
})
.then(invite=>{
embed
.setTitle(`${emoji} Procurando partida..`)
.setColor('RANDOM')
.setTimestamp()
.setDescription(`Pessoal <#${membro.id}> está procurando mais gente para jogar!
\n<:info:775212992895254548> **Informações:**
**・Canal:** ${channel}
**・Codigo:** ${newsInfo}
**・Jogadores:** ${vo}
\n[Entrar na partida](https://discord.gg/${invite.code})`)
.setThumbnail('https://attackofthefanboy.com/wp-content/uploads/2020/09/Among-Us-3.jpg')
message.channel.send(embed)
message.react("✅");
})
} catch (e) {
console.log(e)
return message.reply(`The following error occurred :( \`${e.message}\` add the required permission \`MANAGE_INVITES\`.`);
}}}```
I've had this problem before and I spent hours troubleshooting. I eventually figured out that it was the way that I was looking for permissions. Discord.js v12 has added many changes to this type of function. I suggest changing
(!message.guild.member(bot.user).hasPermission('CREATE_INSTANT_INVITE'))
to
(!message.guild.me.hasPermission("Create_Instant_Invite"){
//rest of your code
}

DiscordJS Argument Slice

I want to make a image embed via arguments, but I can't set the Title of the embed.
But when I try to run the comand, it errors out and the embed won't appear
if(message.content.startsWith(prefix + "foto-annuncio"))
{
if(!message.member.hasPermission(["MANAGE_MESSAGES"]))
{
/* error message pops out */
}
let argsresult;
let mChannel = message.mentions.channels.first()
message.delete()
argsresult = args.slice(1).join(" ")
let url = args.slice(1).join(" ");
let title = args.slice(2);
message.delete();
const embed = new Discord.RichEmbed ()
.setImage(url)
.setColor('#008000')
.setAuthor('Delta Logistics', 'https://cdn.discordapp.com/attachments/604963851561336832/665504827044003860/zoom_delta_6_discord.png')
.setTitle(title)
mChannel.send(embed).catch(err => console.log(err));
message.channel.send("Done!");
}
As Giuuliopime said you can't set an array as a title, you prob meant to join the arguments:
const title = args.slice(2).join(" ");

Bot Crashed When you dont mention

I have this command on my bot where you can mute someone using the command g!mute where the 'user' is mentioned using #. However, if you don't mention e.g GeoGeo instead of #GeoGeo, it causes the bot to crash. I know you need to put .catch(console.error); somewhere, but I'm not sure where. Thanks in advance. The Error is
let person = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[1]))
^
TypeError: message.guild.members.get is not a function
Code:
const Discord = require('discord.js');
const ms = require('ms');
module.exports = {
name: 'mute',
description: "this is mute command",
execute(message, args){
if(!message.member.roles.cache.find(r => r.name ==="Staff", "Head Staff", "Owner", "Co-Owner")) return message.channel.send(`YOU DO NOT HAVE PERMISSION TO DO THAT`)
let members = args[0];
if(!members) return message.reply("g!mute <user> <time>")
let person = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[1]))
if(!person) return message.reply("That person is not in the server!");
let mainrole = message.guild.roles.cache.find(role => role.name === "Fans");
let muterole = message.guild.roles.cache.find(role => role.name === "muted");
if(!muterole) return message.reply("That role does not exist");
let time = args[1];
if(!time){
return message.reply("g!mute <user> <time>");
}
person.roles.remove(mainrole.id);
person.roles.add(muterole.id);
const embed = new Discord.MessageEmbed()
.setTitle ("Muted:")
.setDescription (`${person.user.tag} has now been muted for ${ms(ms(time))}`)
.setColor(0x01B8FF)
message.channel.send(embed);
setTimeout(function(){
person.roles.add(mainrole.id)
person.roles.remove(muterole.id)
const embed = new Discord.MessageEmbed()
.setTitle ("Muted:")
.setDescription (`${person.user.tag} has been unmuted`)
.setColor(0x01B8FF)
message.channel.send(embed);
}, ms(time));
}
}
When faced with an error like: TypeError: message.guild.members.get is not a function
The logical thing to do is check the docs to see that message.guild.members really has a function named get. Here's the docs: https://discord.js.org/#docs/main/stable/class/GuildMemberManager
No get. But there is a cache like you use elsewhere in the code. Just by checking over the docs you can tell that your existing code is wrong (it's outdated) and you need to use cache like you do elsewhere in your code:
message.guild.members.cache.get(args[1])

Resources