so I have been working on this help command for some time now. In the beginning, there was no such error, but now even after all the methods I came up with, weren't able to fix this error. I tried to remove the selectMenu after 60s to prevent old interactions to launch as well but it still doesn't seem to work properly. I have added my code to this as well, please do help me.
const { MessageSelectMenu, Collector } = require("discord.js");
module.exports = {
name: 'help',
description: "This is a help command!",
async execute(message, args, Discord, client){
let commandUser = message.author.id
let helpEmbed = new Discord.MessageEmbed()
.setColor('#EF4344')
.setAuthor('Builder BOT • Help-Command','https://media.discordapp.net/attachments/960440764737921074/960790159597641758/builder_bot_06.png')
.setDescription(`• My prefix is \`b!\`.\n • We recommend to give the BOT Administrator permission.\n • We recommend NOT to change the BOT-role's and channel's permission.\n • Type \`b!help <module>\` for further information regarding a specific module.\n • Type \`b!help <command>\` for further information regarding a specific command.`)
.addFields({
name: 'BOT-Modules:',
value: `• <:Hammer:960753810253414401>_Build-Module_\n • <:Gear:960764548195958834>_Config-Module_\n • <:Pencil:960962910463598615>_Action Log-Module_\n • <:Staff:960964396425814117>_Moderation-Module_\n • <:Misc:960964890460319855>_Misc-Module_\n • <:Rocket:960965476673019954>_Fun-Module_`,
inline: true
},{
name: 'BOT-Updates:',
value: '**Help command under-development**\n Use the command for more information.\n Eg- \`b!help\`',
inline: true
})
.setTimestamp()
.setFooter(`Author ID: ${message.author.id}`,`${message.author.displayAvatarURL()}`);
let helpSelectMenu = new Discord.MessageActionRow().addComponents([
new MessageSelectMenu()
.setCustomId('Help-SelectMenu')
.setPlaceholder('For more information, choose a module!')
.addOptions([
{
label: 'Build-Module',
value: 'Build_Option',
description: 'Build servers more easily than ever before!',
emoji: `<:Hammer:960753810253414401>`
},
{
label: 'Config-Module',
value: 'Config_Option',
description: 'Configure Builder BOT\'s settings!',
emoji: `<:Gear:960764548195958834>`
},
{
label: 'Action Log-Module',
value: 'Action Log_Option',
description: 'Keep track of everything that happens in the server!',
emoji: `<:Pencil:960962910463598615>`
},
{
label: 'Moderation-Module',
value: 'Moderation_Option',
description: 'Automate moderation and protect your server!',
emoji: `<:Staff:960964396425814117>`
},
{
label: 'Misc-Module',
value: 'Misc_Option',
description: 'Uncategorized amazing features!',
emoji: `<:Misc:960964890460319855>`
},
{
label: 'Fun-Module',
value: 'Fun_Option',
description: 'Engage members with interactive commands!',
emoji: `<:Rocket:960965476673019954>`
}
])
])
message.channel.send({ embeds: [helpEmbed], components: [helpSelectMenu] }).catch(() => {
if(message.channel.permissionsFor(client.user.id).has(['SEND_MESSAGES'])){
message.channel.send(`<#${message.author.id}>, I don't have the required permissions!`).then(msg => {
setTimeout(() => {msg.delete()}, 5000)
})
}else{
return;
};
}).then((msg) => {
setTimeout(() => {msg.edit({ embeds: [helpEmbed], components: []})}, 60000)
});
let underDevelopment = new Discord.MessageEmbed()
.setColor('#EF4344')
.setDescription('The BOT is currently under development process!')
.setTimestamp()
let helpDropdownfilter = (interaction) => (interaction.isSelectMenu() && interaction.user.id === message.author.id);
let helpDropdownCollector = message.channel.createMessageComponentCollector({
helpDropdownfilter,
max: 2,
time: 60000
});
helpDropdownCollector.on('collect', async (interaction) => {
console.log(interaction.values[0]);
if(commandUser === interaction.user.id){
if(interaction.values[0] === 'Build_Option'){
underDevelopment.setAuthor('Builder BOT • Build-Module','https://media.discordapp.net/attachments/960440764737921074/960790159597641758/builder_bot_06.png')
underDevelopment.setFooter(`Interaction ID: ${interaction.user.id}`,`${interaction.user.displayAvatarURL()}`);
await interaction.update({ embeds: [underDevelopment], components: [] });
}
if(interaction.values[0] === 'Config_Option'){
underDevelopment.setAuthor('Builder BOT • Config-Module','https://media.discordapp.net/attachments/960440764737921074/960790159597641758/builder_bot_06.png')
underDevelopment.setFooter(`Interaction ID: ${interaction.user.id}`,`${interaction.user.displayAvatarURL()}`);
await interaction.update({ embeds: [underDevelopment], components: []});
}
if(interaction.values[0] === 'Action Log_Option'){
underDevelopment.setAuthor('Builder BOT • Action Log-Module','https://media.discordapp.net/attachments/960440764737921074/960790159597641758/builder_bot_06.png')
underDevelopment.setFooter(`Interaction ID: ${interaction.user.id}`,`${interaction.user.displayAvatarURL()}`);
await interaction.update({ embeds: [underDevelopment], components: [] });
}
if(interaction.values[0] === 'Moderation_Option'){
underDevelopment.setAuthor('Builder BOT • Moderation-Work','https://media.discordapp.net/attachments/960440764737921074/960790159597641758/builder_bot_06.png')
underDevelopment.setFooter(`Interaction ID: ${interaction.user.id}`,`${interaction.user.displayAvatarURL()}`);
await interaction.update({ embeds: [underDevelopment], components: [] });
}
if(interaction.values[0] === 'Misc_Option'){
underDevelopment.setAuthor('Builder BOT • Misc-Module','https://media.discordapp.net/attachments/960440764737921074/960790159597641758/builder_bot_06.png')
underDevelopment.setFooter(`Interaction ID: ${interaction.user.id}`,`${interaction.user.displayAvatarURL()}`);
await interaction.update({ embeds: [underDevelopment], components: [] });
}
if(interaction.values[0] === 'Fun_Option'){
underDevelopment.setAuthor('Builder BOT • Fun-Module','https://media.discordapp.net/attachments/960440764737921074/960790159597641758/builder_bot_06.png')
underDevelopment.setFooter(`Interaction ID: ${interaction.user.id}`,`${interaction.user.displayAvatarURL()}`);
await interaction.update({ embeds: [underDevelopment], components: [] });
}
}else{
await interaction.reply({ content: `<#${interaction.user.id}>, you do not have access to this interaction!`, ephemeral: true})
}
})
}
}
I see that you are using a lot of if conditions. I'd suggest using if and else if instead of using if multiple times. Also, try the following code;
const initial = await message.channel.send({ /** ... */ });
const filter = // ...
const collector = // ...
collector.on("collect", async(interaction) => {
if(interaction.values[0] === "something"){
if(initial.editable){
await initial.edit(/** ... */)
} else return;
} else if (interaction.values[0] === "anything"){
// ...
}
})
You're basically saving the first response of the bot, to later on edit the responses as they select options from the menu.
Related
Wassup people. I am working on some admin commands. At this moment it's going to be a kick command. But it's only giving errors. If you remove a line or change anything, it will infect the code in another place.
That's what I am struggling with.
Here's my code:
const { Client, Intents } = require("discord.js");
const discord = require("discord.js");
const { MessageEmbed, Collection, Permissions } = require("discord.js");
module.exports = {
name: "kick",
description: "Kicks a specific member",
admin: true,
usage: "[Target] [Reason] [Messages]",
options: [
{
name: "Target",
description: "Provide A User To Kick.",
type: "USER",
required: true,
},
{
name: "Reason",
description: "Provide A Reason For The Kick.",
type: "STRING",
required: true,
},
],
async execute(message, args, client) {
const target = message.mentions.members.first();
const reason = args.slice(1, args.length - 1).join(" ");
console.log("Target: ");
const embed = new MessageEmbed().setTitle("There seems to be a error to execute this command").setColor("RED").setDescription("Are you sure you got the right permission? And are you providing a reason?");
if (!message.member.permissions.has(Permissions.FLAGS.KICK_MEMBERS))
return message.reply({ embeds: [embed] }).catch((err) => {
console.log(err);
});
if (target.id === message.member.id)
return message.reply({
embeds: [new MessageEmbed().setTitle("There seems to be a error to execute this command").setColor("RED").setDescription("Why would you kick yourself?")],
ephemeral: true,
});
if (target.permissions.has(Permissions.FLAGS.KICK_MEMBERS)) {
return message.reply({
embeds: [new MessageEmbed().setColor("RED").setDescription("You can't kick this person.")],
});
}
const DMEmbed = new MessageEmbed().setTitle(`You've Been Kicked From ${message.guild.name}`).setColor("RED").setTimestamp().addFields(
{
name: "Reason:",
value: reason,
},
{
name: "Kicked By:",
value: message.member.user.toString(),
}
);
await target
.send({
embeds: [DMEmbed],
})
.catch((err) => {
console.log(err);
});
},
};
From what I can see, it is most likely the reason field being empty.
You can change it to this to ensure there is a fallback!
{
name: "Reason:",
value: reason.replace(/\s/g, '') == "" ? "Not Provided" : reason,
},
I am back again with a question :). I am building my own ticket function, and I just started but if I create a channel for a ticket, its only saying ticket-(Discord account ID) And thats also the case by the embed. Anyone who can look at it?
const discord = require("discord.js");
const { MessageEmbed, Collection, Permissions} = require('discord.js');
const { execute } = require("./ticket");
module.exports = {
name: 'create',
description: 'create your own ticket.',
execute(message, client, args){
if(message.guild.channels.cache.find(channel => channel.name === "Ticket from <#" + message.author + ">")) {
message.reply(`${message.member.user.toString()} **You have successfully created a ticket, Please click on ${channel} to view your ticket**`).then(m => m.delete({ timeout: 14000 }).catch(e => {}));
if(message.guild.channels.cache.find(channel => channel.name === `ticket-${message.author.id}`)) {
return message.reply('<a:no:784463793366761532> **You already have a ticket, please close your exsisting ticket first before opening a new one**');
}
message.delete();
message.guild.channels.create(`Ticket ${message.author}`, {
permissionOverwrites: [
{
id: message.author.id,
allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
},
{
id: message.guild.roles.everyone,
deny: ['VIEW_CHANNEL'],
},
],
type: 'text',
}).then(async channel => {
const embed = new MessageEmbed()
.setTitle("<#" + message.author + "> Ticket")
.setDescription(`**${message.author}, Welcome to your channel! Support will be arriving soon**\n**While you wait please tell us what your problem is**\n**If you want to close the ticket please type .close\`**`)
.setColor("BLUE")
channel.send({ embeds: [embed] })
});
}
}
}
I cleaned up the code a fair bit, less is more. Text channels do not have spaces in them so I replaced them with what Discord uses, hypens. The below code will check if a channel already exists and create one if it doesn't.
const {
MessageEmbed,
} = require('discord.js');
module.exports = {
name: 'create',
description: 'create your own ticket.',
async execute(message, client, args) {
const channelName = `ticket-${message.author.username}`
const existing = message.guild.channels.cache.find(channel => channel.name === channelName.toLowerCase());
if (existing) {
return message.reply({
content: `<a:no:784463793366761532> **You already have a ticket, please close your exsisting ticket first before opening a new one**\n${existing}.`,
}).then((m) => {
setTimeout(() => {
m.delete();
}, 14000);
})
}
message.delete();
message.guild.channels.create(channelName, {
type: 'GUILD_TEXT',
permissionOverwrites: [{
id: message.guild.id,
deny: ['VIEW_CHANNEL'],
}, {
id: message.author.id,
allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
}],
}).then(async channel => {
const embed = new MessageEmbed()
.setColor("BLUE")
.setTitle(`${message.author.username} Ticket`)
.setDescription(`**${message.author}, Welcome to your channel! Support will be arriving soon**\n**While you wait please tell us what your problem is**\n**If you want to close the ticket please type .close\`**`)
channel.send({
embeds: [embed]
})
});
}
}
I have been getting an error as mentioned in the title. Whenever I use that command, the bot creates a channel that brings up a select menu, through which the user can "teleport" to another channel while deleting the newly created channel in the process. This code successfully works twice, after which it gives the error. What should be done to fix the error so that the user can use the command as many times as they'd like? I'll work on this code further once the solution is found, but until then, I'm really stumped here. (Questions shall be answered upon questioning; apologies for the messy coding)
module.exports.run = async (client, msg, args) => {
const guild = client.guilds.cache.get('855845132879921214')
const channel = guild.channels.cache.get('959851265456734319')
const newChannel = await msg.guild.channels.create(`teleporter`)
await newChannel.permissionOverwrites.edit(msg.author.id, {
SEND_MESSAGES: false,
VIEW_CHANNEL: true,
})
const {MessageActionRow, MessageSelectMenu, MessageEmbed} = require('discord.js')
const embed = new MessageEmbed()
.setTitle(`Teleporter!`)
.setDescription("Through this interaction, you can now teleport to the main channel of the desired category!")
const row = new MessageActionRow()
.addComponents(
new MessageSelectMenu()
.setCustomId('teleport')
.setPlaceholder('Choose a channel')
.addOptions([
{
label: 'Rules',
description: "Click to check the rules",
value: 'rules',
},
{
label: 'General',
description: "Click to go to the main chat",
value: 'general',
},
{
label: 'Media',
description: "Click to go to media channel",
value: 'media',
},
{
label: 'Bots',
description: "Click to go to the bots channel",
value: 'bots',
}
]),
)
await newChannel.send({content: `<#${msg.author.id}>`,embeds: [embed], components: [row]})
const wait = require('util').promisify
client.on('interactionCreate', async interaction => {
const member = await interaction.guild.members.fetch({
user: interaction.user.id,
force: true
})
if(!interaction.isSelectMenu()) {
interaction.deferUpdate()}
else if (interaction.values == 'general'){
msg.member.roles.add('958421069650337822')
msg.member.roles.remove('943159431800172584')
let tele = msg.guild.channels.cache.find(channel => channel.name == 'teleporter')
tele.delete()
msg.member.roles.add('943159431800172584')
msg.member.roles.remove('958421069650337822')
}
}
)
}
Don't cache.find and delete, do it like;
const newChannel = await client.channels.fetch("id")
newChannel.delete()
This code should be separated with the first section as your command and the second part as a separate listener, so I have coded as such.
const {
MessageActionRow,
MessageSelectMenu,
MessageEmbed,
} = require('discord.js');
module.exports.run = async (client, msg, args) => {
const guild = client.guilds.cache.get('855845132879921214');
const channel = guild.channels.cache.get('959851265456734319');
const newChannel = await msg.guild.channels.create(`teleporter-${msg.author.username}`, {
permissionOverwrites: [{
id: guild.id,
deny: ["VIEW_CHANNEL"],
}, {
id: msg.author,
deny: ["SEND_MESSAGES"],
allow: ["VIEW_CHANNEL"],
}],
});
// In the event that more than one person uses this command at once, you will need to be able to tell the diffrence when you look up the channel later. So I added the username to the channel name.
const embed = new MessageEmbed()
.setTitle(`Teleporter!`)
.setDescription("Through this interaction, you can now teleport to the main channel of the desired category!");
const row = new MessageActionRow()
.addComponents(
new MessageSelectMenu()
.setCustomId('teleport')
.setPlaceholder('Choose a channel')
.addOptions([{
label: 'Rules',
description: "Click to check the rules",
value: 'rules',
}, {
label: 'General',
description: "Click to go to the main chat",
value: 'general',
}, {
label: 'Media',
description: "Click to go to media channel",
value: 'media',
}, {
label: 'Bots',
description: "Click to go to the bots channel",
value: 'bots',
}]),
);
await newChannel.send({
content: `${msg.author}`,
embeds: [embed],
components: [row],
});
};
This section would go either in the main bot.js file, or if you have your events in seperate files, it would go in the interactionCreate file (may need to be changed a bit if you don't have one, let me know)
const wait = require('util').promisify;
client.on('interactionCreate', async interaction => {
const member = interaction.member;
const guild = interaction.guild;
if (interaction.isSelectMenu()) {
const menuName = interaction.customId;
interaction.deferUpdate();
if (menuName === 'teleport') {
const tele = guild.channels.cache.find(channel => channel.name == `teleporter-${member.user.username}`);
// lookup the channel using the previously mentioned channel name setup
const choice = interaction.value;
if (choice === 'general') {
member.roles.add('958421069650337822');
member.roles.remove('943159431800172584');
} else if (choice === 'rules') {
member.roles.add('roleID');
member.roles.remove('roleID');
} else if (choice === 'media') {
member.roles.add('roleID');
member.roles.remove('roleID');
} else if (choice === 'bots') {
member.roles.add('roleID');
member.roles.remove('roleID');
}
tele.delete();
}
}
});
I want to add info to database and I'm getting the "This interaction failed" error in discord
Using better-sqlite3, discord.js v13
For the code, I've used bits and pieces of tutorials and guides from around the internet and I think some of that may have interfered with what's already been written
const { MessageActionRow, MessageButton, MessageEmbed } = require('discord.js');
const db = require("better-sqlite3")("../../main.db")
module.exports = {
name: 'test',
description: "test buy",
options: [
{
name: 'buy',
description: 'ซื้อสคริป',
type: "SUB_COMMAND",
options: [
{
name: "link",
description: "ลิ้งซองเงิน 99 บาท",
type: "STRING",
required: true,
}
]
},
],
run: async(client, interaction, args) => {
if (interaction.options.getSubcommand() === 'buy') {
const button = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId('confirm')
.setLabel('c')
.setStyle('SUCCESS'),
new MessageButton()
.setCustomId('cancel')
.setLabel('b')
.setStyle('DANGER'),
new MessageButton()
.setURL('https://www.youtube.com/')
.setLabel('a')
.setStyle('LINK'),
);
const embed = new MessageEmbed()
.setColor('#FF0000')
.setTitle('ShuShi')
.setDescription('info')
await interaction.reply({ephemeral: true, embeds: [embed], components: [button] });
const filter = i => i.user.id === interaction.member.id;
const collector = interaction.channel.createMessageComponentCollector({
filter,
time: 600000,
max: 1
});
collector.on('collect', async i => {
collector.stop();
if (i.customId === 'confirm') {
db.prepare(`INSERT INTO discorddata VALUES(:id,:own)`).run({
id: interaction.user.id,
own: 'true'
})
}
})
}
}}
I'm trying to create a moderation discord bot with a mute command. The mute command works in the channel that you send the command in but it doesn't work in all of the other channels. I've tried to have it go over all channels using forEach() but that doesn't seem to work. I've looked through this and tried the other solutions but its still not working. Here is the code, I hope you can help.
const Discord = require("discord.js");
const ms = require('ms')
module.exports = {
name: "mute",
aliases: [],
category: "moderation",
run: async(bot, message, args) => {
let toMute = message.guild.member(message.mentions.users.first() || message.guild.members.cache.get(args[0]));
if(!toMute) return message.channel.send("Couldn't find the user.");
if(toMute.hasPermission("MANAGE_MESSAGES")) return message.reply("Can't mute them")
let muteRole = message.guild.roles.cache.find(muteRole => muteRole.name === "Muted");
//This is where the problem starts
if(!muteRole){
muteRole = await message.guild.roles.create({ data: { name: "Muted", color: 0x000000, permissions: [] } })
message.guild.channels.cache.each(async (channel) => {
await channel.overwritePermissions(muteRole, {
"SEND_MESSAGES": false,
"ADD_REACTIONS": false,
"TALK": false
});
});
}
let muteTime = args[1];
if(!muteTime) return message.reply("Please Specify a time.");
await(toMute.roles.add(muteRole));
const mEmbed = new Discord.MessageEmbed()
.setTitle("Muted")
.addFields({ name: "Member", value: toMute, inline: false },
{ name: "Time", value: muteTime })
.setTimestamp()
message.channel.send(mEmbed)
setTimeout(function() {
toMute.roles.remove(muteRole);
message.channel.send(`<#${toMute.id}> has been unmuted`);
}, ms(muteTime))
}
}
I changed the overwritePermissions() to updateOverwrite() and it seemed to work. Here is the code:
if(!muteRole){
muteRole = await message.guild.roles.create({
data: {
name: "Muted",
color: "#000000",
permissions: [],
},
});
message.guild.channels.cache.forEach(async (channel, id) => {
await channel.updateOverwrite(muteRole, {
SEND_MESSAGES: false,
SPEAK: false,
ADD_REACTIONS: false
})
});
}
I also organized the code to make it easier to see.