timeout.js discord.js v13 command not working - javascript

I got this problem, when i wanna use a message embed in my timeout command, that i get a error message! I sended all of the command / files down there! i appreciate the help!
Here the Error Message:
TypeError: command.run is not a function
at module.exports (/home/runner/Bolt-Utilities/events/guild/command.js:132:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Here the Timeout.js command:
const MessageEmbed = require("discord.js");
module.exports = {
name: 'timeout',
aliases: ["tmute", "tm"],
utilisation: '{prefix}timeout',
async execute(client, message, args) {
const fetch = require('node-fetch');
const ms = require('ms');
if (!message.member.permissions.has('TIMEOUT_MEMBERS')) {
message.delete()
} else {
const user = message.mentions.users.first();
const embed1 = new MessageEmbed()
.setDescription("Please provide the user.")
.setColor("RED");
const embed2 = new MessageEmbed()
.setDescription("Please specify the time.")
.setColor("RED");
const embed3 = new MessageEmbed()
.setDescription("Please specify the time between **10 seconds** (10s) and **28 days** (28d).")
.setColor("RED");
if(!user) return message.reply({ embeds: [embed1] });
const time = args.slice(1).join(' ');
if(!time) return message.reply({ embeds: [embed2] });
const milliseconds = ms(time);
if(!milliseconds || milliseconds < 10000 || milliseconds > 2419200000) return message.reply({ embeds: [embed3] });
const iosTime = new Date(Date.now() + milliseconds).toISOString();
await fetch(`https://discord.com/api/guilds/${message.guild.id}/members/${user.id}`, {
method: 'PATCH',
body: JSON.stringify({ communication_disabled_until: iosTime }),
headers: {
'Content-Type': 'application/json',
'Authorization': `Bot ${client.token}`,
},
});
const embed4 = new MessageEmbed()
.setDescription(`${user} has been **Timeout.** | \`${user.id}\``)
.setColor("YELLOW");
message.channel.send({ embeds: [embed4] })
}
},
};
and here the command.js file:
if (!cooldowns.has(command.name)) {
cooldowns.set(command.name, new Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command.name);
const cooldownAmount = (command.cooldown || 1) * 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);
try {
command.run(client, message, args, p, cooldowns);
} catch (error) {
console.error(error);
let embed2000 = new MessageEmbed()
.setDescription("There was an error executing that command.")
.setColor("BLUE");
message.channel.send({ embeds: [embed2000] }).catch(console.error);
}
};
That are all files! i hope someone can help me i dont know what is wrong there!

Typo: you don't actually have a command.run function in your command file, instead you have execute. Change either one to be the same as the other will solve the problem.
Note: if you change the async execute to async run, change like the following:
async run(client, message, args) => {

Related

MessageEmbed is not defined (discord.js v13)

I have this problem where it always says MessageEmbed is not defined! I don't know why it says that please help me! I have tried to solve this problem but nothing solved the problem!
const wait = require('util').promisify(setTimeout);
const OWNER_ID = require("../../config.json").OWNER_ID;
const { MessageEmbed }= require('discord.js');
require('dotenv').config();
var token = process.env.BOT_TOKEN;
module.exports = {
name: "restart",
description: "restarts the bot",
async execute(interaction, client) {
const logMsg = `Command Used: \`RESTART\` \nUser: \`${interaction.user.id}\` \nChannel: \`${interaction.channel.id} (${interaction.channel.name})\``;
client.channels.cache.get(client.config.errorLog).send(logMsg);
try {
if (interaction.user.id != OWNER_ID || ID) {
await interaction.reply({content: "RESTARRR...",ephemeral: true});
await wait(1000);
await interaction.editReply({content:"Wait ... What?!",ephemeral: true});
await wait(2000);
return await interaction.editReply({content:"Bruh! You are not a developer, this command is not for you : )",ephemeral: true});
}
await interaction.reply("RESTARTING FAST AS F BOIIIIII ...").then((m) => {
client.destroy(BOT_TOKEN);
});
await wait(2000).then((m) => {
client.login(BOT_TOKEN);
});
await interaction.editReply("Damn! I'm Back 🔥");
} catch(err) {
const errTag = client.config.errTag;
client.channels.cache.get(client.config.ERROR_LOGS_CHANNEL).send(`**ERROR!** ${errTag} \n${err}\nCommand: \`RESTART\` \nChannel: \`${interaction.channel.id} (${interaction.channel.name})\` \n User: \`${interaction.user.id}\`\n`);
}
},
};
I have tried to solve this problem but nothing happened!
here the code in the command.js file
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
try {
command.run(client, message, args, p, cooldowns);
} catch (error) {
console.error(error);
let embed2000 = new MessageEmbed()
.setDescription("There was an error executing that command.")
.setColor("BLUE");
message.channel.send({ embeds: [embed2000] }).catch(console.error);
}
};

