interaction.member.fetch(); Triggers on other interaction commands - javascript

Hi my problem is if any user trigger a command or a button (a interaction), then it triggers this line: "await member.send('Du bist bereits auf YANKEEUNIT91 COMMUNITY verifiziert!');" in Code 1.
Example: A user trigger the button in Code 2, he get the DM message from the bot from code 1.
What makes code 1?
It's a verification system, you press the button choose in a select menu that you accept the rules then it open a Modal where you enter you server nickname, then you select in a other select menu a ping role.
You get the nickname the choosed role and the member role from the bot.
But if you already a member this line in code 1 triggers and send you the DM "if (interaction.member.roles.cache.has('707275842295955530')) {".
But for some reason the bot sends the DM even when other interactions are triggered.
Code 1:
const Discord = require('discord.js')
const Command = require('../../structures/CommandClass');
const { stripIndents } = require('common-tags');
const { SlashCommandBuilder, PermissionFlagsBits, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, TextInputStyle, StringSelectMenuBuilder, Events, ModalBuilder, TextInputBuilder } = require('discord.js');
let ninputvalues = {};
module.exports = class verifiy extends Command {
constructor(client) {
super(client, {
data: new SlashCommandBuilder()
.setName('sendverifizierung')
.setDescription('Sende das Verifizierungs Embed')
.setDefaultMemberPermissions(PermissionFlagsBits.BanMembers)
.setDMPermission(false),
});
}
async run(client, interaction) {
let member = await interaction.member.fetch();
const verifiychannelID = '1052951990331773019';
const verifiychannel = member.guild.channels.cache.get(verifiychannelID);
const glocke = interaction.guild.roles.cache.get('884820297977573386');
const news = interaction.guild.roles.cache.get('1032524990274351134');
const memberrole = interaction.guild.roles.cache.get('707275842295955530');
let failsafe = false;
const rulesmenü = new ActionRowBuilder()
.addComponents(
new StringSelectMenuBuilder()
.setCustomId('rulesmenü')
.setPlaceholder('Antwort auswählen')
.addOptions(
{
label: 'Ja, gelesen und einverstanden.',
value: 'ja',
},
{
label: 'Nein, nicht gelsesen und nicht einverstanden.',
value: 'nein',
},
),
);
const rolemenü = new ActionRowBuilder()
.addComponents(
new StringSelectMenuBuilder()
.setCustomId('rolemenü')
.setPlaceholder('Rolle auswählen')
.addOptions(
{
label: 'YU91 Glocke',
description: 'Erhalte extra Benachrichtigungen über Yankeeunit91.',
value: 'glocke',
},
{
label: 'Gaming News',
description: 'Erhalte extra Benachrichtigungen für Neue Infos über z.B Spiele etc.',
value: 'news',
},
{
label: 'Keine',
description: 'Erhalte keine Rolle.',
value: 'keine',
},
),
);
const modalsv = new ModalBuilder()
.setCustomId('ninput')
.setTitle('YANKEEUNIT91 COMMUNITY');
const nameinput = new TextInputBuilder()
.setCustomId('nameinput')
.setLabel("Server Nickname")
.setPlaceholder('Keine Sonderzeichen!')
.setStyle(TextInputStyle.Short)
.setMinLength(2)
.setMaxLength(32)
.setRequired(true);
const firstActionRowv = new ActionRowBuilder().addComponents(nameinput);
modalsv.addComponents(firstActionRowv);
const verifeembed = new EmbedBuilder()
.setTitle(`Verifizieren dich!`)
.setColor('#00ff0c')
.setDescription(stripIndents`Durch das verifizieren erhälst du zugriff auf die YANKEEUNIT91 COMMUNITY!`)
.setFooter({ text: 'YANKEEUNIT91 COMMUNITY'})
.setTimestamp();
const buttonva = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId('buttonanfrageverify')
.setEmoji('✅')
.setLabel('Verifizieren')
.setStyle(ButtonStyle.Success),
);
client.on('interactionCreate', async interaction => {
const member = await interaction.member.fetch();
if (interaction.member.roles.cache.has('707275842295955530')) {
await member.send('**Du bist bereits auf YANKEEUNIT91 COMMUNITY verifiziert!**');
return interaction.deferUpdate()
} else if (interaction.isButton()) {
const buttonID = interaction.customId
if (buttonID === 'buttonanfrageverify') {
await interaction.reply({ content:'**Hast du die Regeln gelesen, und bist du damit einverstanden?**', components: [rulesmenü], ephemeral: true });
}
}
});
client.on('interactionCreate', async interaction => {
if (interaction.isStringSelectMenu()) {
const selected = interaction.values.join(', ');
if (selected === 'ja') {
await interaction.showModal(modalsv);
} else if (selected === 'nein') {
await interaction.update({ content:'**Lese dir die Regeln erneut durch! Solltest du nicht mit denn Regeln einverstanden sein, bitten wir dich denn Server zu verlassen.**', components: [], ephemeral: true });
}
}
});
verifiychannel.send({ embeds: [verifeembed], components: [buttonva] });
await interaction.reply({ content: 'Verifizierungs Embed wurde versendet!', ephemeral: true });
client.on(Events.InteractionCreate, async (interaction) => {
if (interaction.isModalSubmit()) {
if (interaction.customId === "ninput") {
await interaction.update({ content:'**Wähle eine Role für die du dich interresierst!**', components: [rolemenü], ephemeral: true });
var ninputdata = interaction.fields.getTextInputValue('nameinput');
ninputvalues[interaction.user.id] = interaction.fields.getTextInputValue('nameinput');
ninputvalues[interaction.user.id] = ninputvalues[interaction.user.id].replace(/[^a-zA-Z0-9 ]/g, 'X');
}
} else if (interaction.isStringSelectMenu()) {
const selected = interaction.values[0];
const member = await interaction.member.fetch();
if (selected === 'glocke') {
await interaction.update({ content:'**Du hast die \`YU91 Glocke\` erhalten. Willkommen in der YANKEEUNIT91 COMMUNITY!**', components: [], ephemeral: true });
await member.roles.add(glocke)
await interaction.member.setNickname(`${ninputvalues[interaction.user.id]}`).catch(e => (failsafe = true));
return await member.roles.add(memberrole);
} else if (selected === 'news') {
await interaction.update({ content:'**Du hast die \`Gaming News\` erhalten. Willkommen in der YANKEEUNIT91 COMMUNITY!**', components: [], ephemeral: true });
await member.roles.add(news)
await interaction.member.setNickname(`${ninputvalues[interaction.user.id]}`).catch(e => (failsafe = true));
return await member.roles.add(memberrole);
} else if (selected === 'keine') {
await interaction.update({ content:'**Willkommen in der YANKEEUNIT91 COMMUNITY!**', components: [], ephemeral: true });
await interaction.member.setNickname(`${ninputvalues[interaction.user.id]}`).catch(e => (failsafe = true));
await member.roles.add(memberrole);
}
};
});
}
};
Code 2
const Discord = require('discord.js')
const Command = require('../../structures/CommandClass');
const { stripIndents } = require('common-tags');
const { SlashCommandBuilder, PermissionFlagsBits, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, TextInputStyle, StringSelectMenuBuilder, Events, ModalBuilder, TextInputBuilder } = require('discord.js');
let sinputvalues = {};
let ginputvalues = {};
let pfmenüvalues = {};
module.exports = class spielersuche extends Command {
constructor(client) {
super(client, {
data: new SlashCommandBuilder()
.setName('sendspielersuche')
.setDescription('Sende das Spielersuche Embed')
.setDefaultMemberPermissions(PermissionFlagsBits.BanMembers)
.setDMPermission(false),
});
}
async run(client, interaction) {
let member = await interaction.member.fetch();
const anfragechannelID = '889302458906591344';
const anfragechannel = member.guild.channels.cache.get(anfragechannelID);
const createanfragechannelID = '1052951990331773019';
const createanfragechannel = member.guild.channels.cache.get(createanfragechannelID);
const pfmenü = new ActionRowBuilder()
.addComponents(
new StringSelectMenuBuilder()
.setCustomId('pfmenü')
.setPlaceholder('Plattform auswählen (Scrollen)')
.addOptions(
{
label: 'PS4',
value: 'PS4',
},
{
label: 'PS5',
value: 'PS5',
},
{
label: 'PS4/PS5',
value: 'PS4/PS5',
},
{
label: 'PC',
value: 'PC',
},
{
label: 'Switch',
value: 'Switch',
},
{
label: 'Xbox One',
value: 'Xbox One',
},
{
label: 'Xbox Series',
value: 'Xbox Series',
},
{
label: 'Xbox One/Xbox Series',
value: 'Xbox One/Xbox Series',
},
{
label: 'Alle',
value: 'Alle',
},
),
);
const spmenü = new ActionRowBuilder()
.addComponents(
new StringSelectMenuBuilder()
.setCustomId('spmenü')
.setPlaceholder('Mitspieleranzahl auswählen (Scrollen)')
.addOptions(
{
label: '1',
value: '1 Mitspieler',
},
{
label: '2',
value: '2 Mitspieler',
},
{
label: '3',
value: '3 Mitspieler',
},
{
label: '4',
value: '4 Mitspieler',
},
{
label: '5',
value: '5 Mitspieler',
},
{
label: '6',
value: '6 Mitspieler',
},
{
label: '7',
value: '7 Mitspieler',
},
{
label: '8',
value: '8 Mitspieler',
},
{
label: '9+',
value: '9+ Mitspieler',
},
),
);
const modals = new ModalBuilder()
.setCustomId('minput')
.setTitle('Spielersuche 🔎');
const spielinput = new TextInputBuilder()
.setCustomId('spielinput')
.setLabel("Für welches Spiel?")
.setPlaceholder('GTA5, Fortnite, Call of Duty, Minecraft ...')
.setStyle(TextInputStyle.Short)
.setMinLength(2)
.setMaxLength(20)
.setRequired(true);
const grundinput = new TextInputBuilder()
.setCustomId('grundinput')
.setLabel("Der Grund der Anfrage?")
.setPlaceholder('Beispiel: Suche Spieler für Cayo Perico Heist.')
.setStyle(TextInputStyle.Short)
.setMinLength(10)
.setMaxLength(60)
.setRequired(true);
const firstActionRow = new ActionRowBuilder().addComponents(spielinput);
const secondActionRow = new ActionRowBuilder().addComponents(grundinput);
modals.addComponents(firstActionRow, secondActionRow);
const spielersucheerweitertEmbed = new EmbedBuilder()
.setTitle(`Spieler suchen Spieler 🔎`)
.setColor('#00ff0c')
.setDescription(stripIndents`Drücke auf denn Button um eine Spielersuche Anzufragen!`)
.setFooter({ text: 'YANKEEUNIT91 COMMUNITY'})
.setTimestamp();
const buttonsa = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId('buttonanfrage')
.setEmoji('🔎')
.setLabel('Spielersuche Anfragen')
.setStyle(ButtonStyle.Success),
);
client.on('interactionCreate', async interaction => {
if (interaction.isButton()) {
const buttonID = interaction.customId
if (buttonID === 'buttonanfrage') {
await interaction.showModal(modals);
}
}
});
createanfragechannel.send({ embeds: [spielersucheerweitertEmbed], components: [buttonsa] });
await interaction.reply({ content: 'Spielersuche Embed wurde versendet!', ephemeral: true });
client.on(Events.InteractionCreate, async (interaction) => {
if (interaction.isModalSubmit()) {
if (interaction.customId === "minput") {
await interaction.reply({ content:'**Wähle deine Plattform!**', components: [pfmenü], ephemeral: true });
var ginputdata = interaction.fields.getTextInputValue('grundinput');
ginputvalues[interaction.user.id] = interaction.fields.getTextInputValue('grundinput');
var sinputdata = interaction.fields.getTextInputValue('spielinput');
sinputvalues[interaction.user.id] = interaction.fields.getTextInputValue('spielinput');
}
} else if (interaction.isStringSelectMenu()) {
if (interaction.customId === "pfmenü") {
await interaction.update({ content:'**Wähle wie viele Mitpsieler gesucht werden!**', components: [spmenü], ephemeral: true });
var pfmenüdata = interaction.values.join(', ');
pfmenüvalues[interaction.user.id] = interaction.values.join(', ');
}
const spanzahl = await interaction.values.join(', ');
const spielersucheerweitertEmbedfertig = new EmbedBuilder()
.setTitle(`${ginputvalues[interaction.user.id]}`)
.setColor('#00ff0c')
.setFooter({ text: 'YANKEEUNIT91 COMMUNITY'})
.setTimestamp()
.addFields(
{
name: '**Spiel:**',
value: `${sinputvalues[interaction.user.id]}`,
inline: true,
},
{
name: `**Plattform:**`,
value: `${pfmenüvalues[interaction.user.id]}`,
inline: false,
},
{
name: `**Mitspieleranzahl gesucht:**`,
value: `${spanzahl}`,
inline: false,
},
);
if (interaction.customId === "spmenü") {
const member = await interaction.member.fetch();
await interaction.update({ content:'**Spielersuche erfolgreich Angefragt!**', components: [], ephemeral: true });
return await anfragechannel.send({ content: `**Anfrage von:** <#${member.id}>`, embeds: [spielersucheerweitertEmbedfertig] });
}
};
});
}
};
I didnt know why it is but i think form this line: "const member = await interaction.member.fetch();" in code 1, but i dont know how to fix that.

