discord.js reset menu on selection - javascript

So currently I'm making a ticket system which runs when a topic is selected via menu. However, the selection can't be undone automatically. Is there any way?
So I mean when I select the Bug topic and after the ticket being created, the select menu don't go back to Please select(The light letters) but I want to make that happen.
-- sorry for my poor english skills
+)
Currently when the menu is selected, we get input via modal and makes the ticket.
So
import Modal, { TextInputComponent } from '../../structures/Modal.js';
import { TextInputStyle } from 'discord-api-types/v9';
export const id = 'ticket-type';
function makeModel(type) {
return placeholders[type](new Modal()
.setCustomId('create-ticket')
.setTitle('티켓 만들기'));
}
const placeholders = {
report: (modal) => modal.addComponents(
new TextInputComponent()
.setCustomId('report')
.setLabel('신고할 사람의 Minecraft IGN(닉네임)을 작성해주세요.')
.setPlaceholder('예시: komq')
.setRequired(true)
.setMaxLength(16),
new TextInputComponent()
.setCustomId('reason')
.setLabel('위반된 규칙을 써주세요.')
.setPlaceholder('예시: 핵 사용')
.setRequired(true)
.setMaxLength(30),
),
feedback: (modal) => modal.addComponents(new TextInputComponent()
.setCustomId('feedback')
.setLabel('해당 서버에게 줄 피드백 내용을 작성해주세요.')
.setPlaceholder('예시: 이 미니게임에 이런 게 있었다면 좋겠어요.')
.setRequired(true)
.setMinLength(5)
.setMaxLength(500)
.setStyle(TextInputStyle.Paragraph)),
bug_report: (modal) => modal.addComponents(new TextInputComponent()
.setCustomId('bug_report')
.setLabel('발견한 버그를 써주세요. 영상 등의 첨부 자료가 있으면 더 좋습니다.')
.setPlaceholder('예시: 이 미니게임에서 특정 행동을 하면 블록이 파괴됩니다.')
.setRequired(true)
.setMinLength(5)
.setMaxLength(500)
.setStyle(TextInputStyle.Paragraph)),
};
export async function onRun(menu) {
await makeModel(menu.values[0]).sendToInteraction(menu);
}
and after the input,
import { clientId, ticketCategoryId, ticketPingRoleId } from '../../constants/config.js';
import { MessageActionRow, MessageButton, MessageEmbed, Permissions } from 'discord.js';
import getTheme from '../../constants/themes.js';
export const id = 'create-ticket';
export const closeTicketRow = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId('close-ticket')
.setLabel('티켓 닫기')
.setEmoji('🔒')
.setStyle('DANGER'),
);
const types = {
feedback: '피드백', bug_report: '버그 신고', report: '신고',
};
export async function onRun(ticket) {
const category = await ticket.guild.channels.fetch(ticketCategoryId);
const type = Object.keys(types).find((t) => ticket.getValue(t));
const channel = await category.createChannel(
'요청 ' + (Math.random() + 1).toString(36).substring(7), {
type: 'GUILD_TEXT',
topic: ticket.member.id,
permissionOverwrites: [
{
id: ticket.guild.roles.everyone.id,
deny: [Permissions.FLAGS.VIEW_CHANNEL],
},
{
id: ticket.member.id,
allow: [Permissions.FLAGS.VIEW_CHANNEL],
},
{
id: clientId,
allow: [Permissions.FLAGS.VIEW_CHANNEL],
},
],
},
);
ticket.reply({ content: '티켓을 제작했습니다!', ephemeral: true });
const embed = new MessageEmbed()
.setColor(getTheme('primary'))
.addField('채널', `<#${channel.id}>`)
.setAuthor({ name: ticket.member.user.tag, iconURL: ticket.member.user.displayAvatarURL() })
.setTimestamp()
.addField('유형', types[type]);
let send = ticket.getValue(type);
if (type === 'report') {
send += '을(를) ' + ticket.getValue('reason') + '(으)로 신고합니다.';
} else {
send = '```' + send + '```';
}
await channel.send({ embeds: [embed], components: [closeTicketRow] });
await channel.send(`<#&${ticketPingRoleId}>,\n${send}`);
}
I couldn't find any function to set the selected menu to default. So, I would be thankful if you give me the function and where should I run that.

