Unknown Interaction on All interactions - Discord.js v13 - javascript

All of a sudden I keep on getting this error on most interactions and my bot just sends `"Bot is thinking...".
[UnhandledRejection] DiscordAPIError: Unknown interaction
at RequestHandler.execute (/Users/main/Desktop/Discordbots/gamerscavern/node_modules/discord.js/src/rest/RequestHandler.js:349:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/Users/main/Desktop/Discordbots/gamerscavern/node_modules/discord.js/src/rest/RequestHandler.js:50:14)
at async SelectMenuInteraction.reply (/Users/main/Desktop/Discordbots/gamerscavern/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:98:5)
Example this help command. Which returns Unknown interaction on the interaction.update() part in the collector AND in the filter when another user interacts with it. I have no clue why this is happening. And as mentioned, it worked fine just a few hours ago.
Here is my code:
Help command:
const {
Client,
Message,
MessageEmbed,
MessageActionRow,
MessageSelectMenu,
} = require('discord.js');
module.exports = {
name: 'help',
description: 'List all of my commands or info about a specific command.',
aliases: ['commands'],
usage: '[command name]',
category: 'info',
cooldown: 3,
/**
*
* #param {Client} client
* #param {Message} message
* #param {String[]} args
*/
execute: async (client, message, args, prefix) => {
if (message.author.bot) return;
const data = [];
const { commands } = message.client;
const emojis = {
config: '⚙ī¸',
info: 'ℹī¸',
moderation: '🔨',
owner: '🔐',
utility: '🛠',
voice: 'đŸ—Ŗ',
welcoming: '👋',
};
if (!args[0]) {
const directories = [
...new Set(client.commands.map((cmd) => cmd.category)),
].filter((e) => e !== 'secrets' && e !== undefined);
const formatString = (str) =>
`${str[0].toUpperCase()}${str.slice(1).toLowerCase()}`;
const categories = directories.map((dir) => {
const getCommands = client.commands
.filter((cmd) => cmd.category === dir)
.map((cmd) => {
return {
name: cmd.name || 'There is no name',
description:
cmd.description ||
'There is no description for this command',
};
});
return {
directory: formatString(dir),
commands: getCommands,
};
});
const initialEmbed = new MessageEmbed()
.setTitle('Developer: Kev#1880')
.setDescription(
'~~———————————————~~\n** Links âžŧ ** [Invite](https://discord.com/api/oauth2/authorize?client_id=711371556504207423&permissions=8&scope=bot) | [Server](https://discord.gg/XkCTA88) | [Upvote](https://top.gg/bot/711371556504207423/vote) \n~~———————————————~~\n\n**Please choose a category in the dropdown menu**'
)
.setColor('#5787E8')
.setThumbnail(client.user.displayAvatarURL({ format: 'png' }))
.setFooter(
`Requested by: ${message.author.tag}`,
message.author.displayAvatarURL({ format: 'png' })
)
.setTimestamp();
const components = (state) => [
new MessageActionRow().addComponents(
new MessageSelectMenu()
.setCustomId('help-menu')
.setPlaceholder('Please select a category')
.setDisabled(state)
.addOptions(
categories.map((cmd) => {
return {
label: cmd.directory,
value: cmd.directory.toLowerCase(),
description: `Commands from ${cmd.directory} category`,
emoji:
emojis[cmd.directory.toLowerCase()] ||
null,
};
})
)
),
];
const initialMessage = await message.channel.send({
embeds: [initialEmbed],
components: components(false),
});
const filter = async (interaction) => {
if (interaction.user.id === message.author.id) {
return true;
}
interaction.reply({
content: `This is not your help menu, create your own with >help!`,
ephemeral: true,
});
return false;
};
const collector = initialMessage.createMessageComponentCollector({
filter,
componentType: 'SELECT_MENU',
time: 600000,
});
collector.on('collect', (interaction) => {
console.log(interaction);
const [directory] = interaction.values;
const category = categories.find(
(x) => x.directory.toLowerCase() === directory
);
const categoryEmbed = new MessageEmbed()
.setTitle(`${formatString(directory)} commands`)
.setDescription(
'~~———————————————~~\n** Links âžŧ ** [Invite](https://discord.com/api/oauth2/authorize?client_id=711371556504207423&permissions=8&scope=bot) | [Server](https://discord.gg/XkCTA88) | [Upvote](https://top.gg/bot/711371556504207423/vote) \n~~———————————————~~\n\n**Here are the list of commands**'
)
.setColor('#5787E8')
.addFields(
category.commands.map((cmd) => {
return {
name: `\`${cmd.name}\``,
value: cmd.description,
inline: true,
};
})
)
.setThumbnail(
client.user.displayAvatarURL({ format: 'png' })
)
.setFooter(
`Requested by: ${message.author.tag}`,
message.author.displayAvatarURL({ format: 'png' })
)
.setTimestamp();
interaction.update({
embeds: [categoryEmbed],
});
});
collector.on('end', () => {
const ranOut = new MessageEmbed()
.setColor('RED')
.setTitle('Oops!')
.setDescription(
'Interaction ran out of time! Please create a new help menu!'
)
.setThumbnail(
client.user.displayAvatarURL({ format: 'png' })
)
.setFooter(
`Requested by: ${message.author.tag}`,
message.author.displayAvatarURL({ format: 'png' })
)
.setTimestamp();
initialMessage.edit({
embeds: [ranOut],
components: components(true),
});
});
}
if (args[0]) {
const name = args[0].toLowerCase();
const command =
commands.get(name) ||
commands.find((c) => c.aliases && c.aliases.includes(name));
if (!command) {
return message.reply({
content: "that's not a valid command!",
});
}
// data.push(`**Name:** ${command.name}`);
if (command.aliases)
data.push(`**Aliases:** ${command.aliases.join(', ')}`);
if (command.description)
data.push(`**Description:** ${command.description}`);
if (command.nb) data.push(`**NB:** ${command.nb}`);
if (command.userPermissions)
data.push(
`**User Permissions:** \`${command.userPermissions.join(
', '
)}\``
);
if (command.botPermissions)
data.push(
`**Bot Permissions:** ${command.botPermissions
.map((perm) => {
return `\`${perm}\``;
})
.join(', ')}`
);
if (command.usage)
data.push(
`**Usage:** \`${prefix}${command.name} ${command.usage}\``
);
if (command.examples)
data.push(`**Examples:**
${command.examples
.map((example) => {
return `\`${prefix}${command.name} ${example}\``;
})
.join('\n')}
`);
data.push(`**Cooldown:** ${command.cooldown || 3} second(s)`);
const commandHelp = new MessageEmbed()
.setTitle(`Command: **${command.name}**`)
.setColor('#5787E8')
.setDescription(`${data.join('\n')}`)
.setFooter(
`Requested by: ${message.author.tag}`,
message.author.displayAvatarURL({ format: 'png' })
);
return message.reply({ embeds: [commandHelp] });
}
},
};
interactionCreate event:
const blacklist = require('../../models/blacklists.js');
const guildBlacklist = require('../../models/guildBlacklist.js');
const reactionRoles = require('../../models/reactionRoles.js');
module.exports = async (Discord, client, interaction) => {
//Slash Command Handling
if (interaction.isCommand()) {
// await interaction.deferReply();
//blacklists
const bl = await blacklist.findOne({ Client: client.user.id });
if (bl) {
if (bl.Users) {
if (bl.Users.includes(interaction.user.id)) return;
}
}
const gbl = await guildBlacklist.findOne({
Guild: interaction.guild.id,
});
if (gbl) {
if (gbl.Users) {
if (gbl.Users.includes(interaction.user.id)) return;
}
}
const cmd = client.slashCommands.get(interaction.commandName);
if (!cmd) return interaction.reply({ content: 'An error has occured' });
const args = [];
for (let option of interaction.options.data) {
if (option.type === 'SUB_COMMAND') {
if (option.name) args.push(option.name);
option.options?.forEach((x) => {
if (x.value) args.push(x.value);
});
} else if (option.value) args.push(option.value);
}
interaction.member = interaction.guild.members.cache.get(
interaction.user.id
);
if (!interaction.member.permissions.has(cmd.userPermissions || []))
return interaction.reply({
content: 'You do not have the permissions to use this command!',
ephemeral: true,
});
cmd.execute(client, interaction, args);
}
//Context Menu Handling
if (interaction.isContextMenu()) {
await interaction.deferReply();
const command = client.slashCommands.get(interaction.commandName);
if (command) command.execute(client, interaction);
}
//Reaction Roles Handling
if (interaction.isSelectMenu()) {
await interaction.deferReply();
const reactionPanel = await reactionRoles.findOne({
guildId: interaction.guildId,
'reactionPanels.customId': `${interaction.customId}`,
});
if (reactionPanel) {
//if (interaction.customId !== 'reaction-roles') return;
const roleId = interaction.values[0];
const role = interaction.guild.roles.cache.get(roleId);
if (!role) return;
const memberRoles = interaction.member.roles;
const hasRole = memberRoles.cache.has(roleId);
if (hasRole) {
memberRoles.remove(roleId);
interaction.followUp({
content: `${role.name} has been removed from you`,
ephemeral: true,
});
} else {
memberRoles.add(roleId);
interaction.followUp({
content: `${role.name} has been added to you`,
ephemeral: true,
});
}
}
}
};

What happened
If you do not reply or acknowledge the interaction in 3 seconds. There's a cooldown!
The user will see interaction failed and the reply gate is closed.
Solution
However, if you defer the reply and edit later, the gate will open until you update the defer or edit the reply.
Here's how to do it, and here's the documentation about it.
interaction.deferReply();
// Do some stuff that takes time right here...
interaction.editReply({ content: "replied" });
To answer your other question about the bot sending Bot is thinking...,
It happens when you defer without editing the reply after. It will stay like that until you do something.

Related

Discord V14 After typing report out it says: "Command Outdated."

const { SlashCommandBuilder, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, ChannelType, ComponentType } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('test')
.setDescription('Report a problem to admins or report a bot bug to me.')
.addSubcommand(subcommand => subcommand.setName('guild').setDescription('If there is a problem with the guild or any member, report it here.')
.addStringOption(option => option.setName('problem_with').setDescription('What is the problem with?')
.addChoices(
{ name: "Rules", value: 'rule' },
{ name: "User", value: 'user' },
{ name: "Channel", value: 'channel' },
{ name: "Voice", value: 'voice' },
{ name: "Role", value: 'role' },
{ name: "Other", value: 'other' }
).setRequired(true)
)
.addStringOption(option => option.setName('description').setDescription('Describe the problem.').setRequired(true))
.addStringOption(option => option.setName('description_2').setDescription('If you want to add more details, describe them here.'))
.addStringOption(option => option.setName('fix').setDescription('Do you have a fix? If so, describe it here.'))
)
.addSubcommand(subcommand => subcommand.setName('bot').setDescription('If there is a bug in the bot, report it to bot owner.')
.addStringOption(option => option.setName('problem_with').setDescription('What is the problem with?')
.addChoices(
{ name: "Command_error", value: 'commandError' },
{ name: "Event_error", value: 'eventError' },
{ name: "Language_error", value: 'languageError' },
{ name: "Command_feature", value: 'commandFeature' },
{ name: "Event_feature", value: 'eventFeature' },
{ name: "Other", value: 'otherError' }
).setRequired(true)
)
.addStringOption(option => option.setName('description').setDescription('Describe the problem.').setRequired(true))
.addStringOption(option => option.setName('description_2').setDescription('If you want to add more details, describe them here.'))
.addStringOption(option => option.setName('fix').setDescription('Do you have a fix? If so, describe it here.'))
),
async execute(interaction, client, config) {
try {
const problem_with = interaction.options.getString('problem_with');
const description = interaction.options.getString('description');
const description_2 = interaction.options.getString('description_2');
const fix = interaction.options.getString('fix');
const report = new EmbedBuilder()
.setDescription(description + '\n' + (description_2 ? description_2 : "-") + '\n\n**Fix:**\n' + (fix ? fix : "-"))
.setColor(0xFF0000)
.addFields({ name: 'Reported by ID:', value: `${interaction.user.id}`, inline: true })
.setTimestamp()
.setFooter({ text: `React with emoji to delete` })
.setAuthor({ name: `Reported by ${String(interaction.user.tag)}`, iconURL: interaction.user.displayAvatarURL() });
if (interaction.options.getSubcommand() === 'guild') {
report.setTitle('Guild Report about ' + problem_with);
if (client.settings.get(interaction.guild.id, "moderationChannel")) { channel = client.channels.cache.get(client.settings.get(interaction.guild.id, "moderationChannel")) } else { channel = interaction.guild.systemChannel }
if (channel) {
const s = await channel.send({ embeds: [report], fetchReply: true })
s.react('<:red_cross:1008725354296389723>')
await interaction.reply({ content: "Report has been sent to moderators", ephemeral: true })
} else {
const user = await client.users.fetch(interaction.guild.ownerId);
const s = await user.send({ embeds: [report], fetchReply: true })
s.react('<:red_cross:1008725354296389723>')
await interaction.reply({ content: "No admin channel found, server owner got the message", ephemeral: true })
}
}
if (interaction.options.getSubcommand() === 'bot') {
report.setTitle('Bot Bug Report' + '\n' + problem_with);
try {
const config = require('../../config.json')
require('dotenv').config(); var b_o_Id = process.env.botOwnerId;
if (config.botOwnerId === "botOwnerID") {
const user = await client.users.fetch(b_o_Id);
const m = await user.send({ embeds: [report], fetchReply: true })
m.react('<:red_cross:1008725354296389723>')
} else {
const user = await client.users.fetch(config.botOwnerId);
const m = await user.send({ embeds: [report], fetchReply: true })
m.react('<:red_cross:1008725354296389723>')
}
await interaction.reply({ content: "Report has been sent to bot owner", ephemeral: true })
} catch {
console.log("Unable to find a channel to send the report to.")
await interaction.reply({ content: "No bot owner found, unable to report anything", ephemeral: true })
}
}
} catch (error) {
console.log(error)
}
}
}
This here is my report command, when I do /report bot or /report guild and enter the following stuff then hit enter the SlashCommands in the event folder gives me a response saying: "Command outdated."
I really don't know how to fix this but I just want it to work so people can report me feedbacks or errors they are having when I want to launch my bot for a small amounts of people.

Interaction Channel MessageCollector, Discord.js

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

This interaction failed - Discord.js

I'm making a discord slash command nowplaying with save button in it and sent the current music playing in user's dm. i manage to create the buttons working but my problem is after clicking the button "Save Song" it says "This interaction failed" tho the buttons works it sent a embed of the current music playing. Can someone help me why it saying that error?
Node: v17.7.2
Discord: ^13.2.0
my InteractionCreate events for the button "Save Song"
const client = require("../index");
const { MessageEmbed } = require('discord.js');
const ee = require('../config.json');
client.on("interactionCreate", async (interaction) => {
// Slash Command Handling
if (interaction.isCommand()) {
await interaction.deferReply({ ephemeral: false }).catch(() => {});
const cmd = client.slashCommands.get(interaction.commandName);
if (!cmd)
return interaction.followUp({ content: "An error has occured " });
const args = [];
for (let option of interaction.options.data) {
if (option.type === "SUB_COMMAND") {
if (option.name) args.push(option.name);
option.options?.forEach((x) => {
if (x.value) args.push(x.value);
});
} else if (option.value) args.push(option.value);
}
interaction.member = interaction.guild.members.cache.get(interaction.user.id);
cmd.run(client, interaction, args);
}
// Context Menu Handling
if (interaction.isContextMenu()) {
await interaction.deferReply({ ephemeral: false });
const command = client.slashCommands.get(interaction.commandName);
if (command) command.run(client, interaction);
}
//Save Song button function
if (interaction.isButton()){
const queue = client.distube.getQueue(interaction.guildId);
switch (interaction.customId) {
case 'saveTrack': {
if (!queue || !queue.playing){
return interaction.followUp({ content: `No music currently playing. ❌`, ephemeral: true, components: [] });
} else {
const song = queue.songs[0];
const but_save = new MessageEmbed()
.setColor(ee.color)
.setTitle(client.user.username + " - Save Track")
.setThumbnail(client.user.displayAvatarURL())
.addField(`đŸŽļ Track`, `\`${song.name}\``)
.addField(`âŗ Duration`, `\`${song.formattedDuration}\``, true)
.addField(`🔗 URL`, `${song.url}`)
.addField(`㊗ Saved Server`, `\`${interaction.guild.name}\``)
.addField(`➡ Requested By`, `${song.user}`, true)
.setTimestamp()
.setFooter({ text: 'H_M Save Music!', iconURL: interaction.user.displayAvatarURL({ dynamic: true }) });
interaction.user.send({ embeds: [but_save ] }).then(() => {
interaction.followUp({ content: `✅ | I sent the name of the music via private message.`, ephemeral: true }).catch(e => { })
}).catch(error => {
interaction.followUp({ content: `❌ | Unable to send you private message.`, ephemeral: true }).catch(e => { })
});
}
}
}
}
});
and here is my nowplaying.js
const { MessageEmbed, MessageActionRow, MessageButton } = require('discord.js');
const ee = require('../../config.json');
const Format = Intl.NumberFormat();
const status = queue =>
`Volume: \`${queue.volume}%\` | Filters: \`${queue.filters.join(', ') || 'Off'}\` | Loop: \`${
queue.repeatMode ? (queue.repeatMode === 2 ? 'Playlist' : 'Song') : 'Off'
}\` | Autoplay: \`${queue.autoplay ? 'On' : 'Off'}\``
module.exports = {
name: "nowplaying",
description: "Shows the current song playing",
usage: "nowplaying",
run: async (client, interaction, args) => {
const queue = client.distube.getQueue(interaction);
const song = queue.songs[0];
const embed = new MessageEmbed()
.setColor(ee.color)
.setAuthor({name: 'Now playing...', iconURL: 'https://i.imgur.com/81ig9jl.jpg'})
.setDescription(`[${song.name}](${song.url})`)
.setThumbnail(song.thumbnail)
.addField("🌭 | Status", `${status(queue).toString()}`, false)
.addField('👀 | Listens', `${Format.format(song.views)}`, true)
.addField('👍 | Prefer', `${Format.format(song.likes)}`, true)
.addField('⌛ | Played', `${queue.formattedCurrentTime} / ${song.formattedDuration}`, true)
.addField('📩 | Download link', `[Click here](${song.streamURL})`, true)
.addField("👌 | Requested by",` ${song.user}`, true)
const saveButton = new MessageButton();
saveButton.setLabel('Save Song');
saveButton.setCustomId('saveTrack');
saveButton.setStyle('SUCCESS');
const row = new MessageActionRow().addComponents(saveButton);
interaction.followUp({embeds: [embed], components: [row] });
}
}
After you switched case to your id, you need to defer your interaction with await interaction.deferReply() also if you want it an ephemeral message there's option as await interaction.deferReply({ ephemeral: true }). This line should be awaited.