Hi Thanks #Tetie i Fixed it. I write all interactionCreate Events to one interactionCreate Event, replaced the const member = await interaction.member.fetch(); with interaction.member.
And i changed some on the syntax.
Code Befor:
const Command = require('../../structures/CommandClass');
const { stripIndents } = require('common-tags');
const { SlashCommandBuilder, PermissionFlagsBits, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, TextInputStyle, StringSelectMenuBuilder, Events, ModalBuilder, TextInputBuilder } = require('discord.js');
let ninputvalues = {};
module.exports = class verifiy extends Command {
constructor(client) {
super(client, {
data: new SlashCommandBuilder()
.setName('sendverifizierung')
.setDescription('Sende das Verifizierungs Embed')
.setDefaultMemberPermissions(PermissionFlagsBits.BanMembers)
.setDMPermission(false),
});
}
async run(client, interaction) {
let member = await interaction.member.fetch();
const verifiychannelID = '1052951990331773019';
const verifiychannel = member.guild.channels.cache.get(verifiychannelID);
const glocke = interaction.guild.roles.cache.get('884820297977573386');
const news = interaction.guild.roles.cache.get('1032524990274351134');
const memberrole = interaction.guild.roles.cache.get('707275842295955530');
let failsafe = false;
const rulesmenü = new ActionRowBuilder()
.addComponents(
new StringSelectMenuBuilder()
.setCustomId('rulesmenü')
.setPlaceholder('Antwort auswählen')
.addOptions(
{
label: 'Ja, gelesen und einverstanden.',
value: 'ja',
},
{
label: 'Nein, nicht gelsesen und nicht einverstanden.',
value: 'nein',
},
),
);
const rolemenü = new ActionRowBuilder()
.addComponents(
new StringSelectMenuBuilder()
.setCustomId('rolemenü')
.setPlaceholder('Rolle auswählen')
.addOptions(
{
label: 'YU91 Glocke',
description: 'Erhalte extra Benachrichtigungen über Yankeeunit91.',
value: 'glocke',
},
{
label: 'Gaming News',
description: 'Erhalte extra Benachrichtigungen für Neue Infos über z.B Spiele etc.',
value: 'news',
},
{
label: 'Keine',
description: 'Erhalte keine Rolle.',
value: 'keine',
},
),
);
const modalsv = new ModalBuilder()
.setCustomId('ninput')
.setTitle('YANKEEUNIT91 COMMUNITY');
const nameinput = new TextInputBuilder()
.setCustomId('nameinput')
.setLabel("Server Nickname")
.setPlaceholder('Keine Sonderzeichen!')
.setStyle(TextInputStyle.Short)
.setMinLength(2)
.setMaxLength(32)
.setRequired(true);
const firstActionRowv = new ActionRowBuilder().addComponents(nameinput);
modalsv.addComponents(firstActionRowv);
const verifeembed = new EmbedBuilder()
.setTitle(`Verifizieren dich!`)
.setColor('#00ff0c')
.setDescription(stripIndents`Durch das verifizieren erhälst du zugriff auf die YANKEEUNIT91 COMMUNITY!`)
.setFooter({ text: 'YANKEEUNIT91 COMMUNITY'})
.setTimestamp();
const buttonva = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId('buttonanfrageverify')
.setEmoji('✅')
.setLabel('Verifizieren')
.setStyle(ButtonStyle.Success),
);
client.on('interactionCreate', async interaction => {
const member = await interaction.member.fetch();
if (interaction.member.roles.cache.has('707275842295955530')) {
await member.send('**Du bist bereits auf YANKEEUNIT91 COMMUNITY verifiziert!**');
return interaction.deferUpdate()
} else if (interaction.isButton()) {
const buttonID = interaction.customId
if (buttonID === 'buttonanfrageverify') {
await interaction.reply({ content:'**Hast du die Regeln gelesen, und bist du damit einverstanden?**', components: [rulesmenü], ephemeral: true });
}
}
});
client.on('interactionCreate', async interaction => {
if (interaction.isStringSelectMenu()) {
const selected = interaction.values.join(', ');
if (selected === 'ja') {
await interaction.showModal(modalsv);
} else if (selected === 'nein') {
await interaction.update({ content:'**Lese dir die Regeln erneut durch! Solltest du nicht mit denn Regeln einverstanden sein, bitten wir dich denn Server zu verlassen.**', components: [], ephemeral: true });
}
}
});
verifiychannel.send({ embeds: [verifeembed], components: [buttonva] });
await interaction.reply({ content: 'Verifizierungs Embed wurde versendet!', ephemeral: true });
client.on(Events.InteractionCreate, async (interaction) => {
if (interaction.isModalSubmit()) {
if (interaction.customId === "ninput") {
await interaction.update({ content:'**Wähle eine Role für die du dich interresierst!**', components: [rolemenü], ephemeral: true });
var ninputdata = interaction.fields.getTextInputValue('nameinput');
ninputvalues[interaction.user.id] = interaction.fields.getTextInputValue('nameinput');
ninputvalues[interaction.user.id] = ninputvalues[interaction.user.id].replace(/[^a-zA-Z0-9 ]/g, 'X');
}
} else if (interaction.isStringSelectMenu()) {
const selected = interaction.values[0];
const member = await interaction.member.fetch();
if (selected === 'glocke') {
await interaction.update({ content:'**Du hast die \`YU91 Glocke\` erhalten. Willkommen in der YANKEEUNIT91 COMMUNITY!**', components: [], ephemeral: true });
await member.roles.add(glocke)
await interaction.member.setNickname(`${ninputvalues[interaction.user.id]}`).catch(e => (failsafe = true));
return await member.roles.add(memberrole);
} else if (selected === 'news') {
await interaction.update({ content:'**Du hast die \`Gaming News\` erhalten. Willkommen in der YANKEEUNIT91 COMMUNITY!**', components: [], ephemeral: true });
await member.roles.add(news)
await interaction.member.setNickname(`${ninputvalues[interaction.user.id]}`).catch(e => (failsafe = true));
return await member.roles.add(memberrole);
} else if (selected === 'keine') {
await interaction.update({ content:'**Willkommen in der YANKEEUNIT91 COMMUNITY!**', components: [], ephemeral: true });
await interaction.member.setNickname(`${ninputvalues[interaction.user.id]}`).catch(e => (failsafe = true));
await member.roles.add(memberrole);
}
};
});
}
};
After:
const Discord = require('discord.js')
const Command = require('../../structures/CommandClass');
const { stripIndents } = require('common-tags');
const { SlashCommandBuilder, PermissionFlagsBits, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, TextInputStyle, StringSelectMenuBuilder, Events, ModalBuilder, TextInputBuilder } = require('discord.js');
let ninputvalues = {};
module.exports = class verifiy extends Command {
constructor(client) {
super(client, {
data: new SlashCommandBuilder()
.setName('sendverifizierung')
.setDescription('Sende das Verifizierungs Embed')
.setDefaultMemberPermissions(PermissionFlagsBits.BanMembers)
.setDMPermission(false),
});
}
async run(client, interaction) {
const verifiychannelID = '644218169422250014';
const verifiychannel = interaction.guild.channels.cache.get(verifiychannelID);
const glocke = interaction.guild.roles.cache.get('884820297977573386');
const news = interaction.guild.roles.cache.get('1032524990274351134');
const memberrole = interaction.guild.roles.cache.get('707275842295955530');
let failsafe = false;
const rulesmenü = new ActionRowBuilder()
.addComponents(
new StringSelectMenuBuilder()
.setCustomId('rulesmenü')
.setPlaceholder('Antwort auswählen')
.addOptions(
{
label: 'Ja, gelesen und einverstanden.',
value: 'ja',
},
{
label: 'Nein, nicht gelsesen und nicht einverstanden.',
value: 'nein',
},
),
);
const rolemenü = new ActionRowBuilder()
.addComponents(
new StringSelectMenuBuilder()
.setCustomId('rolemenü')
.setPlaceholder('Rolle auswählen')
.addOptions(
{
label: 'YU91 Glocke',
description: 'Erhalte extra Benachrichtigungen über Yankeeunit91.',
value: 'glocke',
},
{
label: 'Gaming News',
description: 'Erhalte extra Benachrichtigungen für Neue Infos über z.B Spiele etc.',
value: 'news',
},
{
label: 'Keine',
description: 'Erhalte keine Rolle.',
value: 'keine',
},
),
);
const modalsv = new ModalBuilder()
.setCustomId('ninput')
.setTitle('YANKEEUNIT91 COMMUNITY');
const nameinput = new TextInputBuilder()
.setCustomId('nameinput')
.setLabel("Server Nickname")
.setPlaceholder('Keine Sonderzeichen!')
.setStyle(TextInputStyle.Short)
.setMinLength(2)
.setMaxLength(32)
.setRequired(true);
const firstActionRowv = new ActionRowBuilder().addComponents(nameinput);
modalsv.addComponents(firstActionRowv);
const verifeembed = new EmbedBuilder()
.setTitle(`Verifizieren dich!`)
.setColor('#00ff0c')
.setDescription(stripIndents`Durch das verifizieren erhälst du zugriff auf die YANKEEUNIT91 COMMUNITY!`)
.setFooter({ text: 'YANKEEUNIT91 COMMUNITY'})
.setTimestamp();
const buttonva = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId('buttonanfrageverify')
.setEmoji('✅')
.setLabel('Verifizieren')
.setStyle(ButtonStyle.Success),
);
client.on(Events.InteractionCreate, async (interaction) => {
if (interaction.isButton()) {
const buttonID = interaction.customId
if (buttonID === 'buttonanfrageverify') {
if (interaction.member.roles.cache.has('707275842295955530')) {
await interaction.reply({ content: '**Du bist bereits auf YANKEEUNIT91 COMMUNITY verifiziert!**', ephemeral: true });
}
else await interaction.reply({ content:'**Hast du die Regeln gelesen, und bist du damit einverstanden?**', components: [rulesmenü], ephemeral: true });
}
} else if (interaction.isStringSelectMenu()) {
const selected = interaction.values.join(', ');
if (selected === 'ja') {
await interaction.showModal(modalsv);
} else if (selected === 'nein') {
await interaction.update({ content:'**Lese dir die Regeln erneut durch! Solltest du nicht mit denn Regeln einverstanden sein, bitten wir dich denn Server zu verlassen.**', components: [], ephemeral: true });
}
} if (interaction.isModalSubmit()) {
if (interaction.customId === "ninput") {
await interaction.update({ content:'**Wähle eine Role für die du dich interresierst!**', components: [rolemenü], ephemeral: true });
var ninputdata = interaction.fields.getTextInputValue('nameinput');
ninputvalues[interaction.user.id] = interaction.fields.getTextInputValue('nameinput');
ninputvalues[interaction.user.id] = ninputvalues[interaction.user.id].replace(/[^a-zA-Z0-9 ]/g, 'X');
}
} else if (interaction.isStringSelectMenu()) {
const selected = interaction.values[0];
if (selected === 'glocke') {
await interaction.update({ content:'**Du hast die \`YU91 Glocke\` erhalten. Willkommen in der YANKEEUNIT91 COMMUNITY!**', components: [], ephemeral: true });
await interaction.member.roles.add(glocke)
await interaction.member.setNickname(`${ninputvalues[interaction.user.id]}`).catch(e => (failsafe = true));
return await interaction.member.roles.add(memberrole);
} else if (selected === 'news') {
await interaction.update({ content:'**Du hast die \`Gaming News\` erhalten. Willkommen in der YANKEEUNIT91 COMMUNITY!**', components: [], ephemeral: true });
await interaction.member.roles.add(news)
await interaction.member.setNickname(`${ninputvalues[interaction.user.id]}`).catch(e => (failsafe = true));
return await interaction.member.roles.add(memberrole);
} else if (selected === 'keine') {
await interaction.update({ content:'**Willkommen in der YANKEEUNIT91 COMMUNITY!**', components: [], ephemeral: true });
await interaction.member.setNickname(`${ninputvalues[interaction.user.id]}`).catch(e => (failsafe = true));
await interaction.member.roles.add(memberrole);
}
};
});
verifiychannel.send({ embeds: [verifeembed], components: [buttonva] });
await interaction.reply({ content: 'Verifizierungs Embed wurde versendet!', ephemeral: true });
}
};```

Related

TypeError: Cannot read properties of undefined (reading 'getTextInputValue')

I want to log value from modal in discord.js into console just for test
I have js file with this code: If someone has some advices for my code I`ll accept them.
const { ChannelType, ButtonInteraction, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, PermissionFlagsBits, ModalBuilder, TextInputBuilder, TextInputStyle } = require("discord.js");
const ticketSchema = require("../../Models/Ticket");
const TicketSetup = require("../../Models/TicketSetup");
module.exports = {
name: "interactionCreate",
async execute(interaction) {
const { guild, member, customId, channel } = interaction;
const { ViewChannel, SendMessages, ManageChannels, ReadMessageHistory } = PermissionFlagsBits;
const ticketId = Math.floor(Math.random() * 9000) + 10000;
const ticket_channel = await interaction.guild.channels.cache.find(channel => channel.name === `тикет-${member.user.username}`)
const ticket_modal = new ModalBuilder().addComponents()
.setCustomId("ticket_modal")
.setTitle("Проходка");
const ticket_modal_nickname = new TextInputBuilder()
.setCustomId('ticket_modal_nickname')
.setLabel("Your nickname")
.setRequired(true)
.setStyle(TextInputStyle.Short);
const ticket_modal_age = new TextInputBuilder()
.setCustomId('ticket_modal_age')
.setLabel("How old are you?")
.setMaxLength(2)
.setRequired(true)
.setStyle(TextInputStyle.Short);
const ticket_modal_know_from = new TextInputBuilder()
.setCustomId('ticket_modal_know_from')
.setLabel("Where did you know us from?")
.setRequired(true)
.setStyle(TextInputStyle.Short);
const ticket_modal_rules = new TextInputBuilder()
.setCustomId('ticket_modal_rules')
.setLabel("did you read the rules??")
.setRequired(true)
.setStyle(TextInputStyle.Short);
const firstActionRow = new ActionRowBuilder().addComponents(ticket_modal_nickname);
ticket_modal.addComponents(firstActionRow)
if (!interaction.isButton()) return;
const data = await TicketSetup.findOne({ GuildID: guild.id });
if (!data)
return;
if (!data.Buttons.includes(customId))
return;
if (!guild.members.me.permissions.has(ManageChannels)) {
await interaction.reply({ content: "У меня нет прав на это!", ephemeral: true });
}
await interaction.showModal(ticket_modal);
const test = await interaction.fields.getTextInputValue('ticket_modal_nickname');
console.log(test)
if (ticket_channel) {
return await interaction.reply({ content: `У вас уже есть тикет в: ${ticket_channel}`, ephemeral: true });
} try {
await guild.channels.create({
name: `тикет-${member.user.username}`,
type: ChannelType.GuildText,
parent: data.Category,
permissionOverwrites: [
{
id: data.Everyone,
deny: [ViewChannel, SendMessages, ReadMessageHistory],
},
{
id: member.id,
allow: [ViewChannel, SendMessages, ReadMessageHistory],
},
{
id: '1060588595917881444',
allow: [ViewChannel, SendMessages, ReadMessageHistory],
},
{
id: '1059419571804704879',
allow: [ViewChannel, SendMessages, ReadMessageHistory],
},
{
id: '1059419404015784016',
allow: [ViewChannel, SendMessages, ReadMessageHistory],
},
],
}).then(async (channel) => {
const newTicketSchema = await ticketSchema.create({
GuildID: guild.id,
MembersID: member.id,
TicketID: ticketId,
ChannelID: channel.id,
Closed: false,
Type: customId,
});
const embed = new EmbedBuilder()
.setTitle(`Проходка.`)
.setDescription("> **Здравствуйте! Спасибо за обращение. Ожидайте ответа от Модератора/Администратора.**\n > **Ожидание может занять до 12 ч.**")
.setFooter({ text: `${ticketId}`, iconURL: member.displayAvatarURL({ dynamic: true }) })
.setColor("0x2f3136")
.setTimestamp();
const button = new ActionRowBuilder().setComponents(
new ButtonBuilder().setCustomId('close').setLabel('Закрыть тикет').setStyle(ButtonStyle.Danger).setEmoji('❌'),
);
channel.send({
embeds: ([embed]),
components: [
button
]
});
interaction.reply({ content: "Успешно создал тикет.", ephemeral: true });
});
} catch (err) {
return console.log(err);
}
}
}
But I`m having an error: TypeError: Cannot read properties of undefined (reading 'getTextInputValue') If someone knows how to fix this please reply. Error in this stroke:
const test = await interaction.fields.getTextInputValue('ticket_modal_nickname');
Thank you for help.

Discord Bot replies undefined in Embed

My bot only replies undefined with two variables, although I actually defined them.
I dont know why it not works pls help
The command is: you press the button enter a reason and a game in the text input field and then you select a platform from the drop down menu. But instead of sending the embed it says undefined.
My Code:
const Discord = require('discord.js')
const Command = require('../../structures/CommandClass');
const { stripIndents } = require('common-tags');
const { SlashCommandBuilder, PermissionFlagsBits, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, TextInputStyle, StringSelectMenuBuilder, Events, ModalBuilder, TextInputBuilder } = require('discord.js');
module.exports = class spielersuche extends Command {
constructor(client) {
super(client, {
data: new SlashCommandBuilder()
.setName('sendspielersuche')
.setDescription('Sende das Spielersuche Embed')
.setDefaultMemberPermissions(PermissionFlagsBits.BanMembers)
.setDMPermission(false),
});
}
async run(client, interaction) {
let member = await interaction.member.fetch();
const anfragechannelID = '889302458906591344';
const anfragechannel = member.guild.channels.cache.get(anfragechannelID);
const createanfragechannelID = '1061113274130772058';
const createanfragechannel = member.guild.channels.cache.get(createanfragechannelID);
const pfmenü = new ActionRowBuilder()
.addComponents(
new StringSelectMenuBuilder()
.setCustomId('pfmenü')
.setPlaceholder('Plattform auswählen')
.addOptions(
{
label: 'PS4',
value: 'ps4',
},
{
label: 'PS5',
value: 'ps5',
},
{
label: 'PS4/PS5',
value: 'ps4ps5',
},
{
label: 'PC',
value: 'pc',
},
{
label: 'Switch',
value: 'switch',
},
{
label: 'Alle',
value: 'alle',
},
),
);
const modals = new ModalBuilder()
.setCustomId('minput')
.setTitle('Spielersuche 🔎');
const spielinput = new TextInputBuilder()
.setCustomId('spielinput')
.setLabel("Für welches Spiel?")
.setPlaceholder('GTA5, Fortnite, Call of Duty, Minecraft ...')
.setStyle(TextInputStyle.Short)
.setMinLength(2)
.setMaxLength(20)
.setRequired(true);
const grundinput = new TextInputBuilder()
.setCustomId('grundinput')
.setLabel("Der Grund der Anfrage?")
.setPlaceholder('Beispiel: Suche Spieler für Cayo Perico Heist.')
.setStyle(TextInputStyle.Short)
.setMinLength(10)
.setMaxLength(60)
.setRequired(true);
const firstActionRow = new ActionRowBuilder().addComponents(spielinput);
const secondActionRow = new ActionRowBuilder().addComponents(grundinput);
modals.addComponents(firstActionRow, secondActionRow);
const spielersucheerweitertEmbed = new EmbedBuilder()
.setTitle(`Spieler suchen Spieler 🔎`)
.setColor('#00ff0c')
.setDescription(stripIndents`Drücke auf denn Button um eine Spielersuche Anzufragen!`)
.setFooter({ text: 'YANKEEUNIT91 COMMUNITY'})
.setTimestamp();
const buttonsa = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId('buttonanfrage')
.setEmoji('🔎')
.setLabel('Spielersuche Anfragen')
.setStyle(ButtonStyle.Success),
);
client.on('interactionCreate', async interaction => {
if (interaction.isButton()) {
const buttonID = interaction.customId
if (buttonID === 'buttonanfrage') {
await interaction.showModal(modals);
}
}
});
createanfragechannel.send({ embeds: [spielersucheerweitertEmbed], components: [buttonsa] });
await interaction.reply({ content: 'Spielersuche Embed wurde versendet!', ephemeral: true });
client.on(Events.InteractionCreate, async (interaction) => {
if (interaction.isModalSubmit()) {
if (interaction.customId === "minput") {
await interaction.reply({ content:'**Wähle deine Plattform!**', components: [pfmenü], ephemeral: true });
var ginputdata = interaction.fields.getTextInputValue('grundinput');
var sinputdata = interaction.fields.getTextInputValue('spielinput');
}
} else if (interaction.isStringSelectMenu()) {
const selected = await interaction.values.join(', ');
const spielersucheerweitertEmbedfertig = new EmbedBuilder()
.setTitle(`${ginputdata}`)
.setColor('#00ff0c')
.setFooter({ text: 'YANKEEUNIT91 COMMUNITY'})
.setTimestamp()
.addFields(
{
name: '**Spiel:**',
value: `${sinputdata}`,
inline: true,
},
{
name: `**Plattform:**:`,
value: `${selected}`,
inline: false,
},
);
if (interaction.customId === "pfmenü") {
const member = await interaction.member.fetch();
await interaction.update({ content:'**Spielersuche erfolgreich Angefragt!**', components: [], ephemeral: true });
return await anfragechannel.send({ content: `**Anfrage von:** <#${member.id}>`, embeds: [spielersucheerweitertEmbedfertig] });
}
};
});
}
};
tried to define something else but it didn't work
You should focus on where your variables is saved. The variable sinputdata is saved inside the function. The function is like a piece of code that is extracted from the file and ran without really saving variables inside of the function. So every time the function is ran, all your variables are reset.
In other words, you need to save the data you want to keep outside of the function. Therefore, you should make a table at the beginning of your module. Every functions inside the module will be able to edit the table and read the values of it. In addition, everything will be saved (I mean, if you reload the bot, every data will be lost so you need to save everything in a database). Back to the table, the table will include the discordid and the sinputdata value. First, you will set the sinputdata value in the table when you receive it. Then, you will be able to use the sinputdata value when the function is ran a new time.
At the top (under const { SlashCommandBuilder, PermissionFlagsBits, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, TextInputStyle, StringSelectMenuBuilder, Events, ModalBuilder, TextInputBuilder } = require('discord.js');), write let sinputvalues = {};
Then, instead of var sinputdata = interaction.fields.getTextInputValue('spielinput');, write sinputvalues[interaction.user.id] = interaction.fields.getTextInputValue('spielinput');.
Finally, replace
{
name: '**Spiel:**',
value: `${sinputdata}`,
inline: true,
},
to
{
name: '**Spiel:**',
value: `${sinputvalues[interaction.user.id]}`,
inline: true,
},

