Unable to define a variable - discord.js (v12) - discord.js

I'm trying to make a ticket system handled by the bot. Once a ticket channel is created, the bot will send a message and the person will have to choose an option.
The code is almost done, but I need some help with the channelCreated variable because I can't define it (the variable that tells the bot when a channel is created).
const Discord = require('discord.js');
const infoembedColor = "#4747f8"
const fs = require('fs')
const {
Message
} = require("discord.js");
module.exports = async(client, args, message) => {
console.log("\nJade - I am Online!\n")
client.user.setStatus('online')
client.user.setActivity('Calympia', {
type: 'WATCHING'
})
if (client.guilds.cache.find(guild => guild.name === "Calympia")) {
if (await channelCreated) {
const ticketEmbed = new Discord.MessageEmbed()
.setColor(infoembedColor)
.setTitle(`Welcome to Calympia's Support`)
.setDescription(`Welcome! Please specify a reason behind opening this ticket.`)
.addFields({
name: "Appeal for a mute or a ban",
value: "*Reply with* \`Appeal\`"
}, {
name: "Apply for Staff",
value: "*Reply with* \`Apply\`"
}, {
name: "Questions, Suggestions, Queries",
value: "*Reply with* \`Basic\`"
}, {
name: "Report a rule-breaker",
value: "*Reply with* \`Report\`"
}, {
name: "Anything else.",
value: "*Reply with* \`Other\`"
})
await channel.send({
embed: ticketEmbed
})
let ticketAppeal = ["appeal", "Appeal"];
let foundInText1 = false;
for (var i in ticketAppeal) {
if (message.content.toLowerCase().includes(ticketAppeal[i].toLowerCase())) foundInText1 = true;
}
if (foundInText1) {
await message.channel.send("Alright. 1")
}
let ticketApply = ["apply", "Apply", "want to become staff", "want to apply for staff", "want to apply"];
let foundInText2 = false;
for (var i in ticketApply) {
if (message.content.toLowerCase().includes(ticketApply[i].toLowerCase())) foundInText2 = true;
}
if (foundInText2) {
await message.channel.send("Alright. 2")
}
let ticketBasic = ["basic", "Basic", "question", "query", "queries", "suggest"];
let foundInText3 = false;
for (var i in ticketBasic) {
if (message.content.toLowerCase().includes(ticketBasic[i].toLowerCase())) foundInText3 = true;
}
if (foundInText3) {
await message.channel.send("Alright. 3")
}
let ticketReport = ["report", "Report"];
let foundInText4 = false;
for (var i in ticketReport) {
if (message.content.toLowerCase().includes(ticketReport[i].toLowerCase())) foundInText4 = true;
}
if (foundInText4) {
await message.channel.send("Alright. 4")
}
let ticketOther = ["other", "anything else"];
let foundInText5 = false;
for (var i in ticketOther) {
if (message.content.toLowerCase().includes(ticketOther[i].toLowerCase())) foundInText5 = true;
}
if (foundInText5) {
await message.channel.send("Alright. 5")
}
}
}
}

You could also just use something like !ticket <reason>.

Related

Args cannot read proprety of undefined ("0")