How to make when bot ask a question, he waiting for an answer and ask another question

I wanted to create my bot for economics, but I ran into a problem. What do I want to do: after writing one question, the bot waits for an answer and then asks another question and so on. Can someone help me with my problem? Currently I have something like this:
const config = require('../../config.json');
const { MessageEmbed } = require('discord.js');
const shopEconomy = require('../../database/shopEconomy');
module.exports = {
name: 'create-item',
aliases: [],
description: '',
run: async(client, message, args) => {
const items = require('../../items.json');
const item = items[Math.floor(Math.random() * items.length)];
const filter = response => {
return response.content.toLowerCase();
};
const embed = new MessageEmbed()
.setColor(`${config.correct}`)
.setAuthor({ name: `Item` })
.addFields(
{ name: `Name`, value: `---`}
)
return message.channel.send(item.question, { fetchReply: true, embeds: [embed] })
.then(() => {
message.channel.awaitMessages({ filter, max: 1, time: 10000, errors: ['time'] })
.then(async collected => {
const embed = new MessageEmbed()
.setColor(`${config.correct}`)
.setAuthor({ name: `Item` })
.addFields(
{ name: `Name`, value: `${collected.first()}`}
)
await shopEconomy.findOneAndUpdate(
{
guildID: message.guild.id,
},
{
name: `${collected.first()}`,
},
{
upsert: true,
}
);
return message.channel.send({ embeds: [embed] });
})
.catch(collected => {
const embed = new MessageEmbed()
.setColor(`${config.false}`)
.setDescription(`Timeout.`)
message.channel.send({ embeds: [embed] });
});
});
}
}
You almost got it, as you collect the message, send a reply and await messages again
//An Example of await messages
let questions = {
first_question: "Hello what is your name?",
second_question: "how old are you",
}
const filter = m => m.author.id === message.author.id
message.channel.send({content: `${questions.first_question}`}).then(async msg=>{
await msg.channel.awaitMessages({filter: filter, time: 60000, max:1 }).then(collected=>{
const msg1 = collected.first().content
message.channel.send({content: `${questions.second_question}`}).then(async msg=>{
await msg.channel.awaitMessages({filter: filter, time: 60000, max:1}).then(collected=>{
const msg2 = collected.first().content
return message.channel.send({content: `${questions.first_question}\nAns: ${msg1}\n${questions.second_question}\nAns: ${msg2}`})
})
})
})
})