Discord Bot always replies one more message

Respons Picture
Hi my Bot always replies one more message, The command works you press the button enter a reason in the text input field and then you select a platform from the drop down menu. But instead of sending the embed once, it sends it multiple times each time.
Error: Error [InteractionAlreadyReplied]: The reply to this interaction has already been sent or deferred.
Or: "Interaction has already been acknowledged."
const Discord = require('discord.js')
const Command = require('../../structures/CommandClass');
const { stripIndents } = require('common-tags');
const { SlashCommandBuilder, PermissionFlagsBits, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, TextInputStyle, StringSelectMenuBuilder, Events, ModalBuilder, TextInputBuilder } = require('discord.js');
module.exports = class spielersucheerweitert extends Command {
constructor(client) {
super(client, {
data: new SlashCommandBuilder()
.setName('sendspielersuche')
.setDescription('Sende das Spielersuche Embed')
.setDefaultMemberPermissions(PermissionFlagsBits.BanMembers)
.setDMPermission(false),
});
}
async run(client, interaction) {
let member = await interaction.member.fetch();
const pfmenü = new ActionRowBuilder()
.addComponents(
new StringSelectMenuBuilder()
.setCustomId('pfmenü')
.setPlaceholder('Plattform auswählen')
.addOptions(
{
label: 'PS4',
value: 'ps4',
},
{
label: 'PS5',
value: 'ps5',
},
{
label: 'PS4/PS5',
value: 'ps4ps5',
},
{
label: 'PC',
value: 'pc',
},
{
label: 'Switch',
value: 'switch',
},
{
label: 'Alle',
value: 'alle',
},
),
);
const modals = new ModalBuilder()
.setCustomId('minput')
.setTitle('Spielersuche 🔎');
const spielinput = new TextInputBuilder()
.setCustomId('spielinput')
.setLabel("Für welches Spiel?")
.setPlaceholder('GTA5, Fortnite, Call of Duty, Minecraft ...')
.setStyle(TextInputStyle.Short)
.setMinLength(2)
.setMaxLength(20)
.setRequired(true);
const grundinput = new TextInputBuilder()
.setCustomId('grundinput')
.setLabel("Der Grund der Anfrage?")
.setPlaceholder('Beispiel: Suche Spieler für Cayo Perico Heist.')
.setStyle(TextInputStyle.Short)
.setMinLength(10)
.setMaxLength(60)
.setRequired(true);
const firstActionRow = new ActionRowBuilder().addComponents(spielinput);
const secondActionRow = new ActionRowBuilder().addComponents(grundinput);
modals.addComponents(firstActionRow, secondActionRow);
const spielersucheerweitertEmbed = new EmbedBuilder()
.setTitle(`Spieler suchen Spieler 🔎`)
.setColor('#00ff0c')
.setDescription(stripIndents`Drücke auf denn Button um eine Spielersuche Anzufragen!`)
.setFooter({ text: 'YANKEEUNIT91 COMMUNITY'})
.setTimestamp();
const buttonsa = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId('buttonanfrage')
.setEmoji('🔎')
.setLabel('Spielersuche Anfragen')
.setStyle(ButtonStyle.Success),
);
client.on('interactionCreate', async interaction => {
if (interaction.isButton()) {
const buttonID = interaction.customId
if (buttonID === 'buttonanfrage') {
await interaction.showModal(modals);
}
}
});
client.on('interactionCreate', (modalSubmit) => {
if (!modalSubmit.isModalSubmit()) return;
const ginputdata = modalSubmit.fields.getTextInputValue('grundinput');
const sinputdata = modalSubmit.fields.getTextInputValue('spielinput');
modalSubmit.reply({
content:'**Wähle deine Plattform!**', components: [pfmenü], ephemeral: true });
client.on('interactionCreate', async interaction => {
if (!interaction.isStringSelectMenu()) return;
const selected = await interaction.values.join(', ');
const spielersucheerweitertEmbedfertig = new EmbedBuilder()
.setTitle(`${ginputdata}`)
.setColor('#00ff0c')
.setDescription(stripIndents`Spiel: \`${sinputdata}\`
Plattform: \`${selected}\``)
.setFooter({ text: 'YANKEEUNIT91 COMMUNITY'})
.setTimestamp();
await interaction.channel.send({ embeds: [spielersucheerweitertEmbedfertig] });
return await interaction.update({ content: '**Spielersuche wurde erfolgreich Angefragt!**', components: [] });
});
});
await interaction.channel.send({ embeds: [spielersucheerweitertEmbed], components: [buttonsa] });
return await interaction.reply({ content: 'Spielersuche Embed wurde versendet!', ephemeral: true });
}
};
I've looked at the code several times but have no idea why he's doing it more and more often
client.on('interactionCreate', async interaction => {
if (!interaction.isStringSelectMenu()) return;
const selected = await interaction.values.join(', ');
const spielersucheerweitertEmbedfertig = new EmbedBuilder()
.setTitle(`${ginputdata}`)
.setColor('#00ff0c')
.setDescription(stripIndents`Spiel: \`${sinputdata}\`
Plattform: \`${selected}\``)
.setFooter({ text: 'YANKEEUNIT91 COMMUNITY'})
.setTimestamp();
//executed when the button with the buttonanfrage custom ID is clicked
await interaction.channel.send({ embeds: [spielersucheerweitertEmbedfertig] });
return await interaction.update({ content: '**Spielersuche wurde erfolgreich Angefragt!**', components: [] });
});
});
//This block is executed when the function is run
await interaction.channel.send({ embeds: [spielersucheerweitertEmbed], components: [buttonsa] });
return await interaction.reply({ content: 'Spielersuche Embed wurde versendet!', ephemeral: true });
}
The issue you are experiencing is caused by the fact that both of these blocks of code are being executed, which is resulting in the same message and update being sent multiple times.
So you have 2 options:
Remove the second block of code that sends the message and updates
the interaction. This will prevent the message and update from being
sent multiple times.
Add a flag to track whether or not the message and update have
already been sent. You can then check the flag before sending the
message and update to ensure that they are only sent once.

