Discord.js Ticket System | Problem With Spamming Tickets - javascript

I am trying to make a ticket system, but there is a problem. I want to make it when somebody opens a ticket, wait until the ticket closes, and then let them react again.
Here is my code:
const Discord = require('discord.js');
const client = new Discord.Client({
partials: ['MESSAGE', 'USER', 'REACTION'],
});
const enmap = require('enmap');
const { token, prefix } = require('./config.json');
const settings = new enmap({
name: 'settings',
autoFetch: true,
cloneLevel: 'deep',
fetchAll: true,
});
client.on('ready', () => {
console.log('Ticket System');
client.user.setActivity(`Community`, { type: 'WATCHING' });
});
client.on('message', async (message) => {
if (message.author.bot) return;
if (message.content.indexOf(prefix) !== 0) return;
const args = message.content
.slice(prefix.length)
.trim()
.split(/ +/g);
const command = args.shift().toLowerCase();
if (command == 'ticket-setup') {
if (message.author == '409327435188928526') {
let channel = message.mentions.channels.first();
if (!channel) return message.reply('Usage: `!ticket-setup`');
let sent = await channel.send(
new Discord.MessageEmbed()
.setTitle('Ticket System')
.setDescription(
'If you want to buy something from us,\n react with‏‏‎ ‎‏‏‎ ‎ 🎫 ‏‏‎ ‎‏‏‎ ‎to open a ticket'
)
.setFooter(
'Community',
''
)
.setColor('00f8ff')
);
sent.react('🎫');
settings.set(`${message.guild.id}-ticket`, sent.id);
message.channel.send('Ticket System Setup Done!');
}
}
if (command == 'close') {
if (!message.channel.name.includes('ticket-'))
return message.channel.send('You cannot use that here!');
message.channel.delete();
}
});
client.on('messageReactionAdd', async (reaction, user) => {
if (user.partial) await user.fetch();
if (reaction.partial) await reaction.fetch();
if (reaction.message.partial) await reaction.message.fetch();
if (user.bot) return;
let ticketid = await settings.get(`${reaction.message.guild.id}-ticket`);
if (!ticketid) return;
if (reaction.message.id == ticketid && reaction.emoji.name == '🎫') {
reaction.users.remove(user);
reaction.message.guild.channels
.create(`ticket-${user.username}`, {
permissionOverwrites: [
{
id: user.id,
allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
},
{
id: reaction.message.guild.roles.everyone,
deny: ['VIEW_CHANNEL'],
},
],
type: 'text',
})
.then(async (channel) => {
channel.send(
`<#${user.id}> Welcome!`,
new Discord.MessageEmbed()
.setDescription(
'Support will be with you shortly.\n \n !close to close the ticket.'
)
.setColor('00f8ff')
.setFooter(
'Community',
''
)
.setTimestamp()
);
});
}
});
client.login(token);
Also, instead of having to use a command to close the ticket, I want the bot to add a yes and no reaction to the message, and ask me if I want to close it.

Related

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.

I'm trying to make reaction roles using my own discord bot but for some reason it doesn't add the role even though it adds the reactions

I'm trying to make a discord bot that adds roles from reactions. I've been following a tutorial from CodeLyon and I hit a snag and I cant find a fix
Basically, I got the bot to send a embed message and it adds the reactions to the message. But it doesn't add the roles.
module.exports = {
name: "reactionrole",
description: "Sets up a reaction role message!",
async execute(message, args, Discord, client) {
const channel = "907732565685846036";
const ACRole = message.guild.roles.cache.find(
(role) => role.name === "Animal Crossing"
);
const ACEmoji = "🐸";
let embed = new Discord.MessageEmbed()
.setColor("#e42643")
.setTitle("Choose which games you play!")
.setDescription(
"React to add the games you play as a role (and receive pings)\n\n" +
`${ACEmoji} for Animal Crossing\n`
);
let messageEmbed = await message.channel.send({ embeds: [embed] });
messageEmbed.react(ACEmoji);
client.on("messageReactionAdd", async (reaction, user) => {
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
if (user.bot) return;
if (!reaction.message.guild) return;
if (reaction.message.channel.id == channel) {
if (reaction.emoji.name === ACEmoji) {
await reaction.message.guild.members.cache
.get(user.id)
.roles.add(ACRole);
}
} else {
return;
}
});
client.on("messageReactionRemove", async (reaction, user) => {
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
if (user.bot) return;
if (!reaction.message.guild) return;
if (reaction.message.channel.id == channel) {
if (reaction.emoji.name === ACEmoji) {
await reaction.message.guild.members.cache
.get(user.id)
.roles.remove(ACRole);
}
} else {
return;
}
});
},
};
In my main.js (some people use index.js) file I had to change const client = new Discord.Client({ intents: ['GUILDS', 'GUILD_MESSAGES', 'GUILD_MESSAGE'] }, { partials: ["MESSAGE", "CHANNEL", "REACTION" ] })
to
const client = new Discord.Client({ intents: ['GUILDS', 'GUILD_MESSAGES', 'GUILD_MESSAGE_REACTIONS'] }, { partials: ["MESSAGE", "CHANNEL", "REACTION" ] })
It fixed it for a little bit but it randomly stopped working again.

