How to embed a message in a command base - discord.js

I am using WOK's advanced command handler and I just want the final message that will be returned to be an embed.
I am working on a specific test command where I type the prefix (for example !) when I run !add 5 10 I want the bot to ping me so it says #Ping , 5 + 10 = 15.
I want to solve 2 things:
I don't want the comma after the ping
I want the message that appears on discord to be an embed.
Here is the code for the command base:
const Discord = require('discord.js')
const { prefix } = require('../config.json')
const validatePermissions = (permissions) => {
const validPermissions = [
'ADMINISTRATOR',
'CREATE_INSTANT_INVITE',
'KICK_MEMBERS',
'BAN_MEMBERS',
'MANAGE_CHANNELS',
'MANAGE_GUILD',
'ADD_REACTIONS',
'VIEW_AUDIT_LOG',
'PRIORITY_SPEAKER',
'STREAM',
'VIEW_CHANNEL',
'SEND_MESSAGES',
'SEND_TTS_MESSAGES',
'MANAGE_MESSAGES',
'EMBED_LINKS',
'ATTACH_FILES',
'READ_MESSAGE_HISTORY',
'MENTION_EVERYONE',
'USE_EXTERNAL_EMOJIS',
'VIEW_GUILD_INSIGHTS',
'CONNECT',
'SPEAK',
'MUTE_MEMBERS',
'DEAFEN_MEMBERS',
'MOVE_MEMBERS',
'USE_VAD',
'CHANGE_NICKNAME',
'MANAGE_NICKNAMES',
'MANAGE_ROLES',
'MANAGE_WEBHOOKS',
'MANAGE_EMOJIS_AND_STICKERS',
'USE_SLASH_COMMANDS',
'REQUEST_TO_SPEAK',
'MANAGE_THREADS',
'USE_PUBLIC_THREADS',
'USE_PRIVATE_THREADS',
'USE_EXTERNAL_STICKERS',
]
for (const permission of permissions) {
if (!validPermissions.includes(permission)) {
throw new Error(`Unknown permission node "${permission}"`)
}
}
}
module.exports = (client, commandOptions) => {
let {
commands,
expectedArgs = '',
permissionError = 'You do not have the permission to run this command.',
minArgs = 0,
maxArgs = null,
permissions = [],
requiredRoles = [],
callback
} = commandOptions
if (typeof commands === 'string') {
commands = [commands]
}
console.log(`Registering the "${commands[0]}" command!`)
if (permissions.length) {
if (typeof permissions === 'string') {
permissions = [permissions]
}
validatePermissions(permissions)
}
client.on('message', (message) => {
const { member, content, guild } = message
for (const alias of commands) {
const command = `${prefix}${alias.toLowerCase()}`
if (
content.toLowerCase().startsWith(`${command} `) ||
content.toLowerCase() === command
) {
for (const permission of permissions) {
if (!member.hasPermission(permission)) {
message.reply(permissionError)
return
}
}
for (const requiredRole of requiredRoles) {
const role = guild.roles.cache.find((role) => role.name === requiredRole)
if (!role || !member.roles.cache.has(role.id)) {
message.reply(`You must have the "${requiredRole}" role to use this command.`)
return
}
}
const arguments = content.split(/[ ]+/)
arguments.shift()
if (arguments.length < minArgs || (
maxArgs !== null && arguments.length > maxArgs
)) {
const embed = new Discord.MessageEmbed()
embed.setTitle(`Incorrect syntax! Use ${prefix}${alias} ${expectedArgs}`)
message.reply(embed)
return
}
callback(message, arguments, arguments.join(' '), client)
return
}
}
})
}
And here is the code for the specific add command:
module.exports = {
commands: ['add', 'addition'],
expectedArgs: '<num1> <num2>',
permissionError: 'You do not have the permission to run this command.',
minArgs: 2,
maxArgs: 2,
callback: (message, arguments, text) => {
const num1 = +arguments[0]
const num2 = +arguments[1]
message.reply(`${num1} + ${num2} = ${num1 + num2}`)
},
permissions: ['SEND_MESSAGES'],
requiredRoles: ['.๐„๐—๐„ โ‚ช | ๐•๐ž๐ซ๐ข๐Ÿ๐ข๐ž๐'],
}
Please advise.