how to send an embed privately after i run a button?

I would have a problem with modals.
I want that when someone executes a modal in the log the embed is sent with the accepted or rejected button and up to here everything is fine.
when a staff accepts or refuses I want the embed of the result to be sent to the person who performed the modal.
how can I do?
this is the modal code:
client.on("messageCreate", (message, interaction) => {
if(message.content == "!bando"){
const bando = new MessageEmbed()
.setColor("#037bfc")
.setTitle("MODULO BANDO STAFF")
.setDescription(`Se vorresti diventare staff, segui le regole\n del bando in <#995108403330416753> e poi premi il bottone qua sotto`)
.setTimestamp()
.setFooter({ text: "Developed by #Wrld#0095", iconURL: "https://cdn.discordapp.com/attachments/987458307092545568/995114362748547183/logo-wrld.gif"})
const row = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId('bando')
.setLabel('Modulo bando')
.setStyle('PRIMARY')
.setEmoji('📝'),
);
message.channel.send({embeds: [bando], components: [row]})
}
})
client.on('interactionCreate', async interaction => {
if (!interaction.isButton()) return;
if (interaction.customId === 'bando') {
// Create the modal
const modal = new Modal()
.setCustomId('modalBando')
.setTitle('MODULO BANDO');
const nome = new TextInputComponent()
.setCustomId('nome')
.setLabel("Nome")
.setStyle('SHORT');
const eta = new TextInputComponent()
.setCustomId('eta')
.setLabel("Età")
.setStyle('SHORT');
const motivo = new TextInputComponent()
.setCustomId('motivo')
.setLabel("Perchè vorresti diventare staff?")
.setStyle('PARAGRAPH');
const mansione = new TextInputComponent()
.setCustomId('mansione')
.setLabel("Che ruolo vorresti ricoprire?")
.setStyle('SHORT');
const firstActionRow = new MessageActionRow().addComponents(nome);
const secondActionRow = new MessageActionRow().addComponents(eta);
const thirdActionRow = new MessageActionRow().addComponents(motivo);
const fourthActionRow = new MessageActionRow().addComponents(mansione);
modal.addComponents(firstActionRow, secondActionRow, thirdActionRow, fourthActionRow);
await interaction.showModal(modal);
}
});
client.on("interactionCreate", async interaction => {
if (!interaction.isModalSubmit()) return;
if (interaction.customId === 'modalBando') {
const author = interaction.member
const bandoInviato = new MessageEmbed()
.setColor("#037bfc")
.setTitle("MODULO BANDO STAFF")
.setDescription(`Salve, il suo bando è stato inviato.\n Presto le comunicheremo l'esito.`)
.setTimestamp()
.setFooter({ text: "Developed by #Wrld#0095", iconURL: "https://cdn.discordapp.com/attachments/987458307092545568/995114362748547183/logo-wrld.gif"})
await author.send({ embeds: [bandoInviato]});
const nome = interaction.fields.getTextInputValue('nome');
const eta = interaction.fields.getTextInputValue('eta');
const motivo = interaction.fields.getTextInputValue('motivo');
const mansione = interaction.fields.getTextInputValue('mansione');
const logBando = interaction.guild.channels.cache.get("995105468341026866");
const bandoLog = new MessageEmbed()
.setColor("#037bfc")
.setTitle("MODULO BANDO STAFF")
.setDescription(`Bando eseguito da ${interaction.user.tag}`)
.addFields(
{ name: 'Nome', value: nome, inline: false },
{ name: 'Età', value: eta, inline: false },
{ name: 'Perchè vorresti diventare staff?', value: motivo, inline: false },
{ name: 'Che ruolo vorresti ricoprire?', value: mansione, inline: false },
)
.setTimestamp()
.setFooter({ text: "Developed by #Wrld#0095", iconURL: "https://cdn.discordapp.com/attachments/987458307092545568/995114362748547183/logo-wrld.gif"})
const esitoBando = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId('accettato')
.setLabel('Accetta')
.setStyle('SUCCESS')
.setEmoji('✔'),
new MessageButton()
.setCustomId('rifiutato')
.setLabel('Rifiuta')
.setStyle('DANGER')
.setEmoji('❌'),
);
await logBando.send({ embeds: [bandoLog], components: [esitoBando]});
}
if(!interaction.isButton()) return;
if(interaction.customId == "accettato"){
const accettato = new MessageEmbed()
.setColor("#037bfc")
.setTitle("BANDO ACCETTATO")
.setDescription(`Salve, il suo bando è stato accettato.\n Apra un <#995105177403142174>e comunica gli orari disponibili\n per effettuare il colloquio.`)
.setTimestamp()
.setFooter({ text: "Developed by #Wrld#0095", iconURL: "https://cdn.discordapp.com/attachments/987458307092545568/995114362748547183/logo-wrld.gif"})
await author.send({ embeds: [accettato]})
} else if(interaction.customId == "rifiutato"){
const rifiutato = new MessageEmbed()
.setColor("#037bfc")
.setTitle("BANDO RIFIUTATO")
.setDescription(`Salve, il suo bando è stato rifiutato.\n Ritenta alle prossime candidature.`)
.setTimestamp()
.setFooter({ text: "Developed by #Wrld#0095", iconURL: "https://cdn.discordapp.com/attachments/987458307092545568/995114362748547183/logo-wrld.gif"})
await author.send({ embeds: [rifiutato]})
}
})
I refactored your code, you don't need more than one listener of each type, but this should work for you.
I added a component to the embed that is created when the modal is submitted. That component is used to locate the original member who created it.
client.on("messageCreate", (message, interaction) => {
if (message.content === "!bando") {
const bando = new MessageEmbed()
.setColor("#037bfc")
.setTitle("MODULO BANDO STAFF")
.setDescription(`Se vorresti diventare staff, segui le regole\n del bando in <#995108403330416753> e poi premi il bottone qua sotto`)
.setTimestamp()
.setFooter({
text: "Developed by #Wrld#0095",
iconURL: "https://cdn.discordapp.com/attachments/987458307092545568/995114362748547183/logo-wrld.gif"
})
const row = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId('bando')
.setLabel('Modulo bando')
.setStyle('PRIMARY')
.setEmoji('📝'),
);
message.channel.send({
embeds: [bando],
components: [row]
});
}
});
client.on('interactionCreate', async interaction => {
const author = interaction.member;
let member2Send = interaction.guild.members.cache.get(interaction.message.embeds[0].author.name);
if (interaction.isButton()) {
if (interaction.customId === 'bando') {
const modal = new Modal()
.setCustomId('modalBando')
.setTitle('MODULO BANDO');
const nome = new TextInputComponent()
.setCustomId('nome')
.setLabel("Nome")
.setStyle('SHORT');
const eta = new TextInputComponent()
.setCustomId('eta')
.setLabel("Età")
.setStyle('SHORT');
const motivo = new TextInputComponent()
.setCustomId('motivo')
.setLabel("Perchè vorresti diventare staff?")
.setStyle('PARAGRAPH');
const mansione = new TextInputComponent()
.setCustomId('mansione')
.setLabel("Che ruolo vorresti ricoprire?")
.setStyle('SHORT');
const firstActionRow = new MessageActionRow().addComponents(nome);
const secondActionRow = new MessageActionRow().addComponents(eta);
const thirdActionRow = new MessageActionRow().addComponents(motivo);
const fourthActionRow = new MessageActionRow().addComponents(mansione);
modal.addComponents(firstActionRow, secondActionRow, thirdActionRow, fourthActionRow);
await interaction.showModal(modal);
} else if (interaction.customId === "accettato") {
if (member2Send) {
const accettato = new MessageEmbed()
.setColor("#037bfc")
.setTitle("BANDO ACCETTATO")
.setDescription(`Salve, il suo bando è stato accettato.\n Apra un <#995105177403142174>e comunica gli orari disponibili\n per effettuare il colloquio.`)
.setTimestamp()
.setFooter({
text: "Developed by #Wrld#0095",
iconURL: "https://cdn.discordapp.com/attachments/987458307092545568/995114362748547183/logo-wrld.gif"
})
await member2Send.send({
embeds: [accettato]
});
}
} else if (interaction.customId === "rifiutato") {
if (member2Send){
const rifiutato = new MessageEmbed()
.setColor("#037bfc")
.setTitle("BANDO RIFIUTATO")
.setDescription(`Salve, il suo bando è stato rifiutato.\n Ritenta alle prossime candidature.`)
.setTimestamp()
.setFooter({
text: "Developed by #Wrld#0095",
iconURL: "https://cdn.discordapp.com/attachments/987458307092545568/995114362748547183/logo-wrld.gif"
})
await member2Send.send({
embeds: [rifiutato]
});
}
}
}
if (interaction.isModalSubmit()) {
if (interaction.customId === 'modalBando') {
const bandoInviato = new MessageEmbed()
.setColor("#037bfc")
.setAuthor({
name: author.user.id
})
.setTitle("MODULO BANDO STAFF")
.setDescription(`Salve, il suo bando è stato inviato.\n Presto le comunicheremo l'esito.`)
.setTimestamp()
.setFooter({
text: "Developed by #Wrld#0095",
iconURL: "https://cdn.discordapp.com/attachments/987458307092545568/995114362748547183/logo-wrld.gif"
})
await author.send({
embeds: [bandoInviato]
});
const nome = interaction.fields.getTextInputValue('nome');
const eta = interaction.fields.getTextInputValue('eta');
const motivo = interaction.fields.getTextInputValue('motivo');
const mansione = interaction.fields.getTextInputValue('mansione');
const logBando = interaction.guild.channels.cache.get("995105468341026866");
const bandoLog = new MessageEmbed()
.setColor("#037bfc")
.setTitle("MODULO BANDO STAFF")
.setDescription(`Bando eseguito da ${interaction.user.tag}`)
.addFields({
name: 'Nome',
value: nome,
inline: false
}, {
name: 'Età',
value: eta,
inline: false
}, {
name: 'Perchè vorresti diventare staff?',
value: motivo,
inline: false
}, {
name: 'Che ruolo vorresti ricoprire?',
value: mansione,
inline: false
}, )
.setTimestamp()
.setFooter({
text: "Developed by #Wrld#0095",
iconURL: "https://cdn.discordapp.com/attachments/987458307092545568/995114362748547183/logo-wrld.gif"
});
const esitoBando = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId('accettato')
.setLabel('Accetta')
.setStyle('SUCCESS')
.setEmoji('✔'),
new MessageButton()
.setCustomId('rifiutato')
.setLabel('Rifiuta')
.setStyle('DANGER')
.setEmoji('❌'),
);
await logBando.send({
embeds: [bandoLog],
components: [esitoBando]
});
}
}
});

