Discord Bot always replies one more message - javascript

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.

Related

Banned and kicked logs

I made a ban and kick script and it's working, but when a user gets a ban, the bot sends a ban and a kick message (even if the user gets a ban). I want it to send only the ban message when the user receives the ban, and the kick message only when the user receives a kick.
client.on(Events.GuildBanRemove, async (ban) => {
const fetchedLogs = await ban.guild.fetchAuditLogs({
limit: 1,
type: AuditLogEvent.MemberBanRemove,
});
const unbanLog = fetchedLogs.entries.first();
const { executor, target } = unbanLog;
if (target.id === ban.user.id) {
const channel2 = client.channels.cache.get("1026979529387950132");
const embed2 = new Discord.EmbedBuilder()
.setColor("#10fee4")
.setThumbnail(`${client.user.displayAvatarURL({ size: 2048 })}`)
.setTitle(`Log | Usuario Desbanido.`)
.setDescription(`**Informações do usuario:**\n > Membro:${ban.user}\n > ID:\`${ban.user.id}\`\n\n**Informações do unban**:\n > Desbanido por: ${executor}\n> ID:\`${executor.id}\``)
.setFooter({ text: `© ${client.user.username} 2023` })
.setTimestamp(new Date());
channel2.send({ embeds: [embed2] });
}
});
client.on(Events.GuildMemberRemove, async (member) => {
const fetchedLogs2 = await member.guild.fetchAuditLogs({
limit: 1,
type: AuditLogEvent.MemberKick,
});
const kickLog = fetchedLogs2.entries.first();
const { executor, target } = kickLog;
if (target.id === member.id) {
const channel3 = client.channels.cache.get("1026979529387950132");
const embed3 = new Discord.EmbedBuilder()
.setColor("#10fee4")
.setThumbnail(`${client.user.displayAvatarURL({ size: 2048 })}`)
.setTitle(`Log | Usuario Expulso.`)
.setDescription(`**Informações do usuario:**\n > Membro:${member.user}\n > ID:\`${member.user.id}\`\n\n**Informações da expulsão:**\n > Expulso por: ${executor}\n> ID:\`${executor.id}\``)
.setFooter({ text: `© ${client.user.username} 2023` })
.setTimestamp(new Date());
channel3.send({ embeds: [embed3] });
}
});

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

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 });
}
};```

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.js V13 player.getQueue() returns undefined even tho a queue exists

I'm creating a discord bot with queue system. A queue is created in play.js file. The queue is then fetched in skip.js using player.getQueue() method to be able to skip songs. However, it returns undefined meaning no queue was found.
I know for a fact a queue exist because I logged it in the console but somehow this methode can't find it.
play.js Code :
const { SlashCommandBuilder } = require('#discordjs/builders');
const { Player, QueryType } = require('discord-player');
module.exports = {
data: new SlashCommandBuilder()
.setName('play')
.setDescription('plays music')
.addStringOption(option => option
.setName("song")
.setDescription("what to play")
.setRequired(true)),
async execute(interaction, Discord) {
const voice_channel = interaction.member.voice.channel;
const bot_channel = interaction.guild.me.voice.channel;
if (!voice_channel) {
await interaction.reply({
embeds: [new Discord.MessageEmbed()
.setColor('#FFDAB9')
.setDescription('You need to be in a voice channel to play music!')],
ephemeral: true
});
}
if (bot_channel && bot_channel.id != voice_channel.id) {
await interaction.reply({
embeds: [new Discord.MessageEmbed()
.setColor('#FFDAB9')
.setDescription(`I'm already connected on ${bot_channel.toString()}`)],
ephemeral: true
});
}
const song = interaction.options.getString("song");
const player = new Player(interaction.client);
const searchResult = await player.search(song, {
requestedBy: interaction.user,
searchEngine: QueryType.AUTO
}).catch(() => { });
if (!searchResult || !searchResult.tracks.length) {
return interaction.reply({ content: 'No music found!', ephemeral: true });
}
const queue = player.createQueue(interaction.guild);
queue.options.initialVolume = 50;
queue.options.leaveOnEmptyCooldown = 5000;
try {
if (!queue.connection) await queue.connect(voice_channel);
} catch {
void player.deleteQueue(interaction.guildId);
return void interaction.reply({ content: "Could not join your voice channel!", ephemeral: true });
}
searchResult.playlist ? queue.addTracks(searchResult.tracks) : queue.addTrack(searchResult.tracks[0]);
if (!queue.playing) {
await queue.play().then(queue.playing = true);
// console.log(queue);
}
const row = new Discord.MessageActionRow()
.addComponents(
new Discord.MessageButton()
.setCustomId('pause')
.setLabel('⏸')
.setStyle('PRIMARY'),
)
.addComponents(
new Discord.MessageButton()
.setCustomId('resume')
.setLabel('▶')
.setStyle('PRIMARY'),
);
const play_embed = await interaction.reply({
embeds: [new Discord.MessageEmbed()
.setColor('#FFDAB9')
.setTitle(`${queue.nowPlaying().title}`)
.setURL(`${queue.nowPlaying().url}`)
.setThumbnail(`${queue.nowPlaying().thumbnail}`)
.setAuthor({ name: ` | Now Playing`, iconURL: `https://imgur.com/krzRxsN.png` })
.addField('Duration :', `\`${queue.nowPlaying().duration}\``, true)
.addField('Author :', `\`${queue.nowPlaying().author}\``, true)
.setTimestamp()
.setFooter({ text: `Requested By ${interaction.user.username}`, iconURL: `${interaction.user.displayAvatarURL()}` })
],
// components: [row]
});
}
}
skip.js Code :
const { SlashCommandBuilder } = require('#discordjs/builders');
const { Player, QueryType } = require('discord-player');
module.exports = {
data: new SlashCommandBuilder()
.setName('skip')
.setDescription('skips to the next music in queue'),
async execute(interaction, Discord) {
await interaction.deferReply();
const player = new Player(interaction.client);
console.log(player.queues);
const queue = player.getQueue(interaction.guildId);
// console.log(queue);
if (!queue || !queue.playing) return void interaction.followUp({ content: "❌ | No music is being played!" });
const currentTrack = queue.current;
const success = queue.skip();
return void interaction.followUp({
content: success ? `✅ | Skipped **${currentTrack}**!` : "❌ | Something went wrong!"
});
}
}
In index.js ,
client.player = new Player(client);
In execute function, pass client as an argument.
execute({interaction, client})
In skip.js, While getting the queue, Try this--
const queue = await client.player.getQueue(interaction.guildId)