require discord.js in your function and use Discord.MessageEmbed() to create the embed.
To ping the user who ran the command use <#${message.author.id}>
module.exports = {
commands: ['add', 'addition'],
expectedArgs: '<num1> <num2>',
permissionError: 'You do not have the permission to run this command.',
minArgs: 2,
maxArgs: 2,
callback: (message, arguments, text) => {
const Discord = require("discord.js")
const num1 = +arguments[0]
const num2 = +arguments[1]
const addEmbed = new Discord.MessageEmbed()
.setTitle(`<#${message.author.id}> ${num1} + ${num2} = ${num1 + num2}`)
message.reply(addEmbed)
},
permissions: ['SEND_MESSAGES'],
requiredRoles: ['.๐„๐—๐„ โ‚ช | ๐•๐ž๐ซ๐ข๐Ÿ๐ข๐ž๐'],
}

Related

discord interaction.deferUpdate() is not a function

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

I keep getting an error in my !giverole command

When the owner of the server runs the command, it works but whenever any other admin/person with admin privileges uses it, the bot replies with "You do not have the required permissions"
Here is the code:
module.exports = {
commands: ['giverole', 'addrole', 'ar','gr'], // The command names/aliases
permissions: 'ADMINISTRATOR', //required permissions
requiredRoles: ['Admins'], // required roles
callback: (message, arguments) => {
const targetUser = message.mentions.users.first()
if (!targetUser) {
message.channel.send('Please specify someone to give a role to.')
return
}
arguments.shift()
const roleName = arguments.join(' ')
const { guild } = message
const role = guild.roles.cache.find((role) => {
return role.name === roleName
})
if (!role) {
message.channel.send(`There is no role with the name "${roleName}"`)
return
}
const member = guild.members.cache.get(targetUser.id)
member.roles.add(role)
message.channel.send(`That user now has the "${roleName}" role`)
},
}
Edit: Here is the command base since it was asked for by #Caladan
const validatePermissions = (permissions) => {
const validPermissions = [
'CREATE_INSTANT_INVITE',
'KICK_MEMBERS',
'BAN_MEMBERS',
'ADMINISTRATOR',
'MANAGE_CHANNELS',
'MANAGE_GUILD',
'ADD_REACTIONS',
'VIEW_AUDIT_LOG',
'PRIORITY_SPEAKER',
'STREAM',
'VIEW_CHANNEL',
'SEND_MESSAGES',
'SEND_TTS_MESSAGES',
'MANAGE_MESSAGES',
'EMBED_LINKS',
'ATTACH_FILES',
'READ_MESSAGE_HISTORY',
'MENTION_EVERYONE',
'USE_EXTERNAL_EMOJIS',
'VIEW_GUILD_INSIGHTS',
'CONNECT',
'SPEAK',
'MUTE_MEMBERS',
'DEAFEN_MEMBERS',
'MOVE_MEMBERS',
'USE_VAD',
'CHANGE_NICKNAME',
'MANAGE_NICKNAMES',
'MANAGE_ROLES',
'MANAGE_WEBHOOKS',
'MANAGE_EMOJIS',
]
for (const permission of permissions) {
if (!validPermissions.includes(permission)) {
throw new Error(`Unknown permission node "${permission}"`)
}
}
}
module.exports = (client, commandOptions) => {
let {
commands,
expectedArgs = '',
permissionError = 'You do not have permission to run this command.',
minArgs = 0,
maxArgs = null,
cooldown = -1,
requiredChannel = '',
permissions = [],
requiredRoles = [],
callback,
} = commandOptions
// Ensure the command and aliases are in an array
if (typeof commands === 'string') {
commands = [commands]
}
console.log(`Registering command "${commands[0]}"`)
// Ensure the permissions are in an array and are all valid
if (permissions.length) {
if (typeof permissions === 'string') {
permissions = [permissions]
}
validatePermissions(permissions)
}
Hope it helps in figuring out the issue.

TypeError: Cannot read property '0' of undefined on discord.js

I am using the WOK Command Handler and it was working fine for a few commands, then it suddenly stopped working when I created a new command, then went backwards and deleted the command, and still got the same error meaning that the error is in this file.
It's giving the error for the console.log(`Registering the "${commands[0]}" command!`) snippet.
const Discord = require('discord.js')
const { prefix } = require('../config.json')
const validatePermissions = (permissions) => {
const validPermissions = [
'ADMINISTRATOR',
'CREATE_INSTANT_INVITE',
'KICK_MEMBERS',
'BAN_MEMBERS',
'MANAGE_CHANNELS',
'MANAGE_GUILD',
'ADD_REACTIONS',
'VIEW_AUDIT_LOG',
'PRIORITY_SPEAKER',
'STREAM',
'VIEW_CHANNEL',
'SEND_MESSAGES',
'SEND_TTS_MESSAGES',
'MANAGE_MESSAGES',
'EMBED_LINKS',
'ATTACH_FILES',
'READ_MESSAGE_HISTORY',
'MENTION_EVERYONE',
'USE_EXTERNAL_EMOJIS',
'VIEW_GUILD_INSIGHTS',
'CONNECT',
'SPEAK',
'MUTE_MEMBERS',
'DEAFEN_MEMBERS',
'MOVE_MEMBERS',
'USE_VAD',
'CHANGE_NICKNAME',
'MANAGE_NICKNAMES',
'MANAGE_ROLES',
'MANAGE_WEBHOOKS',
'MANAGE_EMOJIS_AND_STICKERS',
'USE_SLASH_COMMANDS',
'REQUEST_TO_SPEAK',
'MANAGE_THREADS',
'USE_PUBLIC_THREADS',
'USE_PRIVATE_THREADS',
'USE_EXTERNAL_STICKERS',
]
for (const permission of permissions) {
if (!validPermissions.includes(permission)) {
throw new Error(`Unknown permission node "${permission}"`)
}
}
}
const allCommands = {
}
module.exports = (commandOptions) => {
let {
commands,
permissions = [],
} = commandOptions
if (typeof commands === 'string') {
commands = [commands]
}
console.log(`Registering the "${commands[0]}" command!`)
if (permissions.length) {
if (typeof permissions === 'string') {
permissions = [permissions]
}
validatePermissions(permissions)
}
for (const command of commands) {
allCommands[command] = {
...commandOptions,
commands,
permissions
};
}
}
module.exports.listen = (client) => {
client.on('message', (message) => {
const { member, content, guild } = message;
const arguments = content.split(/[ ]+/);
const name = arguments.shift().toLowerCase();
if (name.startsWith(prefix)) {
const command = allCommands[name.replace(prefix, '')]
if (!command) {
return
}
const {
permissions,
permissionError = "You do not have the permission to run this command.",
requiredRoles = [],
minArgs = 0,
maxArgs = null,
expectedArgs,
callback
} = command
for (const permission of permissions) {
if (!member.hasPermission(permission)) {
message.reply(permissionError)
return
}
}
for (const requiredRole of requiredRoles) {
const role = guild.roles.cache.find((role) => role.name === requiredRole)
if (!role || !member.roles.cache.has(role.id)) {
message.reply(`You must have the "${requiredRole}" role to use this command.`)
return
}
}
if (arguments.length < minArgs || (
maxArgs !== null && arguments.length > maxArgs
)) {
const embed = new Discord.MessageEmbed()
embed.setTitle(`Incorrect syntax! Use ${prefix}${alias} ${expectedArgs}`)
message.reply(embed)
return
}
callback(message, arguments, arguments.join(' '), client)
}
})
}

TypeError: Cannot read property 'toLowerCase' of undefined discord.js

I'm developing a discord.js moderation bot, but when I run it I get this error.
Here is the code:
var Discord = require('discord.js')
const fs = require("fs")
const { PREFIX } = require("../../config")
const db = require('quick.db')
const { stripIndents } = require("common-tags");
module.exports = {
config: {
name: "help",
description: "Help Menu",
usage: "1) m/help \n2) m/help [module name]\n3) m/help [command (name or alias)]",
example: "1) m/help\n2) m/help utility\n3) m/help ban",
aliases: ['h']
},
run: async (bot, message, args) => {
let prefix;
if (message.author.bot || message.channel.type === "dm") return;
try {
let fetched = await db.fetch(`prefix_${message.guild.id}`);
if (fetched == null) {
prefix = PREFIX
} else {
prefix = fetched
}
} catch (e) {
console.log(e)
};
if(message.content.toLowerCase() === `${prefix}help`){
var log = new Discord.MessageEmbed()
.setTitle("**Help Menu: Main**")
.setColor(`#d9d9d9`)
.addField(`**๐Ÿ‘‘Moderation**`, `[ \`${prefix}help mod\` ]`, true)
.addField(`**โš™๏ธUtility**`, `[ \`${prefix}help utility\` ]`, true)
message.channel.send(log);
}
else if(args[0].toLowerCase() === "mod") {
var commandArray = "1) Ban \n2) Kick\n3) Whois\n4) Unban\n5) Warn\n6) Mute\n7) Purge\n8) Slowmode \n9) Nick \n10) Roleinfo"
var commandA2 = "11) Rolememberinfo\n12) Setmodlog\n13) Disablemodlog\n14) Lock (Lock the channel)\n15) Unlock (Unlock the channel)\n16) Lockdown (Fully Lock the whole server. [FOR EMRGENCIES ONLY]) \n17) Hackban\\forceban <id>"
pageN1 = "**\n๐Ÿ’ Commands: **\n`\`\`js\n" + commandArray + "\`\`\`";
pageN2 = "**\n๐Ÿ’ Commands: **\n`\`\`js\n" + commandA2 + "\`\`\`";
let pages = [pageN1, pageN2]
let page = 1
var embed = new Discord.MessageEmbed()
.setTitle('**Help Menu: [Moderation]๐Ÿ‘‘**')
.setColor("#d9d9d9") // Set the color
.setFooter(`Page ${page} of ${pages.length}`, bot.user.displayAvatarURL())
.setDescription(pages[page-1])
message.channel.send({embed}).then(msg => {
msg.react('โฌ…').then( r => {
msg.react('โžก')
// Filters
const backwardsFilter = (reaction, user) => reaction.emoji.name === 'โฌ…' && user.id === message.author.id
const forwardsFilter = (reaction, user) => reaction.emoji.name === 'โžก' && user.id === message.author.id
const backwards = msg.createReactionCollector(backwardsFilter, {timer: 6000})
const forwards = msg.createReactionCollector(forwardsFilter, {timer: 6000})
backwards.on('collect', (r, u) => {
if (page === 1) return r.users.remove(r.users.cache.filter(u => u === message.author).first())
page--
embed.setDescription(pages[page-1])
embed.setFooter(`Page ${page} of ${pages.length}`, bot.user.displayAvatarURL())
msg.edit(embed)
r.users.remove(r.users.cache.filter(u => u === message.author).first())
})
forwards.on('collect', (r, u) => {
if (page === pages.length) return r.users.remove(r.users.cache.filter(u => u === message.author).first())
page++
embed.setDescription(pages[page-1])
embed.setFooter(`Page ${page} of ${pages.length}`, bot.user.displayAvatarURL())
msg.edit(embed)
r.users.remove(r.users.cache.filter(u => u === message.author).first())
})
})
})
}
else if(args[0].toLowerCase() === "util") {
var embed = new Discord.MessageEmbed()
.setTitle('**Help Menu: [Utility]**')
.setColor("#d9d9d9") // Set the color
.setDescription("```js" + `1) Prefix [${prefix}help prefix for more info]\n 2) Help [${prefix}help for more info]` + "```")
} else {
const embed = new Discord.MessageEmbed()
.setColor("#d9d9d9")
.setAuthor(`${message.guild.me.displayName} Help`, message.guild.iconURL())
.setThumbnail(bot.user.displayAvatarURL())
let command = bot.commands.get(bot.aliases.get(args[0].toLowerCase()) || args[0].toLowerCase())
if (!command) return message.channel.send(embed.setTitle("**Invalid Command!**").setDescription(`**Do \`${prefix}help\` For the List Of the Commands!**`))
command = command.config
embed.setDescription(stripIndents`
** Command -** [ \`${command.name.slice(0, 1).toUpperCase() + command.name.slice(1)}\` ]\n
** Description -** [ \`${command.description || "No Description provided."}\` ]\n
** Usage -** [ \`${command.usage ? `\`${command.usage}\`` : "No Usage"}\` ]\n
** Examples -** [ \`${command.example ? `\`${command.example}\`` : "No Examples Found"}\` ]\n
** Aliases -** [ \`${command.aliases ? command.aliases.join(" , ") : "None."}\` ]`)
embed.setFooter(message.guild.name, message.guild.iconURL())
return message.channel.send(embed)
}
}
}
If someone could help with this issue it would be great because I don't know what to do. I already searched on internet but I still don't know what I need to do to solve this error. All this code is for help function, when someone calls -pks help the bot should show embed telling all his functions
Here is my index.js file:
const { Client, Collection } = require('discord.js');
const { PREFIX, TOKEN } = require('./config');
const bot = new Client({ disableMentions: 'everyone' });
const fs = require("fs");
const db = require('quick.db');
bot.commands = new Collection();
bot.aliases = new Collection();
["aliases", "commands"].forEach(x => bot[x] = new Collection());
["console", "command", "event"].forEach(x => require(`./handler/${x}`)(bot));
bot.categories = fs.readdirSync("./commands/");
["command"].forEach(handler => {
require(`./handler/${handler}`)(bot);
});
bot.on('message', async message => {
let prefix;
try {
let fetched = await db.fetch(`prefix_${message.guild.id}`);
if (fetched == null) {
prefix = PREFIX
} else {
prefix = fetched
}
} catch {
prefix = PREFIX
};
try {
if (message.mentions.has(bot.user.id) && !message.content.includes("#everyone") && !message.content.includes("#here")) {
message.channel.send(`\nMy prefix for \`${message.guild.name}\` is \`${prefix}\` Type \`${prefix}help\` for help`);
}
} catch {
return;
};
});
bot.login(TOKEN);

