Cannot read properties of undefined (reading 'length') unhandledRejection - javascript

My code error is:
module.exports = {
name: "gerenciar",
run: async(client, message, args,) => {
const embederro = new Discord.MessageEmbed()
.setTitle(`Erro - Permissão`)
.setDescription(`Você não tem permissão para isto!`)
.setColor(config.cor)
.setFooter({text:`${config.nomebot} - Todos os direitos reservados.`})
if (!message.member.permissions.has("ADMINISTRATOR")) return message.channel.send({ embeds: [embederro] })
if(db.all().length == 0) return message.reply(`❌ | **Você não tem nenhum produto criado!**`).then(msg => setTimeout(() => msg.delete().catch(err => console.log(err)), 5000));
if(!args[0]) return message.reply(`❌ | **Você não selecionou nenhum ID do produto!**`).then(msg => setTimeout(() => msg.delete().catch(err => console.log(err)), 5000));
const adb = args[0];
const row = new Discord.MessageActionRow()
.addComponents(
new Discord.MessageButton()
.setCustomId('nomegerenciar')
.setLabel('Nome')
.setEmoji('<:name:1076148740362092645>')
.setStyle('PRIMARY'),
)
.addComponents(
new Discord.MessageButton()
.setCustomId('precogerenciar')
.setLabel('Valor')
.setEmoji('<:sifras:1075060973074927756>')
.setStyle('PRIMARY'),
)
.addComponents(
new Discord.MessageButton()
.setCustomId('descgerenciar')
.setLabel('Descrição')
.setEmoji('<:config:1076148742912221245>')
.setStyle('PRIMARY'),
)
.addComponents(
new Discord.MessageButton()
.setCustomId('estoquegerenciar')
.setLabel('Estoque')
.setEmoji('<:pasta:1075834358973350008>')
.setStyle('PRIMARY'),
)
.addComponents(
new Discord.MessageButton()
.setCustomId('deletegerenciar')
.setLabel('Deletar')
.setEmoji('<:lixeira:1076148748205441024>')
.setStyle('DANGER'),
);
const msg = await message.reply({ embeds: [new Discord.MessageEmbed()
.setTitle(`${dbB.get(`nomebot`)} | Produto`)
.setDescription(`\`\`\`${db.get(`${args[0]}.desc`)}\`\`\`\n✨ | **Nome:** **__${db.get(`${args[0]}.nome`)}__**\n💳 | **Preço:** **__R$${db.get(`${args[0]}.preco`)}__**\n🛒 | **Estoque:** **__${db.get(`${args[0]}.conta`).length}__**`)
.setColor(`${dbB.get(`cor`)}`)
.setFooter({text:"Para comprar clique no botão abaixo."})
.setImage(`${dbB.get(`imagem`)}`)], components: [row]})
const interação = msg.createMessageComponentCollector({ componentType: "BUTTON", })
interação.on("collect", async (interaction) => {
if (message.author.id != interaction.user.id) {
return;
}
I'm using a sales system bot, and when I use the command "!gerenciar (product_name)" it gives this error, I would like you to tell me how to correct it and what is going wrong. Please help me, I'm new to js, I still don't understand some things

Related

TypeError: Cannot read properties of null (reading 'length') unhandledRejection

error:
TypeError: Cannot read properties of null (reading 'length') unhandledRejection
TypeError: Cannot read properties of null (reading 'length') unhandledRejection
my code erro
module.exports = {
name: "gerenciar",
run: async(client, message, args,) => {
const embederro = new Discord.MessageEmbed()
.setTitle(`Erro - Permissão`)
.setDescription(`Você não tem permissão para isto!`)
.setColor(config.cor)
.setFooter({text:`${config.nomebot} - Todos os direitos reservados.`})
if (!message.member.permissions.has("ADMINISTRATOR")) return message.channel.send({ embeds: [embederro] })
if(db.all().length == 0) return message.reply(`❌ | **Você não tem nenhum produto criado!**`).then(msg => setTimeout(() => msg.delete().catch(err => console.log(err)), 5000));
if(!args[0]) return message.reply(`❌ | **Você não selecionou nenhum ID do produto!**`).then(msg => setTimeout(() => msg.delete().catch(err => console.log(err)), 5000));
const adb = args[0];
const row = new Discord.MessageActionRow()
.addComponents(
new Discord.MessageButton()
.setCustomId('nomegerenciar')
.setLabel('Nome')
.setEmoji('<:name:1076148740362092645>')
.setStyle('PRIMARY'),
)
.addComponents(
new Discord.MessageButton()
.setCustomId('precogerenciar')
.setLabel('Valor')
.setEmoji('<:sifras:1075060973074927756>')
.setStyle('PRIMARY'),
)
.addComponents(
new Discord.MessageButton()
.setCustomId('descgerenciar')
.setLabel('Descrição')
.setEmoji('<:config:1076148742912221245>')
.setStyle('PRIMARY'),
)
.addComponents(
new Discord.MessageButton()
.setCustomId('estoquegerenciar')
.setLabel('Estoque')
.setEmoji('<:pasta:1075834358973350008>')
.setStyle('PRIMARY'),
)
.addComponents(
new Discord.MessageButton()
.setCustomId('deletegerenciar')
.setLabel('Deletar')
.setEmoji('<:lixeira:1076148748205441024>')
.setStyle('DANGER'),
);
const msg = await message.reply({ embeds: [new Discord.MessageEmbed()
.setTitle(`${dbB.get(`nomebot`)} | Produto`)
.setDescription(`\`\`\`${db.get(`${args[0]}.desc`)}\`\`\`\n✨ | **Nome:** **__${db.get(`${args[0]}.nome`)}__**\n💳 | **Preço:** **__R$${db.get(`${args[0]}.preco`)}__**\n🛒 | **Estoque:** **__${db.get(`${args[0]}.conta`).length}__**`)
.setColor(`${dbB.get(`cor`)}`)
.setFooter({text:"Para comprar clique no botão abaixo."})
.setImage(`${dbB.get(`imagem`)}`)], components: [row]})
const interação = msg.createMessageComponentCollector({ componentType: "BUTTON", })
interação.on("collect", async (interaction) => {
if (message.author.id != interaction.user.id) {
return;
}
I'm trying to send a command to manage, in a sales bot, but it gives this error.
someone help me fix it please

Interaction Channel MessageCollector, Discord.js

I'm trying to make a interaction based questionnaire, the user gets a DM with a button, by clicking the button, the user starts a message collector and the bot asks questions, however, the message collector seems to be setup wrong, it fails to read.
I haven't worked with interactions much, so I stick to classic commands, I'm trying to read the interaction channel and start a message collector in the DM, I hope I explained everything, any questions please ask.
Error:
Cannot read properties of null (reading 'createMessageCollector')
Code:
// Main requirements
const { CHANNEL_SSU, CHANNEL_ROLESEL, BOT_PREFIX, ROLE_DEV } = require('../../config.json')
const commandName = 'gba'
// Optional Requirements
const { MessageEmbed, MessageActionRow, MessageButton, MessageCollector } = require('discord.js')
// Main Code
module.exports = client => {
client.on('messageCreate', async message => {
if (message.author.bot) return;
if (!message.content.toLowerCase().startsWith(BOT_PREFIX)) return;
const command = message.content.split(' ')
const args = message.content.substring(1).split(' ')
if (command.toString().toLowerCase().replace(BOT_PREFIX, '').startsWith(commandName)) {
if (!message.member.roles.cache.has(ROLE_DEV)) return message.reply("Only Developers can use this command!")
const buttonsRow1 = new MessageActionRow().addComponents(
new MessageButton()
.setCustomId('GBAempty1')
.setLabel(' ')
.setStyle('SECONDARY')
.setDisabled(true),
new MessageButton()
.setCustomId('GBA')
.setLabel('Appeal')
.setStyle('DANGER')
.setDisabled(false),
new MessageButton()
.setCustomId('GBAempty2')
.setLabel(' ')
.setStyle('SECONDARY')
.setDisabled(true)
)
const GBAEmbed = new MessageEmbed()
.setTitle('Appeal Your Game Ban!')
.setColor('DARK_BLUE')
// .addFields(
// {name: 'Goal:', value: 'Help with development of the **System Bot**.'},
// {name: "Notice:", value: `If you're found **Inactive**, you **will** be removed.`}
// )
.setFooter({ text: 'ASRP | System Bot' })
.setThumbnail(message.guild.iconURL({ dynamic: true, size: 512 }))
message.delete()
message.channel.send({ embeds: [GBAEmbed], components: [buttonsRow1] })
}
})
client.on(`interactionCreate`, async (interaction) => {
if (!interaction.isButton) return
if (interaction.customId == 'GBA') {
await interaction.deferReply({
ephemeral: true
})
const appealEmbed = new MessageEmbed()
.setTitle(`Started Appeal.`)
.setDescription(`Please check your DM for the appeal.`)
// .addFields(
// {name: 'User', value: `${interaction.user} \`(${interaction.user.id})\``},
// {name: 'Action:', value: `\`\`\`${actionDone}\`\`\``}
// )
.setFooter({ text: 'ASRP | System Bot' })
.setTimestamp()
.setColor('ORANGE')
await interaction.editReply({ embeds: [appealEmbed], ephemeral: true })
let user = client.users.cache.get(interaction.member.user.id);
const buttonsRow2 = new MessageActionRow().addComponents(
new MessageButton()
.setCustomId('GBAempty3')
.setLabel(' ')
.setStyle('SECONDARY')
.setDisabled(true),
new MessageButton()
.setCustomId('GBAStart')
.setLabel('Appeal')
.setStyle('DANGER')
.setDisabled(false),
new MessageButton()
.setCustomId('GBAempty4')
.setLabel(' ')
.setStyle('SECONDARY')
.setDisabled(true)
)
const GBAstart = new MessageEmbed()
.setTitle(`Start Appeal.`)
.setDescription(`Press 'Start' to start appealing your game ban.`)
.setFooter({ text: 'ASRP | System Bot' })
.setThumbnail(interaction.guild.iconURL({ dynamic: true, size: 512 }))
user.send({ embeds: [GBAstart], components: [buttonsRow2] })
}
if (interaction.customId == 'GBAStart') {
await interaction.deferReply({
ephemeral: true
})
const questions = [
"How old are you?",
"How are you?",
"What time is for you?"
]
let counter = 0
const filter = m => m.author.id === message.author.id
const collector = await interaction.channel.createMessageCollector({ filter, time: 1000 * 1200, max: 3, min: 3 });
await interaction.channel.send(questions[counter++])
collector.on('collect', (m) => {
if (counter < questions.length) {
m.reply(questions[counter++])
}
if (counter == questions.length + 1) {
collector.stop()
}
})
collector.on('end', collected => {
console.log(`Collected ${collected.size} messages`)
if (collected.size < questions.length) {
interaction.channel.send('You didn\'t answer in time, please restart the appeal.')
return
}
let counter = 0
collected.forEach((value) => {
console.log(questions[counter++], value.content)
})
});
}
})
}
Extra Information:
Node Version: 'v16.14.2'
NPM Version: '8.5.0'
Discord.js Version: '^13.7.0'
Thank you in advance.

Cannot read properties of undefined (reading 'permissions'). | Discord.js v13

I'm making a command called role info in slash command!
And came the error called: Cannot read properties of undefined (reading 'permissions').
const { MessageEmbed, MessageActionRow, MessageButton } = require("discord.js");
const moment = require("moment");
moment.locale("pt-BR");
module.exports = {
name: "role",
description: "「🙋│ Utilidades」 Obtenha informações de um cargo",
options: [
{
name: 'info',
description: "「🙋│ Utilidades」 Obtenha informações de um cargo",
type: "SUB_COMMAND",
options: [
{
name: "role",
type: "ROLE",
description: "O cargo que você deseja obter as informações!",
required: true,
}]
},
],
run: async (client, interaction, args) => {
const role = interaction.guild.roles.cache.get(args[0]);
const permissions = {
"ADMINISTRATOR": "Administrador",
"VIEW_AUDIT_LOG": "Ver Registro de Auditoria",
"VIEW_GUILD_INSIGHTS": "Exibir insights do servidor",
"MANAGE_GUILD": "Gerenciar Servidor",
"MANAGE_ROLES": "Gerenciar Cargos",
"MANAGE_CHANNELS": "Gerenciar Canais",
"KICK_MEMBERS": "Expulsar Membros",
"BAN_MEMBERS": "Banir Membros",
"CREATE_INSTANT_INVITE": "Criar convite",
"CHANGE_NICKNAME": "Mudar apelido",
"MANAGE_NICKNAMES": "Gerenciar apelidos",
"MANAGE_EMOJIS": "Gerenciar Emojis",
"MANAGE_WEBHOOKS": "Gerenciar webhooks",
"VIEW_CHANNEL": "Ler canais de texto e ver canais de voz",
"SEND_MESSAGES": "Enviar mensagens",
"SEND_TTS_MESSAGES": "Enviar mensagens TTS",
"MANAGE_MESSAGES": "Gerenciar mensagens",
"EMBED_LINKS": "Embed Links",
"ATTACH_FILES": "Anexar arquivos",
"READ_MESSAGE_HISTORY": "Leia o histórico da mensagem",
"MENTION_EVERYONE": "Mencione #everyone, #here e Todos os cargos",
"USE_EXTERNAL_EMOJIS": "Usar Emojis Externos",
"ADD_REACTIONS": "Adicionar Reações",
"CONNECT": "Conectar",
"SPEAK": "Falar",
"STREAM": "Video",
"MUTE_MEMBERS": "Mutar Membros",
"DEAFEN_MEMBERS": "Ensurdecer membros",
"MOVE_MEMBERS": "Mover membros",
"USE_VAD": "Usar atividade de voz",
"PRIORITY_SPEAKER": "Orador prioritário"
}
const yesno = {
true: '`Sim`',
false: '`Não`'
}
const rolePermissions = role.permissions.toArray();
const finalPermissions = [];
for (const permission in permissions) {
if (rolePermissions.includes(permission)) finalPermissions.push(`${client.emoji.success} ${permissions[permission]}`);
else finalPermissions.push(`${client.emoji.fail} ${permissions[permission]}`);
}
const position = `\`${interaction.guild.roles.cache.size - role.position}°\``;
const embed = new MessageEmbed()
.setTitle(`${role.name}`)
.addField(`${client.emoji.id} ID`, `\`${role.id}\``, true)
.addField(`${client.emoji.trophy} Posição`, `${position}`, true)
.addField(`${client.emoji.ping} Mencionável`, yesno[role.mentionable], true)
.addField(`${client.emoji.bot} Cargo de bot`, yesno[role.managed], true)
.addField(`${client.emoji.on} Visível`, yesno[role.hoist], true)
.addField(`${client.emoji.rcolor} Cor`, `\`${role.hexColor.toUpperCase()}\``, true)
.addField(`${client.emoji.calendar} Data de criação`, `${moment(role.createdAt).format('LLL')}(${moment(role.createdAt).startOf('day').fromNow()})`, true)
.setColor(`${role.hexColor.toUpperCase()}`)
const row = new MessageActionRow()
.addComponents(
new MessageButton()
.setLabel(`Permissões`)
.setEmoji(`${client.emoji.perms}`)
.setCustomId('perms') .setStyle('SECONDARY')
);
const m = await interaction.followUp({ embeds: [embed], components: [row] })
const iFilter = i => i.user.id === interaction.user.id;
const collector = m.createMessageComponentCollector({ filter: iFilter, time: 10 * 60000 });
collector.on('collect', async(i) => {
switch (i.customId) { //começo da mensagem
case `perms`:
i.reply({
embeds: [
new MessageEmbed()
.setTitle(`${client.emoji.perms} Permissões`)
.setDescription(`${finalPermissions.join('\n')}
`)
.setColor(`${role.hexColor.toUpperCase()}`)
],
ephemeral: true })
}
}) //Final da mensagem
}
}
Since before, the command was working, but I changed it to the second bot and then it gave the error!
If anyone knows, tell me the error, I would be very grateful!
TypeError: Cannot read properties of undefine
d (reading 'permissions')
at Object.run (/home/runner//Slash/Info/roleinfo.js:66:38)
at Client. (/home/runner//events/interactionCreate:24:13
InteractionCreate.js
const client = require("../index");
client.on("interactionCreate", async (interaction) => {
// Slash Command Handling
if (interaction.isCommand()) {
await interaction.deferReply({ ephemeral: false }).catch(() => {});
const cmd = client.slash.get(interaction.commandName);
if (!cmd)
return interaction.followUp({ content: "An error has occured " });
const args = [];
for (let option of interaction.options.data) {
if (option.type === "SUB_COMMAND") {
if (option.name) args.push(option.name);
option.options?.forEach((x) => {
if (x.value) args.push(x.value);
});
} else if (option.value) args.push(option.value);
}
interaction.member = interaction.guild.members.cache.get(interaction.user.id);
cmd.run(client, interaction, args);
}
// Context Menu Handling
if (interaction.isContextMenu()) {
// await interaction.deferReply({ ephemeral: true });
const command = client.slash.get(interaction.commandName);
if (command) command.run(client, interaction);
}
});
You aren't passing in the args parameter in your function execution. You can remove args and use <CommandInteraction>.options.getRole() to get the role argument. Now keeping that in mind we can go ahead and define role as that.
const role = interaction.options.getRole("role");

How to allow a member to only react once to the poll discord.js

Hello everyone
I have a /create-poll command that creates a poll, for this I use the buttons of discord.js v13, but the user can react as many times as he wants to the "Yes" or "No" I want him to only react 1 time, 1 member = 1 reaction .
i just disabled the button when any user press it.
at the moment this is my code:
collector.on("collect", async i => {
if(i.customId === "o1"){
await i.deferUpdate()
option_1 += 1;
row.components[0].setLabel(`Yes (${option_1})`);
row.components[0].setDisabled();
i.editReply( {components: [row] });
}
else if(i.customId === "o2"){
await i.deferUpdate()
option_2 += 1;
row.components[1].setLabel(`No (${option_2})`);
row.components[1].setDisabled();
i.editReply( {components: [row] });
}
})
(If you have any improvement for my code, I still accept it)
just create a role with no permissions with nothing just a role to identificate if the user vote or not.
this is the final code:
const { SlashCommandBuilder } = require("#discordjs/builders")
const { MessageEmbed } = require("discord.js")
const Discord = require("discord.js")
module.exports = {
data: new SlashCommandBuilder()
.setName("create-poll")
.setDescription("Crea una encuesta")
.addStringOption(option =>
option
.setName("encuesta")
.setDescription("Escriba la encuesta que desea hacer")
.setRequired(true)
)
.addNumberOption(option =>
option
.setName("tiempo")
.setDescription("Tiempo que durara la encuesta (minutos)")
.setRequired(true)
),
async run(client, interaction){
const minutos = interaction.options.getNumber("tiempo");
const texto = interaction.options.getString("encuesta");
const minutes = minutos * 1000 * 60;
let optionA = 0;
let optionB = 0;
const row = new Discord.MessageActionRow()
.addComponents(
new Discord.MessageButton()
.setCustomId("yes")
.setLabel(`Sí (${optionA})`)
.setEmoji("✅")
.setStyle("SUCCESS")
)
.addComponents(
new Discord.MessageButton()
.setCustomId("no")
.setLabel(`No (${optionB})`)
.setEmoji("❌")
.setStyle("DANGER")
)
if(interaction.member.roles.cache.has('role-id-admin'))
{
const embed = new Discord.MessageEmbed()
.setTitle("Nueva encuesta")
.setDescription(`**${texto}**`)
.setFooter(`${interaction.user.username} creo la encuesta`,`${interaction.user.avatarURL({ dynamic: true , size: 2048 , format: "png" })}`)
.setColor("BLUE")
interaction.reply({ embeds: [embed], components: [row] }).then(() => {
setTimeout(function() {
row.components[0].setLabel(`Sí (${optionA})`);
row.components[0].setDisabled();
row.components[1].setLabel(`No (${optionB})`);
row.components[1].setDisabled();
optionA = 0;
optionB = 0;
interaction.editReply({ content: "La encuesta termino!", components: [row] });
interaction.guild.members.cache.forEach(member => {
member.roles.remove("role-id-vote");
});
}, minutes);
})
} else {
interaction.reply({ content: "No tienes permisos para usar este comando"})
}
client.on("interactionCreate", async(interaction) =>
{
if(interaction.isButton()){
/* Encuesta */
if(interaction.customId === "yes"){
if(!interaction.member.roles.cache.has('role-id-vote')){
optionA += 1;
row.components[0].setLabel(`Sí (${optionA})`);
row.components[1].setLabel(`No (${optionB})`);
interaction.member.roles.add('role-id-vote');
interaction.update({ components: [ row ] });
}
}
else if(interaction.customId === "no"){
if(!interaction.member.roles.cache.has('role-id-vote')){
optionB += 1;
row.components[0].setLabel(`Sí (${optionA})`);
row.components[1].setLabel(`No (${optionB})`);
interaction.member.roles.add('role-id-vote');
interaction.update({ components: [ row ] });
}
}
}
})
}
}
If this code works for you, use it: D

Javascript then error (await messages) discord

I want to create a command that create an announcement which is carried out in several stages. First, I type *annonce channelID then the bot asks me for the title, then the message (in theory)
Unfortunately, once *annonce channelID typed, the bot does not continue and writes this (it does the .catch)
Can you help me ?
Bot react :
Entre le titre de ton annonce :
title error
msg error
react error
const Discord = require('discord.js');
const delay = require('delay');
const NO = '❌';
const YES = '✅';
module.exports.run = async(bot, message, args) => {
const userN = message.member;
const msgFilter = m => m.author.id === message.author.id;
const userDepotAnnonce = message.author.username;
if(!message.member.hasPermission('ADMINISTRATOR')) {return message.channel.send("Vous ne pouvez pas passer d'annonces !");}
const channelID = args[0];
let sendchannel = bot.channels.get(channelID);
if(message.content !== `*annonce ${channelID}`) {return message.channel.send('Utilise ***annonce ``channelID``** puis valide');}
message.channel.send("Entre le titre de ton annonce :");
await delay(100);
message.channel.awaitMessages(msgFilter, { max: 1, time: 15000, errors: ['time'] })
.then(titleCollected => {
const msgTitle = titleCollected.first().content;
message.channel.send("Entrez le contenu de l'annonce et joint ton fichier :");
})
.catch(titleCollected => {
message.channel.send('*title error*');
console.log('Pas de titre');
})
message.channel.awaitMessages(msgFilter, { max: 1, time: 30000, errors: ['time'] })
.then(msgCollected => {
const messageToSend = msgCollected.first().content;
if(message.attachments.size > 0){
let attachment = message.attachments.first()
const url = attachment.url
var annonceFinal = new Discord.RichEmbed()
.setColor("03CD43")
.setTitle(`Nouvelle annonce : **${msgTitle}**`)
.setAuthor(userDepotAnnonce, message.author.avatarURL, url)
.addField('Annonce', messageToSend)
.addField('Lien', url)
.setFooter("Annonces by PDC")
}
else{
var annonceFinal = new Discord.RichEmbed()
.setColor("03CD43")
.setTitle(`Nouvelle annonce : **${msgTitle}**`)
.setAuthor(userDepotAnnonce, message.author.avatarURL)
.addField('Annonce', messageToSend)
.setFooter("annonces by pdc")
}
message.channel.send(`Vous vous désirez passer l'annonce **${msgTitle}** contenant **${messageToSend}** dans ${sendchannel}.\nPour confirmer, utilisez les reactions.` +YES +NO);
})
.catch(msgCollected => {
message.channel.send('*msg error*');
console.log('Pas de message');
})
const filter = (reaction, user) => {return ['✅', '❌'].includes(reaction.emoji.name) && user.id === message.author.id;};
message.react('✅').then(() => message.react('❌'));
message.awaitReactions(filter, { max: 1, time: 10000, errors: ['time'] })
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '✅'){
sendchannel.send(annonceFinal)
}
else if (reaction.emoji.name === '❌'){
message.channel.send('Alors arrête de me faire chier !');
}
})
.catch(collected => {
message.channel.send('*react error*');
console.log('*react error*');
})
};
module.exports.help = {
name: 'annonce'
};

Categories

Resources