So basically I have that command that use modals to create giveaways but there is one line bothering me. It is right under the run: async line. I have been trying to search the discord documentation about a change that happened from v13 to v14 (yes this code uses discord.js v1.14.5) but I have found nothing. The error is the following: <rejected> TypeError: Cannot read properties of undefined (reading '0'). If you need anymore code, ask me (like the sub files or the rest of the code). Thanks in advance!
Code:
const {
ChannelType,
ButtonBuilder,
ActionRowBuilder,
ComponentType,
TextInputStyle,
TextInputBuilder,
ModalBuilder,
ButtonStyle,
ApplicationCommandOptionType,
} = require("discord.js");
const ems = require("enhanced-ms");
const start = require("./sub/start");
const pause = require("./sub/pause");
const resume = require("./sub/resume");
const end = require("./sub/end");
const reroll = require("./sub/reroll");
const list = require("./sub/list");
const edit = require("./sub/edit");
module.exports = {
name: "giveaway",
description: "Start a giveaway!",
type: 1,
id: "Giveaway",
options: [
{
name: "start",
description: "start a giveaway",
type: ApplicationCommandOptionType.Subcommand,
options: [
{
name: "channel",
description: "the channel to start the giveaway in",
type: ApplicationCommandOptionType.Channel,
channelTypes: [ChannelType.GuildText],
required: true,
},
],
},
{
name: "pause",
description: "pause a giveaway",
type: ApplicationCommandOptionType.Subcommand,
options: [
{
name: "message_id",
description: "the message id of the giveaway",
type: ApplicationCommandOptionType.String,
required: true,
},
],
},
{
name: "resume",
description: "resume a paused giveaway",
type: ApplicationCommandOptionType.Subcommand,
options: [
{
name: "message_id",
description: "the message id of the giveaway",
type: ApplicationCommandOptionType.String,
required: true,
},
],
},
{
name: "end",
description: "end a giveaway",
type: ApplicationCommandOptionType.Subcommand,
options: [
{
name: "message_id",
description: "the message id of the giveaway",
type: ApplicationCommandOptionType.String,
required: true,
},
],
},
{
name: "reroll",
description: "reroll a giveaway",
type: ApplicationCommandOptionType.Subcommand,
options: [
{
name: "message_id",
description: "the message id of the giveaway",
type: ApplicationCommandOptionType.String,
required: true,
},
],
},
{
name: "list",
description: "list all giveaways",
type: ApplicationCommandOptionType.Subcommand,
},
{
name: "edit",
description: "edit a giveaway",
type: ApplicationCommandOptionType.Subcommand,
options: [
{
name: "message_id",
description: "the message id of the giveaway",
type: ApplicationCommandOptionType.String,
required: true,
},
{
name: "add_duration",
description: "the number of minutes to add to the giveaway duration",
type: ApplicationCommandOptionType.Integer,
required: false,
},
{
name: "new_prize",
description: "the new prize",
type: ApplicationCommandOptionType.String,
required: false,
},
{
name: "new_winners",
description: "the new number of winners",
type: ApplicationCommandOptionType.Integer,
required: false,
},
],
},
],
permissions: {
DEFAULT_MEMBER_PERMISSIONS: "ManageMessages" // User permissions needed
},
/**
* #param {ChatInputCommandInteraction} interaction
*/
run: async (client, interaction, config, db, args, message) => {
const sub = args[0]?.toLowerCase();
//line above
let response;
//
if (sub === "start") {
if (!args[1]) return message.safeReply("Incorrect usage! Please provide a channel to start the giveaway in");
const match = message.guild.findMatchingChannels(args[1]);
if (!match.length) return message.safeReply(`No channel found matching ${args[1]}`);
return await runModalSetup(message, match[0]);
}
//
else if (sub === "pause") {
const messageId = args[1];
response = await pause(message.member, messageId);
}
//
else if (sub === "resume") {
const messageId = args[1];
response = await resume(message.member, messageId);
}
//
else if (sub === "end") {
const messageId = args[1];
response = await end(message.member, messageId);
}
//
else if (sub === "reroll") {
const messageId = args[1];
response = await reroll(message.member, messageId);
}
//
else if (sub === "list") {
response = await list(message.member);
}
//
else if (sub === "edit") {
const messageId = args[1];
if (!messageId) return message.safeReply("Incorrect usage! Please provide a message id");
return await runModalEdit(message, messageId);
}
//
else response = "Not a valid sub command";
await message.safeReply(response);
},
async interactionRun(interaction) {
const sub = interaction.options.getSubcommand();
let response;
//
if (sub === "start") {
const channel = interaction.options.getChannel("channel");
return await runModalSetup(interaction, channel);
}
//
else if (sub === "pause") {
const messageId = interaction.options.getString("message_id");
response = await pause(interaction.member, messageId);
}
//
else if (sub === "resume") {
const messageId = interaction.options.getString("message_id");
response = await resume(interaction.member, messageId);
}
//
else if (sub === "end") {
const messageId = interaction.options.getString("message_id");
response = await end(interaction.member, messageId);
}
//
else if (sub === "reroll") {
const messageId = interaction.options.getString("message_id");
response = await reroll(interaction.member, messageId);
}
//
else if (sub === "list") {
response = await list(interaction.member);
}
//
else if (sub === "edit") {
const messageId = interaction.options.getString("message_id");
const addDurationMs = ems(interaction.options.getInteger("add_duration"));
if (!addDurationMs) {
return interaction.followUp("Not a valid duration");
}
const newPrize = interaction.options.getString("new_prize");
const newWinnerCount = interaction.options.getInteger("new_winners");
response = await edit(interaction.member, messageId, addDurationMs, newPrize, newWinnerCount);
}
//
else response = "Invalid subcommand";
await interaction.followUp(response);
},
};
//...
Command handler:
const client = require("../index");
const { PermissionsBitField, Routes, REST, User } = require('discord.js');
const fs = require("fs");
const colors = require("colors");
module.exports = (client, config) => {
console.log("0------------------| Application commands Handler:".blue);
let commands = [];
// Slash commands handler:
fs.readdirSync('./commands/slash/').forEach((dir) => {
console.log('[!] Started loading slash commands...'.yellow);
const SlashCommands = fs.readdirSync(`./commands/slash/${dir}`).filter((file) => file.endsWith('.js'));
for (let file of SlashCommands) {
let pull = require(`../commands/slash/${dir}/${file}`);
if (pull.name, pull.description, pull.type == 1) {
client.slash_commands.set(pull.name, pull);
console.log(`[HANDLER - SLASH] Loaded a file: ${pull.name} (#${client.slash_commands.size})`.brightGreen);
commands.push({
name: pull.name,
description: pull.description,
type: pull.type || 1,
options: pull.options ? pull.options : null,
default_permission: pull.permissions.DEFAULT_PERMISSIONS ? pull.permissions.DEFAULT_PERMISSIONS : null,
default_member_permissions: pull.permissions.DEFAULT_MEMBER_PERMISSIONS ? PermissionsBitField.resolve(pull.permissions.DEFAULT_MEMBER_PERMISSIONS).toString() : null
});
} else {
console.log(`[HANDLER - SLASH] Couldn't load the file ${file}, missing module name value, description, or type isn't 1.`.red)
continue;
};
};
});
// User commands handler:
fs.readdirSync('./commands/user/').forEach((dir) => {
console.log('[!] Started loading user commands...'.yellow);
const UserCommands = fs.readdirSync(`./commands/user/${dir}`).filter((file) => file.endsWith('.js'));
for (let file of UserCommands) {
let pull = require(`../commands/user/${dir}/${file}`);
if (pull.name, pull.type == 2) {
client.user_commands.set(pull.name, pull);
console.log(`[HANDLER - USER] Loaded a file: ${pull.name} (#${client.user_commands.size})`.brightGreen);
commands.push({
name: pull.name,
type: pull.type || 2,
});
} else {
console.log(`[HANDLER - USER] Couldn't load the file ${file}, missing module name value or type isn't 2.`.red)
continue;
};
};
});
// Message commands handler:
fs.readdirSync('./commands/message/').forEach((dir) => {
console.log('[!] Started loading message commands...'.yellow);
const UserCommands = fs.readdirSync(`./commands/message/${dir}`).filter((file) => file.endsWith('.js'));
for (let file of UserCommands) {
let pull = require(`../commands/message/${dir}/${file}`);
if (pull.name, pull.type == 3) {
client.message_commands.set(pull.name, pull);
console.log(`[HANDLER - MESSAGE] Loaded a file: ${pull.name} (#${client.user_commands.size})`.brightGreen);
commands.push({
name: pull.name,
type: pull.type || 3,
});
} else {
console.log(`[HANDLER - MESSAGE] Couldn't load the file ${file}, missing module name value or type isn't 2.`.red)
continue;
};
};
});
// Registering all the application commands:
if (!config.Client.ID) {
console.log("[CRASH] You need to provide your bot ID in config.js!".red + "\n");
return process.exit();
};
const rest = new REST({ version: '10' }).setToken(config.Client.TOKEN || process.env.TOKEN);
(async () => {
console.log('[HANDLER] Started registering all the application commands.'.yellow);
try {
await rest.put(
Routes.applicationCommands(config.Client.ID),
{ body: commands }
);
console.log('[HANDLER] Successfully registered all the application commands.'.brightGreen);
} catch (err) {
console.log(err);
}
})();
};
InteractionCreate.js:
const { EmbedBuilder } = require("discord.js");
const client = require("../../index");
const config = require("../../config/config.js");
const { QuickDB } = require("quick.db");
const db = new QuickDB();
module.exports = {
name: "interactionCreate"
};
client.on('interactionCreate', async (interaction) => {
if (interaction.isChatInputCommand()) {
const command = client.slash_commands.get(interaction.commandName);
if (!command) return;
try {
command.run(client, interaction, config, db);
} catch (e) {
console.error(e)
};
};
if (interaction.isUserContextMenuCommand()) { // User:
const command = client.user_commands.get(interaction.commandName);
if (!command) return;
try {
command.run(client, interaction, config, db);
} catch (e) {
console.error(e)
};
};
if (interaction.isMessageContextMenuCommand()) { // Message:
const command = client.message_commands.get(interaction.commandName);
if (!command) return;
try {
command.run(client, interaction, config, db);
} catch (e) {
console.error(e)
};
};
if (interaction.isModalSubmit()) { // Modals:
const modal = client.modals.get(interaction.customId);
if (!modal) return interaction.reply({
embeds: [
new EmbedBuilder()
.setDescription('Something went wrong... Probably the Modal ID is not defined in the modals handler.')
.setColor('Red')
],
ephemeral: true
});
try {
modal.run(client, interaction, config, db);
} catch (e) {
console.error(e)
};
}
});

