Args cannot read proprety of undefined ("0") - discord

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

Related

Axios Spy not being called correct number of times in Jest

I have a React context I am testing that runs a single function to check for an application update. The checkForUpdate function looks like this:
async function checkForUpdate() {
if (isPlatform('capacitor')) {
const maintanenceURL =
'https://example.com/maintenance.json';
const updateURL =
'https://example.com/update.json';
try {
const maintanenceFetch: AxiosResponse<MaintanenceDataInterface> =
await axios.get(maintanenceURL);
console.log('maintain', maintanenceFetch);
if (maintanenceFetch.data.enabled) {
setUpdateMessage(maintanenceFetch.data.msg);
return;
}
const updateFetch: AxiosResponse<UpdateDataInterface> = await axios.get(
updateURL
);
console.log('updateFetch', updateFetch);
if (updateFetch.data.enabled) {
const capApp = await App.getInfo();
const capAppVersion = capApp.version;
console.log('Thi is a thinkg', capAppVersion);
if (isPlatform('android')) {
console.log('hi');
const { currentAndroid, majorMsg, minorMsg } = updateFetch.data;
const idealVersionArr = currentAndroid.split('.');
const actualVersionArr = capAppVersion.split('.');
if (idealVersionArr[0] !== actualVersionArr[0]) {
setUpdateMessage(majorMsg);
setUpdateAvailable(true);
return;
}
if (idealVersionArr[1] !== actualVersionArr[1]) {
setUpdateMessage(minorMsg);
setUpdateAvailable(true);
return;
}
} else {
const { currentIos, majorMsg, minorMsg } = updateFetch.data;
const idealVersionArr = currentIos.split('.');
const actualVersionArr = capAppVersion.split('.');
if (idealVersionArr[0] !== actualVersionArr[0]) {
setUpdateMessage(majorMsg);
setUpdateAvailable(true);
return;
}
if (idealVersionArr[1] !== actualVersionArr[1]) {
setUpdateMessage(minorMsg);
setUpdateAvailable(true);
return;
}
}
}
} catch (err) {
console.log('Error in checkForUpdate', err);
}
}
}
For some reason, in my test I wrote to test this, my axiosSpy only shows that it has been called 1 time instead of the expected 2 times. The console logs I posted for both get requests run as well. I cannot figure out what I am doing wrong.
Here is the test:
it.only('should render the update page if the fetch call to update bucket is enabled and returns a different major version', async () => {
const isPlatformSpy = jest.spyOn(ionicReact, 'isPlatform');
isPlatformSpy.mockReturnValueOnce(true).mockReturnValueOnce(true);
const appSpy = jest.spyOn(App, 'getInfo');
appSpy.mockResolvedValueOnce({
version: '0.8.0',
name: 'test',
build: '123',
id: 'r132-132',
});
const axiosSpy = jest.spyOn(axios, 'get');
axiosSpy
.mockResolvedValueOnce({
data: {
enabled: false,
msg: {
title: 'App maintenance',
msg: 'We are currently solving an issue where users cannot open the app. This should be solved by end of day 12/31/2022! Thank you for your patience 😁',
btn: 'Ok',
type: 'maintenance',
},
},
})
.mockResolvedValueOnce({
data: {
current: '1.0.0',
currentAndroid: '1.0.0',
currentIos: '2.0.0',
enabled: true,
majorMsg: {
title: 'Important App update',
msg: 'Please update your app to the latest version to continue using it. If you are on iPhone, go to the app store and search MO Gas Tax Back to update your app. The button below does not work but will in the current update!',
btn: 'Download',
type: 'major',
},
minorMsg: {
title: 'App update available',
msg: "There's a new version available, would you like to get it now?",
btn: 'Download',
type: 'minor',
},
},
});
customRender(<UpdateChild />);
expect(axiosSpy).toHaveBeenCalledTimes(2);
});

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()
// })
// }
}
});

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

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>.

Send a message if the channel already exists