I can't change channel permissions ( interaction.channel.permissionOverwrites is not a function )

I'm trying to make a ticket system, that when I click on the button, it changes the channel category and removes the member's permission to see it. When I click the button, it changes the category but doesn't change the channel's permission. I've already looked in the docs, and I haven't found anything.
the error:
C:\Users\whash\OneDrive\Documentos\optipc_bot_beta_sem_erro\events\ticket\suporte.js:187
interaction.channel.permissionOverwrites(subTicketSuporte.userId, {deny: Permissions.FLAGS.VIEW_CHANNEL})
^
TypeError: interaction.channel.permissionOverwrites is not a function
at Client.<anonymous> (C:\Users\whash\OneDrive\Documentos\optipc_bot_beta_sem_erro\events\ticket\suporte.js:187:29)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Database:
my code:
const {
MessageActionRow,
MessageButton,
MessageEmbed,
MessageSelectMenu,
Permissions,
} = require("discord.js");
const firebase = require("firebase");
const db = firebase.database();
const client = require("../../index");
client.on("interactionCreate", async (interaction) => {
if (interaction.isCommand()) return;
interaction.deferUpdate();
// ROWS //
const rowDelChannel = new MessageActionRow().addComponents(
new MessageButton()
.setStyle("DANGER")
.setLabel("🗑 | Deletar canal")
.setCustomId("delChannel")
);
const rowDelMessage = new MessageActionRow().addComponents(
new MessageButton()
.setStyle("DANGER")
.setLabel("🗑 | Deletar mensagem")
.setCustomId("delMessage")
);
const rowArchiveThread = new MessageActionRow().addComponents(
new MessageButton()
.setStyle("DANGER")
.setLabel("📨 | Arquivar thread")
.setCustomId("archiveThread")
);
const rowArchiveChannel = new MessageActionRow().addComponents(
new MessageButton()
.setStyle("DANGER")
.setLabel("📨 | Arquivar canal")
.setCustomId("archiveChannel")
);
// EMBEDS //
let embedOptions = new MessageEmbed()
.setTitle("🔒 | Opções do ticket")
.setDescription(
'Olá, bem vindo a aba de suporte! Caso queira fechar o ticket, clique em "arquivar" ou "deletar".'
)
.setColor("GREY")
.setFooter("A optiPC agradece sua atenção.", interaction.guild.iconURL());
let subTicketSuporte = await db.ref(`Ticket/Arquivado/${interaction.user.id}`).once("value");
subTicketSuporte = subTicketSuporte.val();
// PAINEL DE SUPORTE//
if (interaction.customId === "OPENSUPORTE") {
// DATABASE //
let ticketSuporte = await db.ref(`Ticket/Suporte`).once("value");
ticketSuporte = ticketSuporte.val();
//var subTicketSuporte = await db.ref(`Ticket/Arquivado/${interaction.user.id}`).once("value");
// subTicketSuporte = subTicketSuporte.val();
if (!ticketSuporte) ticketSuporte = {};
if (!subTicketSuporte) subTicketSuporte = {};
// salvando contador
if (!ticketSuporte.contador) {
db.ref(`Ticket/Suporte`).set({
contador: parseInt(1),
});
} else {
db.ref(`Ticket/Suporte`).update({
contador: ticketSuporte.contador + parseInt(1),
});
}
// salvando o ID do user na DB
if (!subTicketSuporte.userId) {
db.ref(`Ticket/Arquivado/${interaction.user.id}`).set({
userId: interaction.user.id
});
}
// configurando o canal do ticket
let canalSuporte = await interaction.guild.channels.create(
`❔▏suporte_${ticketSuporte.contador}`,
{
parent: "915975240541171813",
type: "GUILD_TEXT",
permissionOverwrites: [
{
id: interaction.guild.id,
deny: [Permissions.FLAGS.VIEW_CHANNEL],
},
{
id: interaction.user.id,
allow: [
Permissions.FLAGS.VIEW_CHANNEL,
Permissions.FLAGS.SEND_MESSAGES,
],
},
],
}
);
await canalSuporte.send({
embeds: [embedOptions],
components: [rowDelChannel, rowArchiveChannel],
});
interaction.followUp({
content: `✅ Ticket criado com sucesso! Por favor, vá até ${canalSuporte}.`,
ephemeral: true,
});
/*
// configurando thread
const threadSuporte = await interaction.channel.threads.create({
name: `❔▏suporte_${counterSuporte.contador}`,
autoArchiveDuration: 60,
// type: 'GUILD_PRIVATE_THREAD',
reason: 'Thread para suporte.'
});
if (threadSuporte.joinable) await threadSuporte.join();
await threadSuporte.members.add('840983211458428928');
await threadSuporte.members.add('550978800952016896');
await threadSuporte.members.add('518517142656647208');
await threadSuporte.members.add('639856950368010240');
// ARQUIVAR THREAD //
if (interaction.customId === "archiveThread") {
let permicaoNecessaria = Permissions.FLAGS.BAN_MEMBERS;
if (!interaction.member.permissions.has(permicaoNecessaria))
return interaction.followUp({
content: "Você não possui permissão para arquivar o ticket!",
ephemeral: true,
});
await threadSuporte.setArchived(true); // archived
}
}
*/
}
// ROW CONFIG
if (interaction.customId === "delChannel") {
let permicaoNecessaria = Permissions.FLAGS.BAN_MEMBERS;
if (!interaction.member.permissions.has(permicaoNecessaria))
return interaction.followUp({
content: "Você não possui permissão para fechar o ticket!",
ephemeral: true,
});
interaction.channel.delete();
}
if (interaction.customId === "delMessage") {
let permicaoNecessaria = Permissions.FLAGS.BAN_MEMBERS;
if (!interaction.member.permissions.has(permicaoNecessaria))
return interaction.followUp({
content: "Você não possui permissão para fechar o ticket!",
ephemeral: true,
});
interaction.message.delete();
}
if (interaction.customId === "archiveChannel") {
console.log("a") // a
let permicaoNecessaria = Permissions.FLAGS.BAN_MEMBERS;
if (!interaction.member.permissions.has(permicaoNecessaria))
return interaction.followUp({
content: "Você não possui permissão para arquivar o ticket!",
ephemeral: true,
});
await interaction.channel.setParent("915985254127370240");
interaction.channel.permissionOverwrites(subTicketSuporte.userId, {deny: Permissions.FLAGS.VIEW_CHANNEL})
}
});
In fact, GuildChannel#permissionOverwrites is not a function
It's a property that returns PermissionOverwriteManager
I suggest you to use
interaction.channel.permissionOverwrites.edit(subTicketSuporte.userId, { "VIEW_CHANNEL": false })
And that should be it
Docs Source
GuildChannel#permissionOverwrites is a PermissionOverwriteManager. Use .set on it instead:
interaction.channel.permissionOverwrites.set([{
deny: [Permissions.FLAGS.VIEW_CHANNEL],
id: subTicketSuporte.userId,
type: "member"
}])

Categories