the reaction roles doesn't give me the role when I click it and I get no errors

I've been trying to figure out how to make the reaction roles to give me the roles i want but i dont get any errors and i don't get the roles added to myself at all when I execute the command and press the emojis, i also don't get any console logs and I've added console.log to the code. any help would be appreciated, i'm having a really hard time with this, please help me...
const Discord = require('discord.js');
const { MessageEmbed } = require('discord.js');
const { MessageReaction } = require('discord.js');
const client = new Discord.Client();
module.exports = {
name: 'games',
description: 'Select the games',
async execute(message, args, Discord, bot) {
if (message.member.roles.cache.has('552561546039918593')) {
const channel = '905072473899409438';
const gifsRole = message.guild.roles.cache.find((role) => role.name === 'GIF');
const emojiRole = message.guild.roles.cache.find((role) => role.name === 'EMOJIS');
const gifs = '<:hersheys:823607413843951646>';
const emoji = '<:glokez:858101005512867892>';
const gifsEmoij = '823607413843951646';
const emojiEmoij = '858101005512867892';
let embed = new MessageEmbed()
.setColor('#e42643')
.setTitle('<a:sparkles1:905070246610739240> **Role Selection**')
.setDescription(
`Choose what roles you want to access!\n\n` +
`${gifs} **(** GIF **)**\n` +
`${emoji} **(** EMOJIS **)**`,
);
let messageEmbed = await message.channel.send(embed);
messageEmbed.react(gifsEmoij);
messageEmbed.react(emojiEmoij);
client.on('messageReactionAdd', async (reaction, user) => {
console.log('0');
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
if (user.bot) return;
if (!reaction.message.guild) return;
console.log('1', reaction.message.channel.id === channel);
if (reaction.message.channel.id === channel) {
console.log('2', reaction.emoji.id === gifsEmoij.id);
if (reaction.emoji.id === gifsEmoji.id) {
console.log('3');
await reaction.message.guild.members.cache.get(user.id).roles.add(gifsRole);
}
if (reaction.emoji.id === emojiEmoji.id) {
await reaction.message.guild.members.cache.get(user.id).roles.add(emojiRole);
}
} else {
return;
}
});
client.on('messageReactionRemove', async (reaction, user) => {
console.log('0');
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
if (user.bot) return;
if (!reaction.message.guild) return;
console.log('1', reaction.message.channel.id === channel);
if (reaction.message.channel.id === channel) {
console.log('2', reaction.emoji.id === gifsEmoij.id);
if (reaction.emoji.id === gifsEmoji.id) {
console.log('3');
await reaction.message.guild.members.cache.get(user.id).roles.remove(gifsRole);
}
if (reaction.emoji.id === emojiEmoji.id) {
await reaction.message.guild.members.cache.get(user.id).roles.remove(emojiRole);
}
} else {
return;
}
});
}
},
};

Discord.js bot channel createOverwrite not working