Discord.js button reaction role

I've been trying to make a reaction role in my bot but I keep getting this error
interaction.guild.roles.fetch(mustard).then(role => member.roles.add(role)).catch(console.error())
^
TypeError: Cannot read properties of undefined (reading 'guild')
This is the full code:
const {
Client,
Message,
MessageEmbed,
MessageActionRow,
MessageButton,
} = require('discord.js');
const cooldown = new Set();
module.exports = {
name: "quickroles",
aliases: ["roles"],
permissions: ["ADMINISTRATOR"],
/**
* #param {Client} client
* #param {Message} message
* #param {String[]} args
*/
run: async (client, message, args, interaction) => {
if(cooldown.has(message.author.id)) {
message.reply(`Please wait! You're on a default cooldown of 5 seconds!`)
} else {
const row = new MessageActionRow().addComponents(
new MessageButton()
.setCustomId("pin")
.setLabel("Pink")
.setEmoji('🟥')
.setStyle("SECONDARY"),
new MessageButton()
.setCustomId("mus")
.setLabel("Mustard")
.setEmoji('🟨')
.setStyle("SECONDARY"),
new MessageButton()
.setCustomId("ski")
.setLabel("Sky")
.setEmoji('🟦')
.setStyle("SECONDARY")
)
let pink = '927403952348221449'
let mustard = '927403952427921412'
let sky = '927403952411140137'
let iuser = message.mentions.users.first() || message.author
let embed = new MessageEmbed()
.setTitle(`Color Roles`)
.setDescription('🟥 | Pink\n🟨 | Mustard\n🟦 | Sky')
.setURL("https://www.youtube.com/watch?v=rzVhR7ioqL4")
.setColor('#ffdb58')
const m = await message.channel.send({ embeds: [embed], components: [row] })
const filter = (interaction) => {
if(interaction.user.id === iuser.id) return true;
return interaction.reply({content: "This isn't for u", ephemeral: true})
}
const collector = message.channel.createMessageComponentCollector({
filter,
max: 1,
});
collector.on("end", (ButtonInteraction) => {
const id = ButtonInteraction.first().customId;
let pp = new MessageEmbed()
.setDescription(`You now have the <#&927403952348221449> role`)
.setColor('#ffc0cb')
m.edit(pp)
let mm = new MessageEmbed()
.setDescription(`You now have the <#&927403952427921412> role`)
.setColor('#ffdb58')
m.edit(mm)
let ss = new MessageEmbed()
.setDescription(`You now have the <#&927403952411140137> role`)
.setColor('#ffdb58')
m.edit(ss)
if(id === "pin") {
interaction.guild.roles.fetch(pink).then(role => member.roles.add(role)).catch(console.error())
return ButtonInteraction.first().reply({embeds: [pp]})
}else if(id === "mus") {
interaction.guild.roles.fetch(mustard).then(role => member.roles.add(role)).catch(console.error())
return ButtonInteraction.first().reply({embeds: [pp]})
}else if(id === "ski") {
interaction.guild.roles.fetch(sky).then(role => member.roles.add(role)).catch(console.error())
return ButtonInteraction.first().reply({embeds: [pp]})
}
})
} cooldown.add(message.author.id);
setTimeout(() => {
cooldown.delete(message.author.id)
}, 5000)}
};
I'm pretty much new in coding so hopefully, you could help me figure out the problem and make the code work fully 😄
I think you didn't define "guild",
try instead of
const {
Client,
Message,
MessageEmbed,
MessageActionRow,
MessageButton,
} = require('discord.js');
with the following:
const {
Client,
Guild,
guild
Message,
MessageEmbed,
MessageActionRow,
MessageButton,
} = require('discord.js');

