How to use sqlite to store the cooldown of a command? - javascript

I want to try to store my command cooldown in any sort of storage, I think sqlite will be good, but I don't know how to implement it for a cooldown.. I was checking one guide here https://anidiots.guide/coding-guides/sqlite-based-points-system/#you-get-points-and-you-get-points-and-everybody-gets-points, it's for storage points and levels.. Unfortunately I'm not able edit this example into my needs, to store the cooldown for each user.
'use strict';
const SQLite = require("better-sqlite3");
const sql = new SQLite("./cooldowns.sqlite");
const humanizeDuration = require('humanize-duration');
// Require the necessary discord.js classes
const { Client, Intents, Collection } = require('discord.js');
const config = require("./config.json");
const { MessageEmbed } = require('discord.js');
const cooldowns = new Map();
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
client.on('ready', () => {
const table = sql.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'scores';").get();
if (!table['count(*)']) {
// If the table isn't there, create it and setup the database correctly.
sql.prepare("CREATE TABLE scores (id TEXT PRIMARY KEY, user TEXT, guild TEXT, points INTEGER, level INTEGER);").run();
// Ensure that the "id" row is always unique and indexed.
sql.prepare("CREATE UNIQUE INDEX idx_scores_id ON scores (id);").run();
sql.pragma("synchronous = 1");
sql.pragma("journal_mode = wal");
}
// And then we have two prepared statements to get and set the score data.
client.getCooldown = sql.prepare("SELECT * FROM scores WHERE user = ? AND guild = ?");
client.setCooldown = sql.prepare("INSERT OR REPLACE INTO scores (id, user, guild, points, level) VALUES (#id, #user, #guild, #points, #level);");
client.user.setActivity("thinking...", { type: 'PLAYING' });
console.log('Bot is online!')
});
client.on("messageCreate", message => {
if (message.author.bot) return;
// This is where we'll put our code.
if (message.content.indexOf(config.prefix) !== 0) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if(command === 'mycommand') {
const cooldown = cooldowns.getCooldown(message.author.id);
if (!cooldown) {
cooldowns = {
id: `${message.author.id}`,
user: message.author.id,
cooldown: 0
}
}
if (cooldown) {
const remaining = humanizeDuration(cooldown - Date.now(), { round: true }, { units: ["d","h","m","s"] });
message.reply(`Your cooldown is. ${remaining}`)
return;
}
async function main() {
const messages = await message.channel.messages.fetch({ limit: 1 });
const lastMessage = messages.last();
const isValidDate = (dateString) => new Date(dateString).toString() !== 'Invalid Date'
if(isValidDate(lastMessage.content) == false && lastMessage.content !== 'mycommand')
message.reply("I need your date of birth!.")
if(lastMessage.content === 'mycommand')
message.reply("Please provide me your date of birth.")
if(isValidDate(lastMessage.content) == true && lastMessage.content !== 'mycommand') {
cooldowns.set(message.author.id, Date.now() + 604800000);
message.reply("Check your DMs.")
message.react("emoji"); //react with emoji to the issued command
const predictions = ["Prediction 1", "Prediction 2", "Prediction 3", "Prediction 4", "Prediction 5", "Prediction 6", "Prediction 7"]
const randomprediction = predictions[Math.floor(Math.random() * predictions.length)];
const prediction1 = new MessageEmbed()
.setColor('#ff7518')
.setAuthor(client.user.username, client.user.displayAvatarURL())
.setTitle(`Weekly message` + lastMessage.author.username + `#` + lastMessage.author.discriminator)
.setDescription(randomprediction);
message.author.send({ embeds: [prediction1] });
var random = Math.random()
if (random < 0.9) {
message.author.send("Congrats! You received this message " + '<#' + message.author.id + '>!')
message.channel.send('Congrats again! ' + '<#' + message.author.id + '>');
}
setTimeout(() => cooldowns.delete(message.author.id), 604800000);
client.setCooldown.run(cooldowns);
}
}
}
The problem is I don't know how to edit the sql params, I never used sqlite/anything else before and have 0 experience with it. All I want is to store command in some sort of storage, but I don't know where to start. Any help will be much appreciated!

Related

Trying to Execute a subclass using setInterval() everything that I think of won't work

I'm Creating a discord bot for a pc game that will run /setup command that will automate some other commands using setInterval(). I'm using a class to group the commands into their own subclass. I wanted to make a command that will run a few certain commands every few secs or hours. I've tried everything I can think, tried to google it but nothin came up.
Here is the Index.js file (main file)
require ('dotenv').config();
const { Client, GatewayIntentBits, Partials, Routes, Collection } = require('discord.js')
const Discord = require('discord.js')
const client = new Client({
intents:[
GatewayIntentBits.GuildMessages,
GatewayIntentBits.Guilds,
GatewayIntentBits.MessageContent
],
rest: {version: '10'},
partials: [Partials.Channel]
});
const {TOKEN, APP, GUILD} = process.env;
const {registerCommands} = require('./handler/registercommand');
client.rest.setToken(TOKEN);
client.on('interactionCreate', (interaction) => {
if (interaction.isChatInputCommand()) {
const {commandName} = interaction;
console.log(commandName)
const cmd = client.slashCommands.get(commandName);
if (cmd) {
cmd.execute(client, interaction);
}
else {
interaction.reply({content: 'Error running this slash command'});
}
}
});
async function main() {
try {
client.slashCommands = new Collection;
await registerCommands(client, '../commands');
//console.log(client.slashCommands);
const slashCommandsJson = client.slashCommands.map((cmd) => cmd.getSlashCommandJSON());
console.log(slashCommandsJson);
await client.rest.put(Routes.applicationCommands(APP), {
body: slashCommandsJson,
});
const registeredSlashCommands = await client.rest.get(
Routes.applicationCommands(APP)
);
console.log(registeredSlashCommands);
await client.login(TOKEN);
}
catch(err) {
console.log(err)
}
}
main()
One of the commands I want to automate which in this case is /arbitrations
const unirest = require("unirest");
const { EmbedBuilder, AttachmentBuilder, SlashCommandBuilder } = require("discord.js");
const SlashCommands = require('../handler/slashcommands');
file = new AttachmentBuilder();
module.exports = class arbitration extends SlashCommands {
constructor() {
super('arbitration');
}
async execute(client, interaction) {
const api = unirest("GET", "https://api.warframestat.us/pc/arbitration");
const moment = require("moment");
api.end(function (response) {
//gathers the data from the get request
if (response.error) throw new Error(response.error); // throws(logs) the error
const jsonResponse = response.body; // grabs the body from the response
const jsonEmbed = new EmbedBuilder()
.setTitle("Current Arbitration:")
.setColor("#BF40BF") // sets the color of the embed
.setFooter({ text: "Arbitration" }) // sets the footer text of the embed
if (jsonResponse['enemy'] === 'Grineer'){
file = new AttachmentBuilder('./assets/grineer.jpg')
jsonEmbed.setThumbnail('attachment://grineer.jpg')
}
else if (jsonResponse['enemy'] === 'Corpus'){
file = new AttachmentBuilder('./assets/corpus.jpg')
jsonEmbed.setThumbnail('attachment://corpus.jpg')
}
else if (jsonResponse['enemy'] === 'Corrupted'){
file = new AttachmentBuilder('./assets/corrupted.jpg')
jsonEmbed.setThumbnail('attachment://corrupted.jpg')
}
else {
file = new AttachmentBuilder('./assets/infested.jpg')
jsonEmbed.setThumbnail('attachment://infested.jpg')
}
var d = new Date(jsonResponse["expiry"]);
let date = moment(d, "MMM-DD").format("MMM:DD"); // returns the month and day
date = date.replace(":", " "); // replaces the : with a space
let final = moment(d, "HH:mm:ss").format("h:mm:ss A");
jsonEmbed.addFields({
name: `${jsonResponse["type"]}, \`${jsonResponse["node"]}\``,
value: `\n**Expires on:** \n${date} at ${final}`,`
});
interaction.reply({ embeds: [jsonEmbed], files: [file] });
});
}
getSlashCommandJSON(){
return new SlashCommandBuilder()
.setName(this.name)
.setDescription('Shows current Arbitration')
.toJSON();
}
};
Then the /setup command that will automate certain commands depending on the user's answer, I'm trying to execute /arbitrations command inside the SetInterval() on line 22:
const SlashCommands = require('../handler/slashcommands');
const { EmbedBuilder, Discord, SlashCommandBuilder } = require("discord.js");
module.exports = class setup extends SlashCommands {
constructor() {
super('setup');
}
async execute(client, interaction){
console.log("in the command")
const filter = (m) => m.author.id === interaction.user.id
interaction.channel.send("Would you like to automate the Arbitration command?")
console.log("sent Question")
interaction.channel
.awaitMessages({filter ,max: 1, time: 1000 * 20})
.then((collected) => {
const msg = collected.first()
if (msg.content.toLowerCase() === "yes" || msg.content.toLowerCase() === "y") {
console.log("setting setInterval()")
setInterval(() => {
var minutes = new Date().getMinutes()
if (minutes === 51) {
SlashCommands.get(`arbitrations`).execute(client, interaction)
}
}, 1000 * 5)
interaction.channel.send("Arbitration is Automated")
}
else if (msg.content.toLowerCase() === "no" || msg.content.toLowerCase() === "n") {
interaction.channel.send("Automation for Arbitration is canceled")
}
else {
interaction.channel.send("An error has occured please run again")
}
})
.catch((err) => console.log(err))
}
getSlashCommandJSON(){
return new SlashCommandBuilder()
.setName(this.name)
.setDescription('Automates commands')
.toJSON();
}
}
FYI: first time using this site so sorry if this doesn't look right
I already tried the code that's currently on line 25 and I get error "SlashCommands.get is not a function"

Mongo DB remove 1 item from an array

I have a buy system in place for my discord bot where it adds something to the inventory array in mongoDB:
data.Inventory[itemTobuy] ++;
It gets stored like this:
pizza: 1
And i have a use system where you can use items in your inventory. I would like to remove the whole thing if theres only 1 instance of this item but if there is more i would like to decrement the value by one. Say from pizza: 5 to pizza: 4.
Althought im only 25% sure on how i would do such things
The full code for the command that adds the item if needed:
const { Client, Message, MessageEmbed } = require('discord.js');
const { User } = require("../../databasing/schemas/User")
const inventory = require('../../databasing/schemas/inventory')
const items = require('../../items/shopItems')
module.exports = {
name: 'buy',
/**
* #param {Client} client
* #param {Message} message
* #param {String[]} args
*/
run: async(client, message, args) => {
userData = await User.findOne({ id: message.author.id }) || new User({ id: message.author.id })
const itemTobuy = args[0].toLowerCase()
embed = new MessageEmbed({ color: "#2F3136" })
if(!args[0]) return message.channel.send({
embeds: [ embed.setTitle('<:redCross:1004290018724020224> | Please mention something to buy!')]
});
const itemid = !!items.find((val) => val.item.toLowerCase() === itemTobuy);
if(!itemid) return message.channel.send({
embeds: [ embed.setTitle(`<:redCross:1004290018724020224> | ${itemTobuy} is not a valid item!`)]
});
itemPrice = items.find((val) => val.item.toLowerCase() === itemTobuy).price;
userBalance = userData.wallet;
if(userBalance < itemPrice) return message.channel.send({
embeds: [embed.setTitle(`<:redCross:1004290018724020224> | You dont have enough money to buy this item(LOL)`)]
});
const param ={
User: message.author.id
}
inventory.findOne(param, async(err, data) => {
if(data){
const hasItem = Object.keys(data.Inventory).includes(itemTobuy);
if(!hasItem){
data.Inventory[itemTobuy] = 1;
} else {
data.Inventory[itemTobuy] ++;
}
await inventory.findOneAndUpdate(param, data);
} else {
new inventory({
User: message.author.id,
Inventory: {
[itemTobuy]: 1,
}
}).save()
}
message.channel.send({
embeds: [embed.setTitle(`<:greenTick:1004290019927785472> | Successfully bought ${itemTobuy}!`)]
});
userData.wallet -= itemPrice;
userData.save()
})
}
}
You can use $inc method to decrease the value of your item. For example:
const param = {
User: message.author.id
}
const item_name = args.splice(0).join(" ").toLowerString();
//Take note that .toLowerString() will transform any string to lowercase.
//If your data is case sensitive, remove the .toLowerString().
inventory.findOne({
param, //User.id
"Inventory.name": item_name //Change the "name" to something on how you call the name of your items.
}, async(err, data) => {
//Take note that we only identify if the item existing or not.
if(data) {
//Here's where you decrease the amount of the item.
await inventory.findOneAndUpdate({
param,
"Inventory.name": item_name
}, {
$inc: {
"Inventory.$.value": -1 //Change the value on how you call the value of your item
}
})
} else {
//Here is where you send a message that the item doesn't exist.
}
})
EDIT:
To get the name and the value of your item, you need to find the curtain name.
First you need to create your inventory as array.
const inv = await inventory.findOne({
param
})
const arr = inv.Inventory;
Your const arr = inv.Inventory; will make it to be an array. Then next step. Find the name
const item_name = args.splice(0).join(" ").toLowerString();
const inv = await inventory.findOne({
param
})
const arr = inv.Inventory;
const item = arr.find(x => x.name == item_name);
After you get the item_name. You can now get the value and the name aswell and post it in somewhere you wanted. Can be embed or normal message.
const item_name = args.splice(0).join(" ").toLowerString();
const inv = await inventory.findOne({
param
})
const arr = inv.Inventory;
const item = arr.find(x => x.name == item_name);
const items_value = item.value;
const items_name = item.name;
const embed = new MessageEmbed()
.addFields(
{name: `Name:`, value: `${items_name}`},
{name: `Value:`, value: `${items_value}`}
)
message.channel.send({embeds: [embed]})

Startup TypeError: Cannot read property 'Collection' of undefined

So I've had multiple problems one after another. The first being;
TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client
Which I solved by changing up my code from:
const Discord = require("discord.js");
const bot = new Discord.Client();
To:
const { Client, Intents, Discord } = require("discord.js");
const bot = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
But now I am running into a seperate issue. Where I keep getting this error;
Startup TypeError: Cannot read property 'Collection' of undefined
This is really frustrated because I've been at this problem for a couple of hours. Any help would be massively appreciated!
All essential code:
const { Client, Intents } = require("discord.js");
const bot = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const { prefix, token, mongoPath } = require("./jsonFiles/config.json");
const mongoose = require("mongoose");
const mongo = require("./utility/mongo.js");
const fs = require("fs");
const Levels = require("discord-xp");
bot.login(token);
bot.commands = new Discord.Collection();
bot.cooldowns = new Discord.Collection();
const commandFolders = fs.readdirSync("./commands");
for (const folder of commandFolders) {
//Finds the name of the command
const commandFiles = fs
.readdirSync(`./commands/${folder}`)
.filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const command = require(`./commands/${folder}/${file}`);
bot.commands.set(command.name, command);
}
}
bot.on("ready", async () => {
console.log("Connect as " + bot.user.tag);
//levels(bot);
await mongo().then(() => {
try {
console.log("Connected to mongo!");
} finally {
mongoose.connection.close();
}
});
bot.user.setActivity(".help", {
type: "WATCHING",
});
});
bot.on("message", async (message) => {
try {
await mongo().then(async (mongoose) => {
Levels.setURL(mongoPath);
if (!message.guild) return;
if (message.author.bot) return;
const randomAmountOfXp = Math.floor(Math.random() * 20) + 1; // Min 1, Max 30
const hasLeveledUp = await Levels.appendXp(
message.author.id,
message.guild.id,
randomAmountOfXp
);
if (hasLeveledUp) {
const user = await Levels.fetch(message.author.id, message.guild.id);
message.channel.send(
`${message.author}, congratulations! You have leveled up to **${user.level}** in \`${message.guild.name}\` :sunglasses:`
);
}
});
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command =
bot.commands.get(commandName) ||
bot.commands.find((cmd) => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return;
if (command.guildOnly && message.channel.type === "dm")
return message.reply("I can't execute that command inside DMs!");
if (command.permissions) {
const authorPerms = message.channel.permissionsFor(message.author);
if (!authorPerms || !authorPerms.has(command.permissions)) {
if (message.author.id !== "344834268742156298") {
return message.reply("YOU DO NOT HAVE PERMISSION (git gud scrub)");
}
}
}
if (command.creator === true && message.author.id !== "344834268742156298")
return message.reply("Wait what, you are not creator man, you cannot use the command!!!!!");
if (command.args === true && !args.length) {
let reply = `You didn't provide a valid arguments, ${message.author}!`;
if (command.usage) {
reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
}
message.delete({
timeout: 25 * 1000,
});
return message.channel.send(reply).then((message) => {
message.delete({
timeout: 25 * 1000,
});
});
}
const { cooldowns } = bot;
if (!cooldowns.has(command.name)) {
cooldowns.set(command.name, new Discord.Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command.name);
const cooldownAmount = (command.cooldown ?? 1.5) * 1000;
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return message.reply(
`please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${
command.name
}\` command.`
);
}
}
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
const maxArguments = command.maxArgs || null;
if (
args.length < command.minArgs ||
(maxArguments !== null && command.args === "true" && args.length > command.maxArgs)
) {
let reply = `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
return message.channel.send(reply);
}
try {
command.execute(message, args, message.guild);
} catch (err) {
console.log(err);
}
} catch (err) {
console.log(err);
}
});
At the top you never defined Discord properly. You are trying to access the non-existant Discord property of the discord.js module with object destructuring. There are 2 quick fixes for this, the first one will be faster however.
//at the top change the declaration of Client
const Discord = {
Client,
Intents
} = require('discord.js')
//Discord is module discord.js
Or you can do
const {
Collection,
Client,
Intents
} = require('discord.js')
//use new Collection() instead of new Discord.Collection()
Try instead of:
const { Client, Intents } = require("discord.js");
Try:
const Discord = require("discord.js"), { Client, Intents } = Discord;
Or you can also import Collection from discord:
const { Client, Intents, Collection } = require("discord.js");
and replace:
new Discord.Collection() with new Collection()

Whenever I react to an embed, It sends double messages. [DiscordAPIError: Unknown Message]

I have a waifu command where it gets an image and a name and puts it in a embed, it also then reacts with the ๐Ÿ’– emoji. I wanted to make it so the first person who clicked the emoji would claim the waifu.
const { Client, MessageEmbed, ReactionCollector} = require('discord.js');
const {
prefix
} = require('../../config');
const superagent = require('superagent');
const {
urlencoded
} = require('body-parser');
module.exports = {
name: 'waifu',
category: 'waifu',
description: 'Random Waifu',
usage: `${prefix}waifu`,
perms: 'Send Messages',
cooldown: 5,
run: async (bot, message, args) => {
const rating1 = 10
const rating2 = Math.floor(Math.random() * rating1)
var rating = rating2
const decimals1 = 100
const decimals2 = Math.floor(Math.random() * decimals1)
var decimals = decimals2
const compatibility1 = 100
const compatibility2 = Math.floor(Math.random() * compatibility1)
var compatibility = compatibility2
const {
waifuID
} = require("../../Database/WaifuNameDB.json")
let randW = Math.floor(Math.random() * Object.keys(waifuID).length)
let randomWaifu = waifuID[randW]
let embed2 = new MessageEmbed()
.setTitle(`๐ŸŽ€${randomWaifu.names}๐ŸŽ€`)
.addField("Claims:", `${randomWaifu.claims}`)
.addField("Rating:", `${rating}.${decimals}/10 โญ`)
.setImage(`${randomWaifu.img_url}`, innerHeight = '500', innerWidth = '500')
.setColor('#f095d1')
.setFooter(`| Powered by: #Twintails๐ŸŽ€ API `, `https://64.media.tumblr.com/1a1c3bcc08b5a048b90139a56fe7f415/tumblr_o9ku1rVS8z1vnqjx7o2_250.png`)
var mg = await message.channel.send(embed2);
mg.react('๐Ÿ’–')
message.delete()
bot.on('messageReactionAdd', async (reaction, user) => {
if (reaction.mg) await reaction.mg.fetch();
if (reaction) await reaction.fetch()
if (user.bot) return;
if (reaction.emoji.name == "๐Ÿ’–") {
message.channel.send(`${randomWaifu.names} was claimed!`)
mg.delete()
if(user = message.author) return;
}
})
}
}
It works, but if for example I do /waifu, it sends the embed and says (waifuname) was claimed, but whenever I do /waifu again, everything is the same, but when I click the react button, it says that the previous and the current waifu was claimed.
https://aws1.discourse-cdn.com/business6/uploads/glitch/original/2X/9/98363d9496747899fe23698cb0f98846b1e7136c.jpeg
(Umaru Doma was the previous waifu I rolled)
It also gives an error:
(node:9964) UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Message
Please help if you can!
I have figured out a way to fix this everyone!
bot.on('messageReactionAdd', (messageReaction, user) => {
if(user.bot) return;
const {
message,
emoji
} = messageReaction;
if (emoji.name === "๐Ÿ’–") {
if (!message.id === mg.id) return;
if (message.id === mg.id) {
mg.delete()
message.channel.send(`${randomWaifu.names} was claimed!`)
}
}
});

Working on a Discord bot with discord.js, tempmute won't work

making a discord bot in javascript with visual studio code but for some reason getting an error. I'll show you the code that is relevant first.
Overall trying to get a temporary mute function to work and I want to add it to the available commands which pops up when you hit !help. Table looks like this:
!help
classes I'm working with
Here is the index.js:
const { Client, Collection } = require("discord.js");
const { config } = require("dotenv");
const fs = require("fs");
const client = new Client({
disableEveryone: true
});
client.commands = new Collection();
client.aliases = new Collection();
client.categories = fs.readdirSync("./commands/");
config({
path: __dirname + "/.env"
});
["command"].forEach(handler => {
require(`./handlers/${handler}`)(client);
});
client.on("ready", () => {
console.log(`Hi, ${client.user.username} is now online!`);
client.user.setPresence({
status: "online",
game: {
name: "you get boostedโค๏ธ",
type: "Watching"
}
});
});
client.on("message", async message => {
const prefix = "!";
if (message.author.bot) return;
if (!message.guild) return;
if (!message.content.startsWith(prefix)) return;
if (!message.member) message.member = await message.guild.fetchMember(message);
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const cmd = args.shift().toLowerCase();
if (cmd.length === 0) return;
let command = client.commands.get(cmd);
if (!command) command = client.commands.get(client.aliases.get(cmd));
if (command)
command.run(client, message, args);
});
client.login(process.env.TOKEN);
Here is tempmute:
bot.on('message', message => {
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0]) {
case 'mute':
var person = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[1]));
if(!person) return message.reply("I CANT FIND THE USER " + person)
let mainrole = message.guild.roles.find(role => role.name === "Newbie");
let role = message.guild.roles.find(role => role.name === "mute");
if(!role) return message.reply("Couldn't find the mute role.")
let time = args[2];
if(!time){
return message.reply("You didnt specify a time!");
}
person.removeRole(mainrole.id)
person.addRole(role.id);
message.channel.send(`#${person.user.tag} has now been muted for ${ms(ms(time))}`)
setTimeout(function(){
person.addRole(mainrole.id)
person.removeRole(role.id);
console.log(role.id)
message.channel.send(`#${person.user.tag} has been unmuted.`)
}, ms(time));
break;
}
});
Here is the help.js which lists all commands
const { RichEmbed } = require("discord.js");
const { stripIndents } = require("common-tags");
module.exports = {
name: "help",
aliases: ["h"],
category: "info",
description: "Returns all commands, or one specific command info",
usage: "[command | alias]",
run: async (client, message, args) => {
if (args[0]) {
return getCMD(client, message, args[0]);
} else {
return getAll(client, message);
}
}
}
function getAll(client, message) {
const embed = new RichEmbed()
.setColor("RANDOM")
const commands = (category) => {
return client.commands
.filter(cmd => cmd.category === category)
.map(cmd => `- \`${cmd.name}\``)
.join("\n");
}
const info = client.categories
.map(cat => stripIndents`**${cat[0].toUpperCase() + cat.slice(1)}** \n${commands(cat)}`)
.reduce((string, category) => string + "\n" + category);
return message.channel.send(embed.setDescription(info));
}
function getCMD(client, message, input) {
const embed = new RichEmbed()
const cmd = client.commands.get(input.toLowerCase()) || client.commands.get(client.aliases.get(input.toLowerCase()));
let info = `No information found for command **${input.toLowerCase()}**`;
if (!cmd) {
return message.channel.send(embed.setColor("RED").setDescription(info));
}
if (cmd.name) info = `**Command name**: ${cmd.name}`;
if (cmd.aliases) info += `\n**Aliases**: ${cmd.aliases.map(a => `\`${a}\``).join(", ")}`;
if (cmd.description) info += `\n**Description**: ${cmd.description}`;
if (cmd.usage) {
info += `\n**Usage**: ${cmd.usage}`;
embed.setFooter(`Syntax: <> = required, [] = optional`);
}
return message.channel.send(embed.setColor("GREEN").setDescription(info));
}
ERROR:
Error message, bot not defined.
Overall trying to get a temporary mute function to work and I want to add it to the available commands which pops up when you hit !help. Table looks like this:
!help
I think the tempmute simply doesn't work because you use bot.on() instead of client.on(), which was defined in the index.js. I can't help you for the rest but everything is maybe related to this.

Categories

Resources