Discord.js v13 | ReactionRole.findOneAndUpdate() does not update data in mongoose

Code:
const role = interaction.options.getRole('role');
const description = interaction.options.getString('description');
const emoji = interaction.options.getString('emoji');
const parsedEmoji = Util.parseEmoji(emoji);
if (role.position >= interaction.guild.me.roles.highest.position) {
const embed = new MessageEmbed()
.setColor('RED')
.setTitle('Error:')
.setDescription(`I can not add roles that are higher than mine`)
.setTimestamp()
.setFooter({ text: `Phantom Bot v${config.version}` });
return interaction.reply({ embeds: [embed], ephemeral: true });
}
ReactionRole.findOne({ guild_id: interaction.guild.id }, (err, settings) => {
if (err) {
const embed = new MessageEmbed()
.setColor('RED')
.setTitle('Error:')
.setDescription(`There was an error while adding the reaction role`)
.setTimestamp()
.setFooter({ text: `Phantom Bot v${config.version}` });
return interaction.reply({ embeds: [embed], ephemeral: true });
}
if (!settings) {
new ReactionRole({
guild_id: interaction.guild.id,
message: 0,
roles: {
[parsedEmoji.name]: [
role.id,
{
description: description,
id: parsedEmoji.id,
raw: emoji
}
]
}
}).save();
} else {
settings.roles[parsedEmoji.name] = [
role.id,
{
description: description,
id: parsedEmoji.id,
raw: emoji
}
]
ReactionRole.findOneAndUpdate({ guild_id: interaction.guild.id }, settings);
}
const embed = new MessageEmbed()
.setColor('PURPLE')
.setTitle('Reaction Added:')
.setDescription(`Role ${role}\nEmoji: ${emoji}`)
.setTimestamp()
.setFooter({ text: `Phantom Bot v${config.version}` });
interaction.reply({ embeds: [embed] });
});
Issue:
For some reason if the settings do exist in the else statement, it doesn't actually update it in the Mongoose database. It actually doesn't touch it at all. I've tried awaiting the ReactionRole.findOneAndUpdate but I got an error saying I couldn't await it.
How can I fix this?
Any help would be appreciated!
Fixed buy making the function an async, then it would allow await.

Categories