How can I add a cooldown on work command (economy, currency)

So im trying to make an economy discord bot but I don't know how to make a 3 hour cooldown on the work command after the user uses it so for the does that don't understand
me: !work
bot: you got 123 money while working.
me: !work
bot: you have to wait 3 hours before working again.
This is my code for the work command
if (message.content.toLowerCase().startsWith(prefixS.prefix + 'work')) {
const inventoryS = await inventory.findOne({ userID: message.author.id, guildID: message.guild.id });
const payment = Math.floor(Math.random() * 200);
inventoryS.work = parseInt(payment)
inventoryS.save()
message.channel.send({ embeds: [new Discord.MessageEmbed().setAuthor(message.author.username).setTitle('⚒️⚒️').setColor('BLUE')] }).then((message) => {
setTimeout(function () {
function doRandHT() {
var rand = [`You worked an extra night and got ${inventoryS.work}`, `You worked an extra day and got ${inventoryS.work}`, `Your boss just gave you ${inventoryS.work} for just sitting in your chair`];
return rand[Math.floor(Math.random() * rand.length)];
}
message.edit({ embeds: [new Discord.MessageEmbed().setTitle(doRandHT()).setColor('BLUE')] }).then(() => {
inventoryS.currency = parseInt(inventoryS.currency) + parseInt(inventoryS.work)
inventoryS.save()
}
});
})
}, 3000)
})
}
Thank you
This is the guide for cooldown on discord.js v12, is kind of similar if you are using v13.
In the command file:
module.exports = {
name: 'example',
cooldown: 5,
execute(message) {
// ...
},
};
In the main file:
client.cooldowns = new Discord.Collection();
const { cooldowns } = client;
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 || 3) * 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);
Make sure execute this code before execute the command.

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()

How to make multi-word argumet?

How can I make multi-word argumet. For example a reason for bans or mutes.If I use args[2], args[3], args[4], args[5]... so it's still limited and if nothing is written there, it will write "undefined". So if you knew how to do it, I would be very happy for the answer. :)
const { ReactionCollector } = require("discord.js");
module.exports = {
name: 'ban',
description: "Dočasně zabanuje člena.",
async execute(message, args, Discord, client, chalk, ms){
await message.channel.messages.fetch({limit: 1}).then(messages =>{
message.channel.bulkDelete(messages);
});
const channelId = client.channels.cache.get('802649418087530537');
const author = message.author;
const userName = message.mentions.users.first();
if(!message.member.permissions.has("BAN_MEMBERS")){
message.reply('Nemáš potřebné permisse!')
.then(msg => {
msg.delete({ timeout: 5000 })
});
return;
} else if(!args[1]){
message.reply('!ban <člen> <délka> (<důvod>)')
.then(msg => {
msg.delete({ timeout: 5000 })
});
console.log(chalk.red('[ERROR] Missing args[1]'));
return;
}
if(userName){
const userId = message.guild.members.cache.get(userName.id);
const botId = '799652033509457940';
userId.ban();
const banEmbed = new Discord.MessageEmbed()
.setColor('#a81919')
.setTitle('Ban')
.addFields(
{name:'Člen:', value:`${userId}`},
{name:'Udělil:', value:`${author}`},
{name:'Délka:', value:`${ms(ms(args[1]))}`},
{name:'Důvod:', value:`${args[2]}`},
)
.setTimestamp()
channelId.send(banEmbed)
setTimeout(function () {
message.guild.members.unban(userId);
const unbanEmbed = new Discord.MessageEmbed()
.setColor('#25a819')
.setTitle('Unban')
.addFields(
{name:'Člen:', value:`${userId}`},
{name:'Udělil:', value:`<#${botId}>`},
{name:'Důvod:', value:`Ban vypršel.`},
)
.setTimestamp()
channelId.send(unbanEmbed)
}, ms(args[1]));
console.log(chalk.green(`[INFO] /ban/ ${userId.user.username}, ${ms(ms(args[1]))}`));
}else{
message.channel.send('Nemůžeš zabanovat tohoto člena');
console.log(chalk.red(`[ERROR] /ban/ Can not find target`));
}
}
}
I am assuming that you have defined args correctly. Then you can simply use
args.join(" ");
to seperate each word with spaces.

Categories

Resources