How to take multiple input one by one in - discord.js

How do I take input from user multiple times, store it, and then send an embed with the inputs?
User types command ?start
Bot replies "Hi type your name here"
User types a name, then it is stored in a variable
Bot asks again "Type your favourite game now"
User types games, it is again stored in a variable
Then the variables are taken and then made into an embed
const embed = new Discord.MessageEmbed()
.setTitle("Hobbies")
.setThumbnail(messsage.author.user.displayAvatarURL())
.addDescription("<name>")
.addDescription("<game>")
.setTimestamp();
message.channel.send(embed);
to solve that i created little "Scripts", just predefined Routines for each state of the command
script.js
class Script {
constructor (user, options, callback) {
if (!user.send) {
throw "Invalid Userhandle";
}
this.user = user;
this.options = options;
this.state = 0;
this.callback = callback;
this.responses = [];
if (!!this.options.greeting) {
this.user.send(this.options.greeting)
.then()
.catch(() => console.log(JSON.stringify(this.options.greeting)));
}
};
interpretMessage(message) {
if (!this.options.validator[this.state] || typeof this.options.validator[this.state] !== 'function') {
if (!!this.callback) {
this.callback(this.user, this.responses, false);
return;
} else {
throw "Invalid User Gatherer Object";
}
}
const [msg, steps] = this.options.validator[this.state](message, this.responses);
this.user.send(msg)
.then()
.catch(() => console.error(msg));
if (steps > 0 || steps < 0) {
if (!!this.responses && !!this.responses[this.state]) {
this.responses[this.state] = message;
} else {
this.responses.push(message);
}
this.state += steps;
}
if (this.state >= this.options.validator.length) {
this.callback(this.user, this.responses, false);
}
};
};
module.exports = Script;
I use this Method only in private Messages, that's the reason for my naming:
msg_script.js
const Script = require('./classes/script');
let privateInfoGatherer = {};
let privateInfoGathererCallback = {};
function deletePrivateInfoGatherer(usr, out) {
if (!usr || !usr.id) {
return;
}
privateInfoGathererCallback[usr.id](usr, out);
delete privateInfoGatherer[usr.id];
delete privateInfoGathererCallback[usr.id];
};
function PrivateInfoGatherer (usr, opts, callback) {
if (!usr || !usr.id || !opts || !callback) {
return;
}
privateInfoGatherer[usr.id] = new Script(usr, opts, deletePrivateInfoGatherer);
privateInfoGathererCallback[usr.id] = callback;
};
function checkPrivateMessage(msg, args) {
if (!msg || !msg.author || !privateInfoGatherer[msg.author.id] || msg.guild) {
return;
}
privateInfoGatherer[msg.author.id].interpretMessage(msg.content);
};
module.exports = {
provide: {
PrivateInfoGatherer: PrivateInfoGatherer,
},
events: {
message: checkPrivateMessage,
}
};
my final usage looked something like this:
const ressource = require('./classes/ressource');
function interpretAuth(msg, args, provider) {
const usr = msg.author;
const stage_1 = (msg) => {
let steps = msg.match("^([A-Za-z0-9_ ]{4,32})$") ? 1 : 0;
let ret;
if (msg === 'abort') {
steps = 100; // will result in ending the script
} else {
ret = steps === 1 ? 'And now your Password' : 'Gimme your username';
}
return [ret, steps];
};
const stage_2 = (msg) => {
let steps = msg.match("^([A-Za-z0-9\\!\\#\\#\\%\\&\\_\\(\\)\\*\\-\\$\\^\\[\\]]+)$") ? 1 : 0;
let ret;
if (msg === 'abort') {
steps = 100;
} else {
ret = steps === 1 ? 'I will check the Auth' : 'Your Password man...';
}
return [ret, steps];
};
const options = {
greeting: 'Ok for Authrole i need your login, so first your username pls',
validator: [
stage_1,
stage_2,
]
};
const callback = (usr, out) => {
const [username, password] = out;
// Now we have all, do what ever you want with it.
};
provider.PrivateInfoGatherer(usr, options, callback);
};

Resources