Related

Discord.js SyntaxError: Cannot use import statement outside a module

I am trying to import consts from the second file into the first file so the embed can use those imports to send the message
File one:
module.exports = {
data: {
name: "GT1",
},
async execute(interaction, client, message) {
//const {a1, a2, a3} = require('./src/components/modals/GeneralTicket');
import {a1, a2, a3} from './src/components/modals/GeneralTicket.js'
// const a1 = interaction.fields.getTextInputValue("a1");
// const a2 = interaction.fields.getTextInputValue("a2");
// const a3 = interaction.fields.getTextInputValue("a3");
const embed = new EmbedBuilder()
.setColor(0x0099ff)
.setTitle("General Support Ticket ")
.setTimestamp()
.addFields(
{ name: "IGN:", value: `${a1}` },
{ name: "What is your Ticket related to:", value: `${a2}` },
{ name: "Brief summary:", value: `${a3}` }
);
createdChannel.send({
embeds: [embed],
ephemeral: true,
});
},
};
File two:
module.exports = {
data: {
name: `GeneralTicket`
},
async execute(interaction, client, message) {
client.on('interactionCreate', (modalSubmit) => {
if (!modalSubmit.isModalSubmit()) return;
const a1 = interaction.fields.getTextInputValue('a1');
const a2 = interaction.fields.getTextInputValue('a2');
const a3 = interaction.fields.getTextInputValue('a3');
const embed = new EmbedBuilder()
.setColor(0x0099FF)
.setTitle('General Support Ticket ')
.setTimestamp()
.addFields(
{ name: 'IGN:', value: `${a1}` },
{ name: 'What is your Ticket related to:', value: `${a2}`},
{ name: 'Brief summary:', value: `${a3}`});
const row = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId('GT1')
.setLabel(`Submit`)
.setStyle(ButtonStyle.Success)
.setDisabled(false),
);
modalSubmit.reply({ embeds: [embed] , ephemeral: true, components: [row], content: "To submit your ticket click `Submit` to cancel click `Dismiss Message`." });
});
},
};
My error with import:
SyntaxError: Cannot use import statement outside a module
I have tried both of these methods and still could not get it to work
import {a1, a2, a3} from './src/components/modals/GeneralTicket.js'
const { a1, a2, a3 } = require("./src/components/modals/GeneralTicket");
That's not how imports work in Javascript. What you're doing is importing variables from a function that hasn't even been called yet. Imports need to be at the top of the file, and the const x = require('x') syntax is correct. You can't do what you want the way you're doing it, but I'm sure there's another way. Unfortunately without knowledge of what you want and more code, I can't help.

TypeError [INVALID_TYPE]: Supplied data.type is not a valid MessageComponentType - Discord.js

hey im trying to make a slashCommand that generate random pics with button..
so when a user use the command it will sent an embed with button and then the button when a user clicked that, the embed will edited and load another picture
but It seems i was doing it wrong..
Node: v17.7.2
Discord.js: 13.2.0
here is my code
const { MessageEmbed, MessageActionRow, MessageButton } = require('discord.js');
const superagent = require('superagent');
const ee = require("../../config.json");
module.exports = {
name: 'waifu',
description: 'Give you a random anime waifus pics',
run: async (client, interaction, args) => {
let { body } = await superagent.get(`https://api.waifu.pics/sfw/waifu`);
const msg = await interaction.followUp({
embeds: [
new MessageEmbed()
.setColor(ee.color)
.setTitle("Waifu 😳")
.setImage(body.url)
.setTimestamp()
],
components: [
new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId('nextWaifu')
.setLabel('More Waifu')
.setStyle('SUCCESS')
)
],
fetchReply: true
});
let embed = msg.embeds
embed.color = ee.color;
embed.image = body.url;
let components = msg.components
return msg.edit({ embeds: [embed], components: [components], fetchReply: true });
}
}

Error [INTERACTION_ALREADY_REPLIED]: The reply to this interaction has already been sent or deferred. Ticket System