discord interaction.deferUpdate() is not a function

I'm creating a message with buttons as reaction roles but do the reaction role handling in another file so it stays loaded after a reset but it either says "interaction.deferUpdate() is not a function, or in discord it says "this interaction failed" but it gave/removed the role
my code for creating the message:
const { ApplicationCommandType, ActionRowBuilder, ButtonBuilder, EmbedBuilder } = require('discord.js');
module.exports = {
name: 'role',
description: "reactionroles",
cooldown: 3000,
userPerms: ['Administrator'],
botPerms: ['Administrator'],
run: async (client, message, args) => {
const getButtons = (toggle = false, choice) => {
const row = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setLabel('member')
.setCustomId('member')
.setStyle(toggle == true && choice == 'blue' ? 'Secondary' : 'Primary')
.setDisabled(toggle),
new ButtonBuilder()
.setLabel('member2')
.setCustomId('member2')
.setStyle(toggle == true && choice == 'blue' ? 'Secondary' : 'Primary')
.setDisabled(toggle),
);
return row;
}
const embed = new EmbedBuilder()
.setTitle('Wähle eine rolle')
.setDescription('Wähle die rolle, die du gern haben möchtest')
.setColor('Aqua')
message.channel.send({ embeds: [embed], components: [getButtons()] })
.then((m) => {
const collector = m.createMessageComponentCollector();
collector.on('collect', async (i) => {
if (!i.isButton()) return;
await i.deferUpdate();
});
});
}
};
code for the reaction role:
const fs = require('fs');
const chalk = require('chalk')
var AsciiTable = require('ascii-table')
var table = new AsciiTable()
const discord = require("discord.js");
table.setHeading('Events', 'Stats').setBorder('|', '=', "0", "0")
module.exports = (client) => {
client.ws.on("INTERACTION_CREATE", async (i) => {
let guild = client.guilds.cache.get('934096845762879508');
let member = await guild.members.fetch(i.member.user.id)
let role = guild.roles.cache.find(role => role.name === i.data.custom_id);
if (!member.roles.cache.has(role.id)) {
member.roles.add(role);
} else {
member.roles.remove(role);
}
return i.deferUpdate()
})
};
The client.ws events give raw data (not discord.js objects), so the .deferUpdate() method doesn't exist there. You should be using client.on("interactionCreate")
client.on("interactionCreate", async (i) => {
// ...
return i.deferUpdate()
})