Discord.js(v13) - Delete a channel with discord button

So I made a discord selection menu ticket that when I select that category it makes a channel and send a message with a button. The button is supposed to delete the channel when pressed, but it doesn't seem to work. I think I have found the error but I don't know how to fix it. It is probably easy to fix but I'm stuck.
The code: (I think the error is located in the end here)
} else if (Discord.MessageButton.customId === 'del') {
const channel = message.guild.channel
channel.delete();
const Discord = require("discord.js");
const { MessageSelectMenu, MessageActionRow } = require("discord.js");
module.exports = {
name: "ticket",
author: "Falcone",
run: async(client, message, args) => {
if (!message.member.permissions.has("ADMINISTRATOR")) return message.reply('You Dont Have the `ADMINISTRATOR` permision');
message.delete();
let embed = new Discord.MessageEmbed()
.setColor("RANDOM")
.setDescription(`Test`)
.setThumbnail(message.guild.iconURL({ dynamic: true }))
.setAuthor(message.guild.name, message.guild.iconURL({ dynamic: true }));
let painel = new MessageActionRow().addComponents( new MessageSelectMenu()
.setCustomId('menu')
.setPlaceholder('Test') // Mensagem estampada
.addOptions([
{
label: 'Support',
description: '',
emoji: '🙋‍♂ī¸',
value: '1',
},
{
label: 'Test',
description: '',
emoji: '⛔',
value: '2',
},
{
label: 'Test',
description: '',
emoji: '🤖',
value: '3',
}
])
);
message.channel.send({ embeds: [embed], components: [painel] }).then(msg => {
const filtro = (interaction) =>
interaction.isSelectMenu()
const coletor = msg.createMessageComponentCollector({
filtro
});
coletor.on('collect', async (collected) => {
let ticket = collected.values[0]
collected.deferUpdate()
if (ticket === "1") {
const embed = new Discord.MessageEmbed()
.setTitle('Ticket')
.setDescription('Hello there, \n The staff will be here as soon as possible mean while tell us about your issue!\nThank You!')
.setColor('GREEN')
.setTimestamp()
const del = new MessageActionRow()
.addComponents(
new Discord.MessageButton()
.setCustomId('del')
.setLabel('🗑ī¸ Delete Ticket!')
.setStyle('DANGER'),
);
message.guild.channels.create(`${collected.user.id}`, {
type : 'GUILD_TEXT',
permissionOverwrites : [
{
id : message.guild.id,
deny : ['VIEW_CHANNEL']
},
{
id : collected.user.id,
allow : ['VIEW_CHANNEL', 'SEND_MESSAGES', 'ATTACH_FILES']
}
]
}).then(async (msg) => {
msg.send({ embeds: [embed], components: [del] }).then(msg => msg.pin() );
})
} else if (Discord.MessageButton.customId === 'del') {
const channel = message.guild.channel
channel.delete();
}
})
});
}
}
MessageButton.customId is not a static property. That means it must be done on an instance, not the class. Something that you could try is this:
const msg = await message.channel.send({
content: "Which one?",
components: [
new Discord.MessageActionRow().addComponents([
new Discord.MessageButton().setLabel("Delete").setStyle("DANGER").setCustomId("DEL"), //delete button
new Discord.MessageButton().setLabel("Cancel").setStyle("DANGER").setCustomId("CAN") //cancel button
])
]
})
//Create button collector
const collector = msg.createMessageComponentCollector({
componentType: "BUTTON",
filter: (c) => c.member.id === msg.member.id,
max: 1
})
//Handle button click
collector.on("collect", i => {
if(i.customId === "CAN") return i.reply("Cancelled")
if(i.customId === "DEL") i.channel.delete() //or whatever channel you want to delete
})
Warning: I did not test this code. You can tell me any problems you have and I will try to modify this

Categories

Resources