I am making a ticket system, everything works fine except when I go onto a different account to test out what the ticket system looks like for the people using it, I try to react to the "Player Report", "Bug Report", etc... as seen in the code, it just says i am unable to use the buttons and then throws this error.
Full error:
C:\Users\wrigh\Documents\Discord Bots\Practice Bot - Copy\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:90
if (this.deferred || this.replied) throw new Error('INTERACTION_ALREADY_REPLIED');
^
Error [INTERACTION_ALREADY_REPLIED]: The reply to this interaction has already been sent or deferred.
at ButtonInteraction.reply (C:\Users\wrigh\Documents\Discord Bots\Practice Bot - Copy\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:90:46)
at C:\Users\wrigh\Documents\Discord Bots\Practice Bot - Copy\Events\Ticket\initialTicket.js:86:24
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async C:\Users\wrigh\Documents\Discord Bots\Practice Bot - Copy\Events\Ticket\initialTicket.js:79:9
at async Object.execute (C:\Users\wrigh\Documents\Discord Bots\Practice Bot - Copy\Events\Ticket\initialTicket.js:20:9) {
[Symbol(code)]: 'INTERACTION_ALREADY_REPLIED'
Ticket.js Code:
const { MessageEmbed, CommandInteraction, MessageActionRow, MessageButton } = require("discord.js");
const { OPENTICKET } = require("../../Structures/config.json");
module.exports = {
name: "ticket",
description: "Setup your ticket",
permission: "ADMINISTRATOR",
/**
*
* #param {CommandInteraction} interaction
*/
async execute(interaction) {
const { guild } = interaction;
const Embed = new MessageEmbed()
.setAuthor(
guild.name + " | Ticketing System",
guild.iconURL({ dynamic: true})
)
.setDescription(
"Open a ticket to discuss any of the issues listed on the button."
)
.setColor("BLUE");
const Buttons = new MessageActionRow();
Buttons.addComponents(
new MessageButton()
.setCustomId("player")
.setLabel("Player Report")
.setStyle("PRIMARY")
.setEmoji("🏮"),
new MessageButton()
.setCustomId("bug")
.setLabel("Bug Report")
.setStyle("SECONDARY")
.setEmoji("✔"),
new MessageButton()
.setCustomId("other")
.setLabel("Other Report")
.setStyle("SUCCESS")
.setEmoji("❤"),
);
await guild.channels.cache
.get(OPENTICKET)
.send({ embeds: [Embed], components: [Buttons] });
interaction.reply({ content: "Done", ephemeral: true });
},
};
InitialTicket.js Code:
const { ButtonInteraction, MessageEmbed, MessageActionRow, MessageButton } = require("discord.js");
const DB = require("../../Structures/Handlers/Schemas/Ticket");
const { PARENTID, EVERYONEID } = require("../../Structures/config.json");
const Ticket = require("../../Structures/Handlers/Schemas/Ticket");
module.exports = {
name: "interactionCreate",
/**
*
* #param {ButtonInteraction} interaction
*/
async execute(interaction) {
if(!interaction.isButton()) return;
const { guild, member, customId } = interaction;
if (!["player", "bug", "other"].includes(customId)) return;
const ID = Math.floor(Math.random() * 90000) + 10000;
await guild.channels
.create(`${customId + "-" + ID}`, {
type: "GUILD_TEXT",
parent: PARENTID,
permissionOverwrites: [
{
id: member.id,
allow: ["SEND_MESSAGES", "VIEW_CHANNEL", "READ_MESSAGE_HISTORY"],
},
{
id: EVERYONEID,
deny: ["SEND_MESSAGES", "VIEW_CHANNEL", "READ_MESSAGE_HISTORY"],
},
],
})
.then(async (channel) => {
await DB.create({
GuildID: guild.id,
MemberID: member.id,
TicketID: ID,
ChannelID: channel.id,
Closed: false,
Locked: false,
Type: customId,
});
const Embed = new MessageEmbed()
.setAuthor(
`${guild.name} | Ticket: ${ID}`,
guild.iconURL({ dynamic: true })
)
.setDescription(
"Please wait patiently for a response from the Staff team, in the mean while, describe your issue in as much detail."
)
.setFooter("The buttons below are staff only buttons.");
const Buttons = new MessageActionRow();
Buttons.addComponents(
new MessageButton()
.setCustomId("close")
.setLabel("Save and close")
.setStyle("PRIMARY")
.setEmoji("💾"),
new MessageButton()
.setCustomId("lock")
.setLabel("lock")
.setStyle("SECONDARY")
.setEmoji("🔒"),
new MessageButton()
.setCustomId("unlock")
.setLabel("unlock")
.setStyle("SUCCESS")
.setEmoji("🔓"),
);
channel.send({
embeds: [Embed],
components: [Buttons],
});
await channel
.send({ content: `${member} here is your ticket` })
.then((m) => {
setTimeout(() => {
m.delete().catch(() => {});
}, 1 * 3000);
interaction.reply({
content: `${member} your ticket has been created: ${channel}`,
ephemeral: true
});
});
});
},
};
If you need to see any other parts of the bot please just ask, any help is rlly appreciated.
Any questions feel free to ask and I will try answer them to the best of my ability.
I am somewhat new to JavaScript and Node.js so please be patient with me.
Are these executed from the same button press/same interaction? If so, then set the reply that happens second to interaction.followUp() or interaction.editReply (depending on whether you want a second message (followUp) or to edit the existing message (editReply)).

Error [INTERACTION_ALREADY_REPLIED]: The reply to this interaction has already been sent or deferred

So I was currently working on the Ticket system and wanted to try it out.
When I click on the Player report Button, I get a reply (in ephemeral) saying: "No data was found in the database" and in the logs, it gives me the following error
Error [INTERACTION_ALREADY_REPLIED]: The reply to this interaction has already been sent or deferred.
This is the code:
const {
ButtonInteraction,
MessageEmbed,
MessageActionRow,
MessageButton
} = require("discord.js");
const DB = require("../../Structures/Schemas/Ticket");
const { PARENTID, EVERYONEID } = require("../../Structures/config.json")
module.exports = {
name: "interactionCreate",
/**
*
* #param {ButtonInteraction} interaction
*/
async execute(interaction){
if(!interaction.isButton) return;
const { guild, member, customId } = interaction;
if(!["player", "bug", "other"].includes(customId)) return;
const ID = Math.floor(Math.random() * 90000) + 10000;
await guild.channels.create(`${customId + "-" + ID}`, {
type: "GUILD_TEXT",
parent: PARENTID,
permissionOverwrites: [
{
id: member.id,
allow: ["SEND_MESSAGES", "VIEW_CHANNEL", "READ_MESSAGE_HISTORY"],
},
{
id: EVERYONEID,
deny: ["SEND_MESSAGES", "VIEW_CHANNEL", "READ_MESSAGE_HISTORY"],
},
],
}).then(async(channel) => {
await DB.create({
GuildID: guild.id,
MemberID: member.id,
TicketID: ID,
ChannelID: channel.id,
Closed: false,
Locked: false,
type: customId,
});
const Embed = new MessageEmbed()
.setAuthor(
`${guild.name} | Ticket: ${ID}`,
guild.iconURL({dynamic: true})
)
.setDescription("Please wait patiently for a response from the Staff team. In the meanwhile, describe your issue in as much detail as possible."
)
.setFooter("The buttons below are Staff Only Buttons.");
const Buttons = new MessageActionRow();
Buttons.addComponents(
new MessageButton()
.setCustomId("close")
.setLabel("Save & Close Ticket")
.setStyle("PRIMARY")
.setEmoji("💾"),
new MessageButton()
.setCustomId("lock")
.setLabel("Lock")
.setStyle("SECONDARY")
.setEmoji("🔒"),
new MessageButton()
.setCustomId("unlock")
.setLabel("Unlock")
.setStyle("SUCCESS")
.setEmoji("🔓")
);
channel.send({
embeds: [Embed],
components: [Buttons],
});
await channel
.send({content: `${member} here is your ticket.`})
.then((m) =>{
setTimeout(() =>{
m.delete().catch(() => {});
}, 1 * 5000);
});
interaction.reply({
content: `${member} your ticket has been created: ${channel}`,
ephemeral: true,
});
});
},
};
I have been looking for the solution but couldn't find anything.

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