Select Menu message collector returns interaction has already been acknowledged when ran twice

The command that I'm trying to do this with is a help command with multiple sub-menu's like the FM-bot.
Whenever I run my command twice, it always returns Interaction has already been acknowledged..
You have to select one of the sub-menus though first for this to happen, otherwise the command loads fine.
Here's the code for the command:
const categories = [
{
label: `AniList Commands`,
description: `Show's you the AniList commands`,
id: 'anilist',
commandFolder: "anilist",
color: '#0099ff',
filterFn: (x) => x.endsWith(".js")
},
{
label: `General Commands`,
description: `Show's you the general commands`,
id: 'general',
commandFolder: "general",
color: '#ea9e07',
filterFn: (x) => x.endsWith(".js") && x != "help.js" && x != "birthday.js"
},
{
label: `Hentai Commands`,
description: `Show's you the Hentai commands`,
id: 'hentai',
commandFolder: "hentai",
color: '#fb2347',
filterFn: (x) => x.endsWith(".js")
}
]
function parseCategory(category) {
const commandFiles = fs.readdirSync(path.join(__dirname, `../${category.commandFolder}`)).filter(category.filterFn);
const commands = [];
for (const file of commandFiles) {
const command = require(`../${category.commandFolder}/${file}`);
if (command.name && command.description && command.type) {
commands.push({ name: command.name, description: command.description });
}
}
return commands;
}
const row = new MessageActionRow()
.addComponents(
new MessageSelectMenu()
.setCustomId(`1`)
.setPlaceholder(`Select one of the available categories`)
.addOptions(categories.map(category => {
return {
label: category.label,
description: category.description,
value: category.id
}
}))
)
const embed = new MessageEmbed()
.setTitle(`Here are all the bot commands`)
.setDescription(`Select one of the command categories using the dropdown menu.`)
await message.channel.send({ content: ` `, embeds: [embed], components: [row] })
let categoryContents = {};
for (const category of categories) {
categoryContents[category.id] = parseCategory(category)
}
let categoryEmbeds = {};
for (const category of categories) {
const commands = categoryContents[category.id];
if (commands.length > 0) {
const embed = new MessageEmbed()
.setTitle(`${category.label}`)
.setColor(category.color)
.setFooter(`${commands.length} commands in this category`)
.setTimestamp();
for (const command of commands) {
embed.addField(`${process.env.prefix}${command.name}`, `${command.description}`);
}
categoryEmbeds[category.id] = embed;
}
}
let collector = message.channel.createMessageComponentCollector({
componentType: `SELECT_MENU`,
idle: 10_000,
});
collector.on(`collect`, async (collected) => {
let value = collected.values[0];
await collected.update({ embeds: [categoryEmbeds[value]] });
})
Any help would be appreciated!