Hai i am working on a discord moderation bot i made a mute command but it will add mute role to people and if the role doesn't exist it will create one and add it to the member but i have a problem it wont deny send message permission in every channel i added the code for that but it isn't working and i get no errors in console here is my code
message.guild.channels.cache.forEach(async (channel) => {
await channel.createOverwrite(muterole, {
SEND_MESSAGES: false,
ADD_REACTIONS: false,
SPEAK: false,
CONNECT: false,
})
Here is my full mute.js code
const { MessageEmbed } = require("discord.js");
const db = require('quick.db');
module.exports = {
name: 'mute',
description: 'mutes a user',
async execute(message, args) {
try {
if (!message.member.hasPermission("MANAGE_GUILD")) return message.channel.send("**You Dont Have Permmissions To Mute Someone! - [MANAGE_GUILD]**");
if (!message.guild.me.hasPermission("MANAGE_GUILD")) return message.channel.send("**I Don't Have Permissions To Mute Someone! - [MANAGE_GUILD]**")
if (!args[0]) return message.channel.send("**Please Enter A User To Be Muted!**");
var mutee = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find(r => r.user.username.toLowerCase() === args[0].toLocaleLowerCase()) || message.guild.members.cache.find(ro => ro.displayName.toLowerCase() === args[0].toLocaleLowerCase());
if (!mutee) return message.channel.send("**Please Enter A Valid User To Be Muted!**");
if (mutee === message.member) return message.channel.send("**You Cannot Mute Yourself!**")
if (mutee.roles.highest.comparePositionTo(message.guild.me.roles.highest) >= 0) return message.channel.send('**Cannot Mute This User!**')
let reason = args.slice(1).join(" ");
if (mutee.user.bot) return message.channel.send("**Cannot Mute Bots!**");
const userRoles = mutee.roles.cache
.filter(r => r.id !== message.guild.id)
.map(r => r.id)
let muterole;
let dbmute = await db.fetch(`muterole_${message.guild.id}`);
let muteerole = message.guild.roles.cache.find(r => r.name === "muted")
if (!message.guild.roles.cache.has(dbmute)) {
muterole = muteerole
} else {
muterole = message.guild.roles.cache.get(dbmute)
}
if (!muterole) {
try {
muterole = await message.guild.roles.create({
data: {
name: "muted",
color: "#514f48",
permissions: []
}
})
message.guild.channels.cache.forEach(async (channel) => {
await channel.createOverwrite(muterole, {
SEND_MESSAGES: false,
ADD_REACTIONS: false,
SPEAK: false,
CONNECT: false,
})
})
} catch (e) {
console.log(e);
}
};
if (mutee.roles.cache.has(muterole.id)) return message.channel.send("**User Is Already Muted!**")
db.set(`muteeid_${message.guild.id}_${mutee.id}`, userRoles)
try {
mutee.roles.set([muterole.id]).then(() => {
mutee.send(`**Hello, You Have Been Muted In ${message.guild.name} for - ${reason || "No Reason**"}`).catch(() => null)
})
} catch {
mutee.roles.set([muterole.id])
}
if (reason) {
const sembed = new MessageEmbed()
.setColor("GREEN")
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription(`${mutee.user.username} was successfully muted for ${reason}`)
message.channel.send(sembed);
} else {
const sembed2 = new MessageEmbed()
.setColor("GREEN")
.setDescription(`${mutee.user.username} was successfully muted`)
message.channel.send(sembed2);
}
let channel = db.fetch(`modlog_${message.guild.id}`)
if (!channel) return;
let embed = new MessageEmbed()
.setColor('RED')
.setThumbnail(mutee.user.displayAvatarURL({ dynamic: true }))
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL())
.addField("**Moderation**", "mute")
.addField("**Mutee**", mutee.user.username)
.addField("**Moderator**", message.author.username)
.addField("**Reason**", `${reason || "**No Reason**"}`)
.addField("**Date**", message.createdAt.toLocaleString())
.setFooter(message.member.displayName, message.author.displayAvatarURL())
.setTimestamp()
var sChannel = message.guild.channels.cache.get(channel)
if (!sChannel) return;
sChannel.send(embed)
} catch {
return;
}
}
}
Hope i get a answer have a wonderful day happy coding...
Make sure that the "mute" role was added to the channel and the permission node "SEND_MESSAGES" was denied.
This does only work if the user's highest role is the "mute" role!

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