Interaction Channel MessageCollector, Discord.js - javascript

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.

Related

Discord-Modals failing on phones. Discord.js

I'm trying to make a game ban appeal, using the Discord-Modals package, and it seems to work good so far, however, the modal looks odd on phones, which will be a problem.
There are no errors, Here is what it looks like:
On PC, and On Phone1 Phone2
As you can see, On PC there was the Do you think the ban was fair? select drop down, but on both phones, it wasn't there.
I'm not sure of this is fixable, but I sure hope it is.
Code:~
// Main requirements
const { CHANNEL_SSU, CHANNEL_ROLESEL, BOT_PREFIX, ROLE_DEV } = require('../../config.json')
const commandName = '2gba'
// Optional Requirements
const { MessageEmbed, MessageActionRow, MessageButton, MessageCollector, InteractionType } = require('discord.js')
const { Modal, TextInputComponent, showModal, SelectMenuComponent } = require(`discord-modals`)
// 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('GBAempty5')
.setLabel(' ')
.setStyle('SECONDARY')
.setDisabled(true),
new MessageButton()
.setCustomId('GBA2')
.setLabel('Appeal')
.setStyle('DANGER')
.setDisabled(false),
new MessageButton()
.setCustomId('GBAempty6')
.setLabel(' ')
.setStyle('SECONDARY')
.setDisabled(true)
)
const GBAEmbed = new MessageEmbed()
.setTitle('Appeal Your Game Ban! 222')
.setColor('DARK_BLUE')
.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 == 'GBA2') {
const modal = new Modal()
.setCustomId(`gbamodal`)
.setTitle(`ASRP | Game Ban Appeal`)
.addComponents(
new TextInputComponent()
.setCustomId("RobloxUsername-gba")
.setLabel("Roblox Username")
.setStyle("SHORT")
.setMinLength(1)
.setPlaceholder('Please check for any typos.')
.setRequired(true),
new TextInputComponent()
.setCustomId("Moderator-gba")
.setLabel("Who banned you?")
.setStyle("SHORT")
.setMinLength(1)
.setPlaceholder('This field is optional.')
.setRequired(false),
new TextInputComponent()
.setCustomId("unbanreason-gba")
.setLabel("Why should we unban you?")
.setStyle("LONG")
.setMinLength(1)
.setPlaceholder('Give us a reason to unban you.')
.setRequired(true),
new TextInputComponent()
.setCustomId("banreason-gba")
.setLabel("Why were you banned from asrp?")
.setStyle("LONG")
.setMinLength(1)
.setPlaceholder('Give us the reason you were banned for.')
.setRequired(true),
new SelectMenuComponent()
.setCustomId('fair-gba')
.setPlaceholder('Do you think your punishment was fair?')
.addOptions(
{
label: "Yes",
description: "You think the punishment was fair.",
value: "Yes",
emoji: "✅"
},
{
label: "No",
description: "You think the punishment was unfair.",
value: "No, I think it's unfair.",
emoji: "❌"
}
)
);
showModal(modal, {
client: client,
interaction: interaction
})
}
});
client.on('modalSubmit', async modal => {
if (modal.customId === 'gbamodal') {
const RBXuser = modal.getTextInputValue('RobloxUsername-gba');
let BanMod = modal.getTextInputValue('Moderator-gba');
if (!BanMod) BanMod = 'None Stated';
const ReasonUnban = modal.getTextInputValue('unbanreason-gba');
const ReasonBan = modal.getTextInputValue('banreason-gba');
const Fairness = modal.getSelectMenuValues('fair-gba');
const user = modal.user
const appealEmbed = new MessageEmbed()
.setTitle(`New Game Ban Appeal`)
.setAuthor({ name: `User: ${user.tag} (${user.id})` })
.addFields(
{name: `Q: Roblox Username`, value: `A: ${RBXuser}`},
{name: `Q: Who banned you?`, value: `A: ${BanMod}`},
{name: `Q: Why should we unban you?`, value: `A: ${ReasonUnban}`},
{name: `Q: Why were you banned?`, value: `A: ${ReasonBan}`},
{name: `Q: Do you think the ban was fair?`, value: `A: ${Fairness}`}
)
.setFooter({ text: `This is beta, please report any errors.` })
.setThumbnail(user.displayAvatarURL({ dynamic: true, size: 512 }))
await modal.reply({ content: 'Your submission was recieved successfully!', ephemeral: true }).then(() => {
client.guilds.cache.get(`954881682429853726`).channels.cache.get('998833987810246666').send({ embeds: [appealEmbed] });
})
console.log(modal.getTextInputValue('RobloxUsername-gba'))
console.log(modal.getTextInputValue('Moderator-gba'))
console.log(modal.getTextInputValue('unbanreason-gba'))
console.log(modal.getTextInputValue('banreason-gba'))
console.log(modal.getSelectMenuValues('fair-gba'))
}
});
}
Extra Information:
Node Version: 'v16.14.2'
NPM Version: '8.5.0'
Discord.js Version: '^13.7.0'
Thank you in advance.
Select Menu's within Modals are unsupported and not documented by Discord - this is not a user issue nor an issue with the code.
Select Menu's just don't show up on mobile and only partially work within Modals (as of August 2022).

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

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

Unknown Interaction on All interactions - Discord.js v13

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.

what this error mean await message.guild.channels.create

let ticket = new Map()
module.exports = {
commands: ['ticket'],
description: "open a new ticket",
callback: (message, async, text) => {
const ticketChannel = message.guild.channels.cache.find(c => c.name.toLowerCase() === `${message.author.username}--ticket`.toLowerCase())
if(ticketChannel || ticket.get(message.author.id) === true) return message.channel.send("You already have a ticket currently open!")
const ticketCreated = await message.guild.channels.create(`${message.author.username}-ticket`, {
type: 'text',
permissionOverwrites: [
{
allow: 'VIEW_CHANNEL',
id: message.author.id
},
{
deny: 'VIEW_CHANNEL',
id: message.guild.id
}
]
})
ticket.set(message.author.id, true)
let embed1 = new Discord.MessageEmbed()
.setAuthor(message.member.displayName, message.member.user.displayAvatarURL())
.setTitle(`Your Ticket has been created!`)
.setTimestamp()
.setColor('RANDOM');
let embed3 = new Discord.MessageEmbed()
.setAuthor(message.member.displayName, message.member.user.displayAvatarURL())
.setTitle(`Why have you created this ticket?`)
.setDescription('Give a brief explanation on why you created this ticket.')
.addField('Staff will be here shortly', 'Please wait without pinging anyone.')
.setTimestamp()
.setColor('RANDOM');
ticketCreated.send(embed3)
message.channel.send(embed1)
}
}
i have this code and this is give me const ticketCreated = await message.guild.channels.create(${message.author.username}-ticket, {
error, what this is mean?
It's important to note that this is not my code, but I've made some changes to it for it to work, I'd love help

Categories

Resources