Discord js - Ticket system

TICKET PROBLEM
When I reopen the ticket and want to close it again, the "interaction.channel.edit" function is not working, why?
There are no errors, version v13
When I close my ticket before reopening, everything is fine
//Now I am writing a sample message because they are stating that I wrote the code alone
const client = require("../index");
const { createTranscript } = require('discord-html-transcripts');
const { MessageEmbed, MessageActionRow, MessageButton, Message } = require("discord.js");
client.on("interactionCreate", async (interaction) => {
// Slashe
if (interaction.isCommand()) {
await interaction.deferReply({ ephemeral: false }).catch((error) => { console.log(error)});
const cmd = client.slashCommands.get(interaction.commandName);
if (!cmd)
return interaction.followUp({ content: "Wystapil jakis blad!" });
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
if (interaction.isContextMenu()) {
await interaction.deferReply({ ephemeral: false });
const command = client.slashCommands.get(interaction.commandName);
if (command) command.run(client, interaction);
}
// Buttony
if(interaction.isButton()) {
await interaction.deferUpdate()
if(interaction.customId === 'verify') {
let error = 0
const roleAdd = interaction.guild.roles.cache.get('949702807517265930')
const roleRemove = interaction.guild.roles.cache.get('949702776508792864')
if(!interaction.guild.me.permissions.has('ADMINISTRATOR')) {
const channel = interaction.guild.channels.cache.get("949716268146131066")
const embed = new MessageEmbed()
.setColor('RED')
.setTitle("ERROR")
.setDescription("Nie posiadam permissji potrzebnych do weryfikacji!")
.setTimestamp();
error = 1
channel.send({ embeds:[embed]});
}
if(interaction.guild.me.roles.highest.position <= roleAdd.position){
const channel = interaction.guild.channels.cache.get("949716268146131066")
const embed = new MessageEmbed()
.setColor('RED')
.setTitle("ERROR")
.setDescription("Moja rola jest niżej niż rola, którą dodaje podczas weryfikacji!")
.setTimestamp();
error = 1
channel.send({ embeds:[embed]});
}
if(interaction.guild.me.roles.highest.position <= roleRemove.position){
const channel = interaction.guild.channels.cache.get("949716268146131066")
const embed = new MessageEmbed()
.setColor('RED')
.setTitle("ERROR")
.setDescription("Moja rola jest niżej niż rola, którą zabieram podczas weryfikacji")
.setTimestamp();
error = 1
channel.send({ embeds:[embed]});
}
if(error > 0){
interaction.guild.members.cache.get("613438379174133770").send("Błąd podczas weryfikacji!")
return interaction.member.send("Wystąpił błąd podczas weryfikacji!");
}
await interaction.member.roles.add(roleAdd)
await interaction.member.roles.remove(roleRemove)
interaction.member.send("Pomyślnie zweryfikowano!")
}if(interaction.customId === 'ticket-open'){
if(interaction.guild.channels.cache.find(ch => ch.topic == interaction.user.id)) {
return interaction.followUp({
content: `Posiadasz już ticket!`,
ephemeral: true
})}
interaction.guild.channels.create(`Ticket-${interaction.user.username}`, {
parent: '949978511324635136',
permissionOverwrites: [{
id: interaction.user.id,
allow: ['VIEW_CHANNEL', 'SEND_MESSAGES']
},
{
id: '949701839560011797',
deny: ['VIEW_CHANNEL', 'SEND_MESSAGES']
},
{
id: client.user.id,
allow: ['VIEW_CHANNEL', 'SEND_MESSAGES']
}],
topic: interaction.user.id
})
.then(async(tick) => {
interaction.followUp({
content: `Ticket otworzony <#${tick.id}>`,
ephemeral: true
})
const tickEmbed = new MessageEmbed()
.setColor('GREEN')
.setFooter({
text: `${interaction.user.username} ${new Date().getFullYear()}`,
iconURL: interaction.user.displayAvatarURL({ dynamic: true })
})
.setTitle("Ticket")
.setDescription(`**Otworzyłeś/aś ticket, poczekaj cierpliwie, aż ktoś z administracji Cie obsłuży, nie pinguj oraz zachowaj kulturę na tickecie**`);
const closeButton = new MessageButton()
.setCustomId("close-button")
.setLabel("Zamknij")
.setEmoji("🔒")
.setStyle("SECONDARY");
const row = new MessageActionRow()
.setComponents(closeButton);
tick.send({
content: `Cześć <#${interaction.user.id}>, administracja za chwilę Cie obsłuży <#&949982338031423541>`,
embeds: [tickEmbed],
components: [row]
})
})
} if(interaction.customId === 'close-button'){
if(interaction.channel.name.includes(`zamkniety`)) return interaction.followUp({ content: 'Ticket jest już zamknięty!', ephemeral: true });
const buttonTak = new MessageButton()
.setCustomId('close-tak')
.setLabel('Zamknij')
.setStyle('SECONDARY')
const buttonNie = new MessageButton()
.setCustomId('close-nie')
.setLabel('Anuluj')
.setStyle('DANGER')
const raw = new MessageActionRow()
.setComponents([buttonTak, buttonNie])
interaction.channel.send({
content:'Czy napewno chcesz zamknąć ticket?',
components: [raw]
})
} if(interaction.customId === 'close-tak'){
const usd = interaction.guild.members.cache.get(interaction.channel.topic)
const name = usd.user.username
interaction.channel.edit({
name: "zamkniety",
permissionOverwrites: [{
id: interaction.channel.topic,
deny: ['SEND_MESSAGES', 'VIEW_CHANNEL']
}, {
id: '949701839560011797',
deny: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
}, {
id: client.user.id,
allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
}],
})
const message = await interaction.channel.messages.fetch(interaction.message.id).catch(() => null);
if (message) {
interaction.message.delete()
}
const embed = new MessageEmbed()
.setDescription(`Ticket zamknięty przez <#${interaction.user.id}>`)
interaction.channel.send({embeds:[embed]})
setTimeout(() => {
const embed2 = new MessageEmbed()
.setDescription(`\`\`\`System kontroli ticketów po zamknięciu\`\`\``)
.setColor('YELLOW');
const buttonReopen = new MessageButton()
.setCustomId("reopenButton")
.setLabel("Otworz")
.setEmoji('🔓')
.setStyle('SECONDARY')
const buttonTranscript = new MessageButton()
.setCustomId("transcriptButton")
.setLabel("Transcript")
.setEmoji('📝')
.setStyle('SECONDARY')
const buttonDelete = new MessageButton()
.setCustomId("deleteButton")
.setLabel("Usun")
.setEmoji('⛔')
.setStyle('SECONDARY')
const row = new MessageActionRow()
.setComponents([ buttonTranscript, buttonReopen, buttonDelete])
interaction.channel.send({
embeds:[embed2],
components: [row]
})
}, 500)
} if(interaction.customId === 'close-nie'){
const message = await interaction.channel.messages.fetch(interaction.message.id).catch(() => null);
if (message) {
interaction.message.delete()
}
} if(interaction.customId === 'reopenButton') {
const usd = interaction.guild.members.cache.get(interaction.channel.topic)
const name = usd.user.username
interaction.channel.edit({
permissionOverwrites: [{
id: interaction.channel.topic,
allow: ['SEND_MESSAGES', 'VIEW_CHANNEL']
}, {
id:'949701839560011797' ,
deny: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
}, {
id: client.user.id,
allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
}],
name: `ticket`
})
const embed = new MessageEmbed()
.setDescription(`Ticket został ponownie otworzony przez <#${interaction.user.id}> (${interaction.user.username})`)
.setColor('GREEN')
interaction.channel.send({embeds:[embed]})
const message = await interaction.channel.messages.fetch(interaction.message.id).catch(() => null);
if (message) {
interaction.message.delete()
}
}
// } if(interaction.customId === 'transcriptButton'){
// interaction.channel.send({ content: "Tworzenie zapisu..." })
// const user = await client.users.fetch(interaction.channel.topic)
// const transcript = await createTranscript(interaction.channel, {
// limit: -1,
// fileName: `ticket-${interaction.channel.topic}.html`,
// returnBuffer: false,
// })
// client.channels.cache.get("950383700904931368").send({
// files: [transcript]
// }).then(() => {
// interaction.channel.delete()
// })
// }
}
});

How wait a "Array for each" function?

I got a little problem with synchronous/asynchronous system in the function "Array.foreach".
I don't know how to force my code to wait its end.
I tried to use await/async system but my code did not wait the code in "async responseDB =>".
This is my class:
...
let responsesDTO = [];
await Array.prototype.forEach.call(await searchResponsesByQuestionAndUserId(questions[cpt].idquestion, idUser), async responseDB => {
if(responseDB !== undefined){
const responseDTO = {
response_id:0,
response_text:"",
response_type:""
}
const responseEntity = await searchResponseByResponseId(responseDB.response_id);
responseDTO.response_id = responseDB.response_id;
responseDTO.response_text= responseEntity.text;
responseDTO.response_type= responseDB.type;
responsesDTO.push(responseDTO);
}
});
questionResponse.responses=responsesDTO;
questionResponses[cpt]=questionResponse;
}
Could you help me please? Thanks in advance.
I had to mock your async functions. However, the relevant part is to use for..of instead of forEach
async function searchResponsesByQuestionAndUserId() {
let responsesDB = [];
for (let i = 0; i < 10; i++) {
responsesDB.push({
response_id: parseInt(1000 * Math.random(), 10),
type: 'whatever ' + i
});
}
return new Promise((res) => {
window.setTimeout(() => {
res(responsesDB);
}, 1500);
});
}
async function searchResponseByResponseId(response_id) {
return new Promise((res) => {
window.setTimeout(() => {
res({
text: 'text for response ' + response_id
});
}, 300);
});
}
async function getResponsesDTO() {
let responsesDTO = [],
responsesDB = await searchResponsesByQuestionAndUserId();
for (let responseDB of responsesDB) {
if (responseDB === undefined) {
continue;
}
let responseDTO = {
response_id: 0,
response_text: "",
response_type: ""
},
responseEntity = await searchResponseByResponseId(responseDB.response_id);
responseDTO.response_id = responseDB.response_id;
responseDTO.response_text = responseEntity.text;
responseDTO.response_type = responseDB.type;
responsesDTO.push(responseDTO);
console.log({responseDTO});
}
return responsesDTO;
}
getResponsesDTO().then(responsesDTO => {
console.log(responsesDTO);
});

Resources