I have another question concerning my catch cmd. If I wanted to make it so that it was no longer an activable command but instead had a small chance of triggering when anyone speaks ever, how would I go about that? Would I need to put it in my message.js file? I know if I put it there as is it will trigger every time someone uses a command. However, I don't want it limited to someone using a command and I don't want it to happen every time. I've also heard of putting it in a separate json file and linking it back somehow. Any help is appreciated.
const profileModel = require("../models/profileSchema");
module.exports = {
name: "catch",
description: "users must type catch first to catch the animal",
async execute(client, message, msg, args, cmd, Discord, profileData) {
const prey = [
"rabbit",
"rat",
"bird",
];
const caught = [
"catch",
];
const chosenPrey = prey.sort(() => Math.random() - Math.random()).slice(0, 1);
const whenCaught = caught.sort(() => Math.random() - Math.random()).slice(0, 1);
const filter = ({ content }) => whenCaught.some((caught) => caught.toLowerCase() == content.toLowerCase());
const collector = message.channel.createMessageCollector({ max: 1, filter, time: 15000 });
const earnings = Math.floor(Math.random() * (20 - 5 + 1)) + 5;
collector.on('collect', async (m) => {
if(m.content?.toLowerCase() === 'catch') {
const user = m.author;
const userData = await profileModel.findOne({ userID: user.id });
message.channel.send(`${userData.name} caught the ${chosenPrey}! You gained ${earnings} coins.`);
}
await profileModel.findOneAndUpdate(
{
userID: m.author.id,
},
{
$inc: {
coins: earnings,
},
}
);
});
collector.on('end', (collected, reason) => {
if (reason == "time") {
message.channel.send('Too slow');
}
});
message.channel.send(`Look out, a ${chosenPrey}! Type CATCH before it gets away!`);
}
}
message.js file just in case
const profileModel = require("../../models/profileSchema");
const cooldowns = new Map();
module.exports = async (Discord, client, message) => {
let profileData;
try {
profileData = await profileModel.findOne({ userID: message.author.id });
if(!profileData){
let profile = await profileModel.create({
name: message.member.user.tag,
userID: message.author.id,
serverID: message.guild.id,
coins: 0,
});
profile.save();
}
} catch (err) {
console.log(err);
}
const prefix = '-';
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const cmd = args.shift().toLowerCase();
const command = client.commands.get(cmd) || client.commands.find(a => a.aliases && a.aliases.includes(cmd));
if(!command) return;
if(!cooldowns.has(command.name)){
cooldowns.set(command.name, new Discord.Collection());
}
const current_time = Date.now();
const time_stamps = cooldowns.get(command.name);
const cooldown_amount = (command.cooldown) * 1000;
if(time_stamps.has(message.author.id)){
const expiration_time = time_stamps.get(message.author.id) + cooldown_amount;
if(current_time < expiration_time){
const time_left = (expiration_time - current_time) / 1000;
return message.reply(`Slow down there! You have to wait ${time_left.toFixed(0)} seconds before you can perform ${command.name} again.`);
}
}
if(command) command.execute(client, message, args, cmd, Discord, profileData);
}
Yes...that can be possible. In your command handler, create and export a variable with a boolean
Make sure to do this in global scope (outside any function)
let canBeActivated = true;
module.exports.getCanBeActivated = function () { return canBeActivated };
module.exports.setCanBeActivated = function(value) { canBeActivated = value };
Then, in your command file, import it and check whether it can be activated
const { getCanBeActivated, setCanBeActivated } = require("path/to/message.js")
module.exports = {
...
execute(...) {
// command wont run
if(!getCanBeActivated()) return
}
You can make some logic to make the command run if canBeActivated is false (like get a random number between 1-100 and if it matches 4 run it).In case you need to change it, just run, setCanBeActivated
Related
So i tried following the https://discordjs.guide/additional-info/rest-api.html guide before making my own. But I can't get either to work.
Firstly with /cat it crashes and the console returns with:
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at getJSONResponse (BOTLOCATION\index.js:77:14)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Client.<anonymous> (BOTLOCATION\index.js:90:20)
And /urban works but no matter what term I enter it returns with NULL.
Here is the code, its nearly identical from the guides apart from the added SlashCommandBuilder and REST.
const { request } = require('undici');
const clientId = 'CLIENTID_HERE';
const guildId = 'GUILDID_HERE';
const { SlashCommandBuilder } = require('#discordjs/builders');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const commands = [
new SlashCommandBuilder().setName('cat').setDescription('Cat thing idk'),
new SlashCommandBuilder().setName('urban').setDescription('Urban Dictionary Thing'),
]
.map(command => command.toJSON());
const rest = new REST({ version: '9' }).setToken("TOKEN_HERE");
rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
//rest.put(Routes.applicationGuildCommands(clientId), { body: commands })
.then(() => console.log('Successfully registered application commands.'))
.catch(console.error);
const trim = (str, max) => (str.length > max ? `${str.slice(0, max - 3)}...` : str);
async function getJSONResponse(body) {
let fullBody = '';
for await (const data of body) {
fullBody += data.toString();
}
return JSON.parse(fullBody);
}
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const { commandName } = interaction;
await interaction.deferReply();
if (commandName === 'cat') {
const catResult = await request('https://aws.random.cat/meow');
const { file } = await getJSONResponse(catResult.body);
interaction.reply({ files: [{ attachment: file, name: 'cat.png' }] });
} else if (commandName === 'urban') {
const term = interaction.options.getString('term');
const query = new URLSearchParams({ term });
const dictResult = await request(`https://api.urbandictionary.com/v0/define?${query}`);
const { list } = await getJSONResponse(dictResult.body);
if (!list.length) {
return interaction.editReply(`No results found for **${term}**.`);
}
const [answer] = list;
const embed = new MessageEmbed()
.setColor('#EFFF00')
.setTitle(answer.word)
.setURL(answer.permalink)
.addFields(
{ name: 'Definition', value: trim(answer.definition, 1024) },
{ name: 'Example', value: trim(answer.example, 1024) },
{
name: 'Rating',
value: `${answer.thumbs_up} thumbs up. ${answer.thumbs_down} thumbs down.`,
},
);
interaction.editReply({ embeds: [embed] });
}
});
So for the cat command since there is a deferReply first we need to use editReply since deferReply counts as the first/initial reply.
await interaction.deferReply();
const catResult = await request('https://aws.random.cat/meow').catch((err) => { console.log(err); });;
const { file } = await getJSONResponse(catResult.body).catch((err) => { console.log(err); });
return await interaction.editReply({ files: [{ attachment: file, name: 'cat.png' }] });
I also added a .catch to the end of each await, this was just for testing however I recommend it.
Now with the urban command, the reason it is using null is since you don't have the string option's text. We can check for it by adding an if statement.
await interaction.deferReply();
const term = interaction.options.getString('term');
if (!term) return await interaction.editReply('Please provide a term.'); // We need to add this check to see if the user provided the term option or not.
const query = new URLSearchParams({ term });
const dictResult = await request(`https://api.urbandictionary.com/v0/define?${query}`);
const { list } = await getJSONResponse(dictResult.body);
if (!list.length) {
return interaction.editReply(`No results found for **${term}**.`);
}
const [answer] = list;
const embed = new MessageEmbed()
.setColor('#EFFF00')
.setTitle(answer.word)
.setURL(answer.permalink)
.addFields(
{ name: 'Definition', value: trim(answer.definition, 1024) },
{ name: 'Example', value: trim(answer.example, 1024) },
{
name: 'Rating',
value: `${answer.thumbs_up} thumbs up. ${answer.thumbs_down} thumbs down.`,
},
);
return await interaction.editReply({ embeds: [embed] });
IMPORTANT: When you are building your slash command you are not setting a string option. In the commands array, when creating the second slash command called urban we will add the support for the string option there. (An example using the string option, discord.js guide all command options)
This is how we can do this:
const commands = [
new SlashCommandBuilder().setName('cat')
.setDescription('Cat thing idk'),
new SlashCommandBuilder()
.setName('urban')
.setDescription('Urban Dictionary Thing')
.addStringOption((option) => option.setName('term').setDescription('term')) // We first add the string option then set the name to 'term' which is what the code calls for and then the description.
].map((command) => command.toJSON());
If you would like to make the term input required, add .setRequired(true) which will not allow the command to be ran without entering the term to search.
Once you do that you should be all good! Tested the code and it's working once that's fixed
So I am trying to make a suggestion command using discord buttons in Discord.JS. When I run the command the embed and the buttons send but whenever I click one of the buttons whether it be Upvote, Maybe, or Downvote it edits the embed, but it never updates the number. I've tried upvote_number ++ and upvote_number + 1 but it doesn't work. It would be awesome if somebody could help me with this. Thank you.
const Discord = require('discord.js');
const disbut = require('discord-buttons');
const { MessageActionRow, MessageButton } = require("discord-buttons");
const { Color, Prefix } = require("../../config.js");
const { MessageEmbed } = require("discord.js");
const disbutpages = require("discord-embeds-pages-buttons")
const db = require('quick.db');
module.exports = {
name: "suggest",
aliases: [],
description: "Suggestion Command",
usage: "^suggest <suggestion>",
run: async(client, message, args) => {
const SayMessage = message.content.slice(8).trim();
let upvote_number = 0
let downvote_number = 0
let maybe_number = 0
const embed = new Discord.MessageEmbed()
.setAuthor("Suggestion from: " + message.author.tag, message.author.displayAvatarURL({dynamic: true}))
.setThumbnail(message.author.displayAvatarURL({dynamic: true}))
.setDescription(SayMessage)
.addField(`Votes`, `Upvote: **${upvote_number}**
Downvote: **${downvote_number}**`)
let upvotebutton = new MessageButton()
.setLabel(`Upvote`)
.setID(`upvote`)
.setEmoji(`⬆️`)
.setStyle("green")
let maybebutton = new MessageButton()
.setLabel(`Maybe`)
.setID(`maybe`)
.setEmoji(`🤷`)
.setStyle("blurple")
let downvotebutton = new MessageButton()
.setLabel(`Downvote`)
.setID(`downvote`)
.setEmoji(`⬇️`)
.setStyle("red")
let row = new MessageActionRow()
.addComponents(upvotebutton, maybebutton, downvotebutton)
const MESSAGE = await message.channel.send(embed, { components: [row] })
const filter = ( button ) => button.clicker.user.id === message.author.id
const collector = MESSAGE.createButtonCollector(filter, { time : 120000 });
collector.on('collect', async (b) => {
if(b.id == "upvote") {
await upvote_number + 1
await MESSAGE.edit(embed, { components: [row] });
await b.reply.defer()
}
if(b.id == "downvote") {
downvote_number + 1
MESSAGE.edit(embed, { components: [row] });
await b.reply.defer()
}
if(b.id == "maybe") {
maybe_number + 1
MESSAGE.edit(embed, { components: [row] });
await b.reply.defer()
}
})
collector.on('end', (b) => {
})
}
};
You'd want to use the += operator for your question. By the way, because of how button collectors work, the suggestions will be timing out after some time, which may cause you some issues in the future, so you may want to switch to the event. My only other concerns are that you are using d.js 12 and discord-buttons which are both deprecated. As d.js 12 is losing support soon because of discord's api updates, I'd highly recommend switching to v13, as it has built in buttons, along with many other new features such as menus and slash commands.
let upvote_number = 0
let downvote_number = 0
let maybe_number = 0
/* ... */
collector.on('collect', async b => {
if(b.id == "upvote") {
upvote_number += 1
updateEmbed()
await MESSAGE.edit(embed, { components: [row] })
await b.reply.defer()
} else if (b.id == "downvote") {
downvote_number += 1
updateEmbed()
await MESSAGE.edit(embed, { components: [row] })
await b.reply.defer()
} else if (b.id == "maybe") {
maybe_number += 1
updateEmbed()
await MESSAGE.edit(embed, { components: [row] })
await b.reply.defer()
}
});
updateEmbed(){
embed.fields.find(i=>i.name==='Votes').value = `Upvote: **${upvote_number}**
Downvote: **${downvote_number}**`
}
tldr: Use += to set vars dynamically as well as update the embed object, and update to `discord.js#latest`
So I want my bot for everytime it boots up I want it to join a specific vc and to play some music! Although, I have come accross a problem. I tried doing this with an id and it worked fine but doing it with json causes some errors and keeps saying that it can't join of undefined. Here is my code:
Processor:
const ytdl = require('ytdl-core-discord');
const editJsonFile = require("edit-json-file");
var fs = require('file-system');
var path = require('path');
const ytfps = require('ytfps');
const prefix = "v_";
let value = true;
let temp;
exports.run = async (client, message, args, ops) => {
const idchannel = client.channels.cache.find(channel => channel.id === "815183065843499008");
const ytchannel = client.channels.cache.find(channel => channel.id === "815183091244597248");
let song = editJsonFile(`live/song.json`);
song.save();
let channelid = editJsonFile(`live/channelid.json`);
song.save();
let count = editJsonFile(`live/count.json`);
count.save();
let cloud = editJsonFile(`live/could.json`);
cloud.save();
let v = count.get(`v`);
let check = cloud.get(`${v}`);
let ope = channelid.get(`${v}`);
if (ope == undefined){
setTimeout(function() {
delete require.cache[require.resolve(`./liveplay.js`)];
let commandFile = require(`./liveplay.js`);
commandFile.run(client, message);
}, 1000);
}
const voiceChannel = client.channels.cache.find(channel => channel.id === `${ope}`);
if (voiceChannel == undefined){
setTimeout(function() {
delete require.cache[require.resolve(`./liveplay.js`)];
let commandFile = require(`./liveplay.js`);
commandFile.run(client, message);
}, 1000);
}
console.log(`${ope}`);
setTimeout(async function() {
try {
console.log("BIP");
setTimeout(async function() {
connection = await voiceChannel.join();
}, 100);
} catch (error) {
console.log(error);
const embed = {
"url": "https://discordapp.com",
"color": 16747962,
"fields": [
{
"name": "🛑 Error ",
"value": "There was an error connecting to the voice channel!"
}
]
};
return message.channel.send({ embed });
}
}, 5000);
setTimeout(async function() {
let ope2 = song.get(`${v}`);
dispatcher = connection.play(await ytdl(ope2), { type: 'opus' })
.on('finish', () => {
voiceChannel.leave();
})
.on('error', error => {
console.log(error);
});
dispatcher.setVolumeLogarithmic(5 / 5);
}, 7000);
count.set(`v`, v-1);
count.save();
v = count.get(`v`);
if (v < 0){
count.set(`v`, v+1);
count.save();
} else {
setTimeout(function() {
delete require.cache[require.resolve(`./liveplay.js`)];
let commandFile = require(`./liveplay.js`);
commandFile.run(client, message);
}, 8000);
}
}
Here is the join command where it actually works:
const ytdl = require('ytdl-core-discord');
const editJsonFile = require("edit-json-file");
var fs = require('file-system');
var path = require('path');
const ytfps = require('ytfps');
const prefix = "v_";
exports.run = async (client, message, args, ops) => {
var value = false;
let number = editJsonFile(`premium/premium.json`);
number.save();
let count = editJsonFile(`premium/count.json`);
count.save();
let v = count.get(`v`)
for(var i = 0; i <= v; i++){
let check = number.get(`${i}`)
if (check == message.author.id){
value = true;
}
}
if(value == false){
return message.channel.send("You do not have premium so you cant run this command");
} else {
args = message.content.substring(prefix.length).split(" ");
const voiceChannel = client.channels.cache.find(channel => channel.id === "809466736491233294");
try {
setTimeout(async function() {
connection = await voiceChannel.join();
}, 500);
} catch(e) {
console.log(e);
}
}
}
EDIT: ope is suppose to equal to the channel id!
i might not be right on this but it seems like your not properly catching the error!
it says that the channel is undefined, that can mean a lot of things. maybe you gave a wrong channel id, maybe a wrong guild id, only way to know for sure is to closely check your code for typos.
as for the error catching, try this:
const channel = client.channels.cache.get("ChannelIDhere");
if (!channel) return console.error("The channel does not exist!");
channel.join().then(connection => {
// Yay, it worked!
console.log("Successfully connected.");
}).catch(e => {
// Oh no, it errored! Let's log it to console :)
console.error(`Failed to connect to the channel! Error:\n${e}`
oh and you forgot to put var before you defined connection
If you wanna export the data from a json file you need to do editJsonFile = require('edit-json-file') then channel.id === ${editJsonFilewhat.channelid} or what ever u define the vc as in json file
in this example in the json file is
{
"channelid":"815183065843499008"
}
I was trying to setup the bot's .setActivity(), but it doesn't seem to work, though, if I do it using the eval command, it actually sets it and works. Is this because I tried calling an external functions module?
Files
Essentials: ./resources/utils/essentials.js
placeHolder(client, string) {
const owner = client.users.cache.get(client.config.admin.owner.id);
if (typeof string === "string") {
return string
.replace(/%totalCommands%/g, client.commands.array().length)
.replace(/%clientName%/g, client.name)
.replace(/%clientId%/g, client.user.id)
.replace(/%clientDescription/g, client.package.description)
.replace(/%clientUsername%/g, client.user.username)
.replace(/%clientTag%/g, client.user.tag)
.replace(/%clientDevName%/g, client.dev.name)
.replace(/%clientDevHelpers%/g, client.dev.helpers.join(", "))
.replace(/%clientDefaultPrefix%/g, client.def.prefix)
.replace(/%clientGuildCount%/g, client.guilds.cache.size)
.replace(/%clientChannelCount%/g, client.channels.cache.size)
.replace(/%clientPackageName%/g, client.package.name)
.replace(/%clientVersion%/g, client.package.version)
.replace(/%clientLicense%/g, client.package.license)
.replace(/%clientAvatarURL%/g, client.avatar)
.replace(/%clientRepository%/g, client.package.repository)
.replace(/%clientAuthor%/g, client.package.author)
.replace(/%clientOwnerUsername%/g, owner.username)
.replace(/%clientOwnerTag%/g, owner.tag)
.replace(/%clientOwnerID%/g, owner.id)
.replace(/%clientMainFile%/g, client.package.main)
.replace(/%clientOwnerAvatarURL%/g, owner.avatarURL() || owner.defaultAvatarURL)
.replace(/%clientOriginalAuthor%/g, client.package.original_author);
} else {
return string;
}
}
Event Handler for ready: ./resources/events/ready.js
const Discord = require('discord.js');
const Essentials = require("../utils/essentials.js");
module.exports = {
name: "ready", // Event Name
async execute(
client, event
) {
let activity = {};
async function setActv() {
activity.type = client.config.client.presence.activity.default.name;
activity.status = client.config.client.presence.activity.status;
activity.name = await Essentials.placeHolder(client, client.config.client.presence.activity.default.name);
client.user.setActivity(activity.name, {
type: activity.type
});
client.user.setStatus(activity.status);
}
client.footer = Essentials.placeHolder(client, client.config.client.settings.footer);
try {
// Set Activity every 30 seconds
setInterval(async () => {
await setActv().catch(err => Essentials.log(client, error))
}, 5000);
} catch (error) {
Essentials.log(client, error);
}
// Bot Ready Log //
console.log(
`Logged in as ${client.user.tag}.\n`
+ `There are ${client.users.cache.size} users and/or bots online.\n`
+ `${client.user.tag} connected to:\n${client.guilds.cache
.map(g => g.name)
.join(", ")}`
);
}
};
Main bot file: ./bot.js
client.events = new Discord.Collection();
var eventFiles = fs
.readdirSync(`./resources/events`)
.filter(file => file.endsWith(".js"));
for (var file of eventFiles) {
var event = require(`./resources/events/${file}`);
client.events.set(event.name, event);
console.log(`Loading event handler for event "${event.name}".`);
}
client.on("ready", async () => {
const event = client.events.get("ready");
if (event) {
try {
await event.execute(
client, event
)
} catch (err) {
Essentials.log(client, err)
}
}
});
Eval command: ./resources/commands/eval.js
const Discord = require('discord.js');
const Essentials = require('../utils/essentials.js')
module.exports = {
id: "eval",
name: "Eval", // Command name
description: "A simple eval tool to use on Discord.", // Command Description
aliases: ["evl", "ev"], // Command Aliases
category: "Utilities",
cooldown: 5000, // Command cooldown
examples: ["eval message.author.id", "eval process.cwd()"], // Command Examples
usage: ["<args>"], // Command Usage
permissions: ["SEND_MESSAGES", "READ_MESSAGE_HISTORY"], // Command Permissions
memberPermissions: ["SEND_MESSAGES", "READ_MESSAGE_HISTORY", "MANAGE_SERVER"], // User is required to have these permissions
admin: true, // Command is admin only
async execute(client, command, message, args, auth, channel, guild) { // Function async execute()
// Command Starts Here
try {
let evaled = eval(args.join(" "));
if (typeof evaled !== "string") evaled = require("util").inspect(evaled);
const avtr = message.author.avatarURL() || message.author.defaultAvatarURL;
const embed = new Discord.MessageEmbed()
.setAuthor(client.name, client.avatar)
.setTitle(command.name)
.setTimestamp()
.setColor(client.color.default)
.addField("**Input**", '```' + args.join(" ") + '```')
.addField("**Result**", '```' + Essentials.clean(evaled) + '```')
.setFooter(`${message.author.username} evaled`, avtr);
message.channel.send(embed);
} catch (err) {
const embed = Essentials.errorEmbed(err);
message.channel.send((embed), { split: true });
}
}
};
I've tried a lot of combinations, ranging from actually putting it outside of the Event Handler and straight to the bot.js until actually using eval(), shown above is my current code. NO error codes were thrown, and all of the other components in ready.js works, including client.footer = ..., except for setting the activity, did I miss something?
i made a discord bot with discord.js and tried to do a help command to show the user all available commands.
example command: avatar.js
module.exports.run = async(bot, message, args) => {
let msg = await message.channel.send("doing some magic ...");
let target = message.mentions.users.first() || message.author;
await message.channel.send({files: [
{
attachment: target.displayAvatarURL,
name: "avatar.png"
}
]});
msg.delete();
}
module.exports.help = {
name: "avatar",
description: "show the avatar of a user",
usage: "[#user]"
}
Then i tried to send a message with the complete list of the commands like:
command 1
description
usage
command 2
description
usage
...
help.js
const fs = require("fs");
const Discord = require("discord.js");
module.exports.run = async(bot, message, args, con) => {
fs.readdir("./cmds/", (err, files) => {
if(err) console.error(err);
let jsfiles = files.filter(f => f.split(".").pop() === "js");
if(jsfiles.length <= 0) {
console.log("No commands to load!");
return;
}
var namelist = "";
var desclist = "";
var usage = "";
let result = jsfiles.forEach((f, i) => {
let props = require(`./${f}`);
namelist = props.help.name;
desclist = props.help.description;
usage = props.help.usage;
});
message.author.send(`**${namelist}** \n${desclist} \n${usage}`);
});
}
module.exports.help = {
name: "help",
description: "show all commands",
usage: ""
}
my code is kinda working but it only sends the first command.
Im pretty new to javascript and i can't find a solution to this.
I tried to google everything on foreach maps discord collections and stuff but i cant find a example where the results get combined together.
If anybody can help me or give me a hint where i can search for something like this. Would be awesome.
The reason your code is only sending the one command is because your code only calls message.author.send('...' once. You successfully set the variables namelist, desclist, and usage with data from every file, but your .forEach(... loop just overwrites all of the data when it moves to the next files.
Try to send data inside each iteration of the .forEach(... loop like this:
var namelist = "";
var desclist = "";
var usage = "";
let result = jsfiles.forEach((f, i) => {
let props = require(`./${f}`);
namelist = props.help.name;
desclist = props.help.description;
usage = props.help.usage;
// send help text
message.author.send(`**${namelist}** \n${desclist} \n${usage}`);
});
you should do this in an Array and it'll solve the problem, so it should look like this.
module.exports.run = async(bot, message, args, con) => {
fs.readdir("./cmds/", (err, files) => {
if(err) console.error(err);
let jsfiles = files.filter(f => f.split(".").pop() === "js");
if(jsfiles.length <= 0) {
console.log("No commands to load!");
return;
}
let result = jsfiles.forEach((f, i) => {
let props = require(`./${f}`);
let filesArray = [props.help.name, props.help.description, props.help.usage]
message.author.send(`**${filesArray[0]}** \n${filesArray[1]} \n${filesArray[2]}`);
});
});
}
sorry for the late response.
Here is my take on this.... it works for me.
const Discord = require('discord.js');
const fs = require("fs");
module.exports = {
name: 'help',
description: 'Lists available commands',
async run(client, message, args, con) {
fs.readdir("./commands/", (err, files) => {
if(err) console.error(err);
let jsfiles = files.filter(f => f.split(".").pop() === "js");
if(jsfiles.length <= 0) {
console.log("No commands to load!");
return;
}
var namelist = "";
var desclist = "";
let result = jsfiles.forEach((f, i) => {
let props = require(`./${f}`);
namelist = props.name;
desclist = props.description;
message.author.send(`**${namelist}** \n${desclist} \n`);
});
});
}
I'm using DiscordJS 12 so this may not work on 11.
const discord = require('discord.js')
module.exports = {
name: 'cmd-list',
async run(client, message, args) {
const commandFiles = readdirSync(join(__dirname, "<your commands folder name>")).filter(file => file.endsWith(".js")); // Get files
const cmdmap = commandFiles.map(files => `${files}`).join(' | Working\n')
const embed = new discord.MessageEmbed()
.setDescription(cmdmap)
message.channel.send(embed)
}
}
You can just use discord 's normal embed system like this:
const { Message, MessageEmbed } = require('discord.js');
Add this to the top of your code then type everything as the following to make a normal embed like this:
const embed = new MessageEmbed()
.setTitle(`Your title!`)
.setColor(5814783)
.setTimestamp()
.setThumbnail('')
.setDescription(`Your description`)
.addFields(
{ name: 'Field 1', value: `Filed 1 Value`},
{ name: 'Field 2', value: `Filed 2 Value` },
{ name: 'Field 3', value: `Filed 3 Value`, inline: true },
{ name: 'Field 4', value: `Filed 4 Value`, inline: true },
{ name: 'Field 5', value: `Field 5 Value`, inline: true },
)
message.channel.send(embed2)