I am working on a kind of ticket system. Suppose someone has a ticket open called ticket-$ {message.author.username} how can I prevent that person from making another ticket? Because the way I try it doesn't work.
Edit: I've added a lot more code now, this is almost my whole code. I still get an error with these changes.
Code:
module.exports.run = async (bot, message, args) => {
message.delete();
const filter = (reaction, user) => ['🗒️', '👨‍💻', '🖥️', '🧐'].includes(reaction.emoji.name) && user.id === message.author.id;
var name = `ticket-${message.author.username}`
const category = message.guild.channels.cache.get('708800011160256582');
let supportRole = message.guild.roles.cache.get("708629895621640242");
let supportRole2 = message.guild.roles.cache.get("708628839659733032");
let chan = `ticket-${message.author.username}`;
if (message.guild.channels.cache.find(channel => channel.name === chan)) {
return message.channel.send("TEST")
} else {
message.guild.channels.create(name, {
parent: category,
topic: `📩 TICKET | ${message.author.username}`,
permissionOverwrites: [{
id: message.author.id,
allow: ['VIEW_CHANNEL', 'SEND_MESSAGES', 'ATTACH_FILES'],
}, {
id: message.guild.id,
deny: ['VIEW_CHANNEL'],
}, {
id: supportRole,
allow: ['VIEW_CHANNEL', 'SEND_MESSAGES'],
}, {
id: supportRole2,
allow: ['VIEW_CHANNEL', 'SEND_MESSAGES']
}]
})
}
}).then(async c => {
let orderEmbed = new Discord.MessageEmbed()
.setTitle("Choose one of the topics below.")
.setColor("#e05856")
.setDescription(`
🗒️ » **Make order.**
👨‍💻 » **Personal support.**
🖥️ » **Technical support (Personal)**
🧐 » **Something else.**
`)
.setTimestamp();
c.send(orderEmbed).then(async msg => {
await msg.react("🗒️");
await msg.react("👨‍💻");
await msg.react('🖥️');
await msg.react("🧐");
msg.awaitReactions(filter, {
max: 1,
time: 30000,
errors: ['time']
}).then(collected => {
const reaction = collected.first();
switch(reaction.emoji.name) {
case '🗒️':
c.send("test1");
break;
case '👨‍💻':
c.send("test2");
break;
case '🖥️':
c.send("test3");
break;
case '🧐':
c.send("test4");
break;
}
}).catch(collected => {
});
})
});
message.channel.send(`Hi ${message.author.username}! You have opened an order, view it in #${name.id}`).then(async msg => {
})
}
module.exports.help = {
name: "order"
}
I hope someone can help me! :-)
Your code should work, but since you said it's not working, do this:
module.exports.run = async (bot, message, args) => {
message.delete();
const filter = (reaction, user) => ['🗒️', '👨‍💻', '🖥️', '🧐'].includes(reaction.emoji.name) && user.id === message.author.id;
var name = `ticket-${message.author.username}`
const category = message.guild.channels.cache.get('708800011160256582');
let supportRole = message.guild.roles.cache.get("708629895621640242");
let supportRole2 = message.guild.roles.cache.get("708628839659733032");
let chan = `ticket-${message.author.username}`;
if (message.guild.channels.cache.find(channel => channel.name === chan)) {
return message.channel.send("TEST")
} else {
message.guild.channels.create(name, {
parent: category,
topic: `📩 TICKET | ${message.author.username}`,
permissionOverwrites: [{
id: message.author.id,
allow: ['VIEW_CHANNEL', 'SEND_MESSAGES', 'ATTACH_FILES'],
}, {
id: message.guild.id,
deny: ['VIEW_CHANNEL'],
}, {
id: supportRole,
allow: ['VIEW_CHANNEL', 'SEND_MESSAGES'],
}, {
id: supportRole2,
allow: ['VIEW_CHANNEL', 'SEND_MESSAGES']
}]
})
.then(async c => {
let orderEmbed = new Discord.MessageEmbed()
.setTitle("Choose one of the topics below.")
.setColor("#e05856")
.setDescription(`
🗒️ » **Make order.**
👨‍💻 » **Personal support.**
🖥️ » **Technical support (Personal)**
🧐 » **Something else.**
`)
.setTimestamp();
c.send(orderEmbed).then(async msg => {
await msg.react("🗒️");
await msg.react("👨‍💻");
await msg.react('🖥️');
await msg.react("🧐");
msg.awaitReactions(filter, {
max: 1,
time: 30000,
errors: ['time']
}).then(collected => {
const reaction = collected.first();
switch (reaction.emoji.name) {
case '🗒️':
c.send("test1");
break;
case '👨‍💻':
c.send("test2");
break;
case '🖥️':
c.send("test3");
break;
case '🧐':
c.send("test4");
break;
}
}).catch(collected => {
});
})
});
message.channel.send(`Hi ${message.author.username}! You have opened an order, view it in #${name.id}`).then(async msg => {
})
}
}
module.exports.help = {
name: "order"
}

Resources