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.
Related
The discord bot's made in node.js. I made a keepalive.js file and did everything that is required to keep pinging the static page with uptimerobot. It was working till 2 days ago. But now, it just keeps shutting down after 5-7 minutes. I have don't think the problem lies within the code. Also I've noticed that my repl randomly keeps disconnecting even when I'm working with the code. And it stays disconnected for an hour or more. Even when I reload the page, it stays stuck on Booting Repl
Here's index.js & keepa_live.js
/**
* Module Imports
*/
//Token import
const mySecret = process.env['MY_SECRET']
////////////
//call to keepalive
const keep_alive = require('./keep_alive.js')
////////////
const { Client, Collection } = require("discord.js");
const { readdirSync } = require("fs");
const { join } = require("path");
const { TOKEN, PREFIX, LOCALE } = require("./util/EvobotUtil");
const path = require("path");
const i18n = require("i18n");
const client = new Client({
disableMentions: "everyone",
restTimeOffset: 0
});
client.login(process.env.MY_SECRET);
client.commands = new Collection();
client.prefix = PREFIX;
client.queue = new Map();
const cooldowns = new Collection();
const escapeRegex = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
i18n.configure({
locales: ["en", "es", "ko", "fr", "tr", "pt_br", "zh_cn", "zh_tw"],
directory: path.join(__dirname, "locales"),
defaultLocale: "en",
objectNotation: true,
register: global,
logWarnFn: function (msg) {
console.log("warn", msg);
},
logErrorFn: function (msg) {
console.log("error", msg);
},
missingKeyFn: function (locale, value) {
return value;
},
mustacheConfig: {
tags: ["{{", "}}"],
disable: false
}
});
/**
* Client Events
*/
//Cycle activity
client.on('ready', () => {
console.log(`${client.user.username} ready!`);
let types = ['LISTENING', 'WATCHING', 'PLAYING'];
let typeIndex = 0;
setInterval(() => {
const currentType = types[typeIndex];
client.user.setPresence({
status: 'idle',
activity: {
name: `${PREFIX}help and ${PREFIX}play`,
type: currentType
}
});
typeIndex = (typeIndex + 1) % types.length;
}, 30000);
});
///
//client.on("ready", () => {
// console.log(`${client.user.username} ready!`);
// client.user.setPresence({
// activity: { name: `${PREFIX}help and ${PREFIX}play`, type: "LISTENING" },
// status: "idle"
// });
//});
client.on("warn", (info) => console.log(info));
client.on("error", console.error);
/**
* Import all commands
*/
const commandFiles = readdirSync(join(__dirname, "commands")).filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const command = require(join(__dirname, "commands", `${file}`));
client.commands.set(command.name, command);
}
client.on("message", async (message) => {
if (message.author.bot) return;
if (!message.guild) return;
const prefixRegex = new RegExp(`^(<#!?${client.user.id}>|${escapeRegex(PREFIX)})\\s*`);
if (!prefixRegex.test(message.content)) return;
const [, matchedPrefix] = message.content.match(prefixRegex);
const args = message.content.slice(matchedPrefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command =
client.commands.get(commandName) ||
client.commands.find((cmd) => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return;
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(
i18n.__mf("common.cooldownMessage", { time: timeLeft.toFixed(1), name: command.name })
);
}
}
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply(i18n.__("common.errorCommend")).catch(console.error);
}
});
var http = require("http");
//create a server object:
//http
// .createServer(function(req, res) {
// res.write("Hello World!"); //write a response to the client
// res.end(); //end the response
// })
// .listen(8080); //the server object listens on port 8080
var http = require('http');
http.createServer(function (req, res) {
res.write("Woah I'm alive. But you should join Galaxy's Edge!");
res.end();
}).listen(8080);
After I setup the uptimerobot monitor to ping the repl's static page, it worked for 2 days. But now it doesn't anymore. After 5-7 minutes, replit just shuts down the bot. I even tried with a different python code. Same results. It just shuts. Do you think it could be because uptime robot isn't successfully pinging the bot?
I'm trying to create a discord bot using a different syntax you could say and trying to integrate a bunch of different commands. The original command I was trying to add was the "fees.js" below. And the bot wasn't responding to the command, but isn't crashing in the console either. I tried testing with a simple ping command that would respond with "Pong!" within an embed, but still doesn't respond. Below I've attached my index.js, fees.js, and my test ping.js
const Discord = require("discord.js");
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES", "GUILD_MESSAGE_REACTIONS"] }, { partials: ["MESSAGE", "CHANNEL", "REACTION", "MANAGE_ROLES"] })
require("dotenv").config();
const prefix = "-";
const fs = require("fs");
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync("./commands/").filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("messageCreate", message => {
if (message.author.bot) return;
if (message.content === prefix + 'reactionrole') {
if (!message.member.roles.cache.has('885603457938108476')) {
return message.channel.send('You dont have access to this!');
}
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command === "ping") {
client.commands.get("ping").execute(message, args, Discord, client);
}
}
});
client.login('Token');
fees.js
module.exports = {
name: 'fee',
description: 'This command will calculate the payouts for every major platform\n`!fee <amount>`\nexample: `!fee 100`',
async execute(message) {
const fees = {
'StockX Level 1 (9.5%)': n => .095 * n,
'StockX Level 2 (9%)': n => .09 * n,
'StockX Level 3 (8.5%)': n => .085 * n,
'StockX Level 4 (8%)': n => .08 * n,
'Goat 90+ (9.5% + $5.00 + 2.9%)': n => 0.095 * n + 5 + (0.905 * n * 0.029),
'Goat 70-89 (15% + $5.00 + 2.9%)': n => 0.15 * n + 5 + (0.85 * n * 0.029),
'Goat 50-69 (20% + $5.00 + 2.9%)': n => 0.20 * n + 5 + (0.80 * n * 0.029),
'Ebay (12.9% + $0.30': n => 0.129 * n + 0.3,
'Paypal (2.9% + $0.30)': n => (0.029 * n) + 0.3,
'Grailed (9% + 2.9%)': n => 0.089 * n + 0.911 * n * 0.029,
}
const embed = new Discord.MessageEmbed();
embed.setTitle("Fee Calculator")
if (msg.content.split(" ").length == 2) {
if (isNaN(message.content.split(" ")[1])) {
embed.setDescription('Please input a number');
}
else {
const [, number] = message.content.split(' ');
Object.keys(fees).forEach(fee => {
embed.addField(`${fee} Payout`, `$${Number(number - fees[fee](number)).toFixed(2)}`);
});
}
}
else if (message.content.split(" ").length > 2) {
embed.setDescription("This command takes only 1 argument");
}
else if (message.content.split(" ").length == 1) {
embed.setDescription("Please put a price to calculate fees");
}
else {
embed.setDescription("Please input a price")
}
message.channel.send(embed);
}
}
ping.js
module.exports = {
name: 'ping',
description: 'This command will display the latency between Discord and our servers\n`!ping`\nexample: `!ping`',
permission: 'USE_APPLICATION_COMMANDS',
async execute(message, args, Discord, client) {
const embed = new Discord.MessageEmbed()
.setTitle("Ping")
.setColor('#5104DB')
.setDescription(`Pong!`)
message.channel.send({ embeds: [embed] });
}
}
On September 1st, Discord made message content a privileged intent. Maybe you should check your application settings over at Discord Developers? Also you might want to consider switching to Slash Commands.
EDIT:
I noticed that you are checking if the command equals to "reactionrole", before checking for equality to "ping". Maybe try moving the if statement outside of that check?
Here is the challenge bot slash command:
const {
SlashCommandBuilder
} = require('#discordjs/builders');
const {
MessageEmbed,
MessageAttachment,
Role
} = require('discord.js');
const {
$where
} = require('../../schemas/balance');
const Challenge = require('../../schemas/challenge');
const challenges = require('./challenges.json');
module.exports = {
data: new SlashCommandBuilder()
.setName('challenge')
.setDescription('Get your DAILY Fortune! Challenge and progress through the server!'),
async execute(interaction, message) {
const item = challenges[Math.floor(Math.random() * challenges.length)];
const filter = response => {
return response.author.id === interaction.user.id;
};
interaction.reply({
content: `${item.question}`,
ephemeral: true
})
.then(() => {
interaction.channel.awaitMessages({
filter,
max: 1,
time: 30000,
errors: ['time']
})
.then(collected => {
const response = collected.first().content;
collected.first().delete();
if (item.answers.includes(response.toLowerCase())) {
interaction.followUp({
content: `${collected.first().author} got the correct answer!`,
ephemeral: true
});
console.log("Challenge Answered Correct");
var guild = message.guilds.cache.get('948892863926771722');
var role = guild.roles.cache.find(role => role.name === 'Fortune Hunters');
var member = guild.members.cache.get(collected.first().author.id);
member.roles.add(role);
} else {
collected.first().delete();
interaction.followUp({
content: `Looks like you missed the answer this time, come back tomorrow for another chance to find your Fortune! with our daily challenges!`,
ephemeral: true
});
console.log("Challenge Answered Incorrectly");
}
})
.catch(collected => {
interaction.followUp({
content: 'You ran out of time!',
ephemeral: true
});
console.log("Timed Out");
});
});
},
};
And then I have the database setup but I'm not sure how to link it up how I did for the balance command. I think I set it up right, I made clones of the balance stuff and renamed it challenge which brought me up to the implementation into the actual command.
SCHEMA:
const mongoose = require('mongoose');
const challengeSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
guildId: String,
memberId: String,
amount: {type: Number, default: 0 },
correctAnswers: {type: Number, default: 0 },
wrongAnswers: {type: Number, default: 0 },
dateLastAnswered: { type: Date, default: Date.now },
});
module.exports = mongoose.model('Challenge', challengeSchema, 'challenges');
And then there's the createChallenge function:
const Balance = require('../schemas/challenge');
const mongoose = require("mongoose");
module.exports = (client) => {
client.createChallenge = async (member) => {
let challengeProfile = await Challenge.findOne({ memberId: member.id, guildId: member.guild.id });
if (challengeProfile) {
return challengeProfile;
} else {
challengeProfile = await new Challenge({
_id: mongoose.Types.ObjectId(),
guildId: member.guild.id,
memberId: member.id,
});
await challengeProfile.save().catch(err => console.log(err));
return challengeProfile;
console.log('The Challenge Database is live!');
}
};
};
I know the database is setup, because for the /balance command in mongo I can see the balances being updated with the user IDs and all that information. Here is what I have for the balance slash command:
const { SlashCommandBuilder } = require('#discordjs/builders');
const Balance = require('../../schemas/balance');
module.exports = {
data: new SlashCommandBuilder()
.setName('balance')
.setDescription('Returns info based on a user\'s balance.')
.addSubcommand(subcommand =>
subcommand
.setName("user")
.setDescription("Gets information of a user mentioned")
.addUserOption(option => option.setName("target").setDescription("The user mentioned"))),
async execute(interaction, client) {
let user = (interaction.options.getUser("target") ? interaction.options.getUser("target") : interaction.user);
const balanceProfile = await client.createBalance(interaction.member);
await interaction.reply({ content: `${interaction.user.tag} has ${balanceProfile.amount}$FP.`});
},
};
The balance schema:
const mongoose = require('mongoose');
const balanceSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
guildId: String,
memberId: String,
amount: {type: Number, default: 0 }
});
module.exports = mongoose.model('Balance', balanceSchema, 'balances');
Create balance function:
const Balance = require('../schemas/balance');
const mongoose = require("mongoose");
module.exports = (client) => {
client.createBalance = async (member) => {
let balanceProfile = await Balance.findOne({ memberId: member.id, guildId: member.guild.id });
if (balanceProfile) {
return balanceProfile;
} else {
balanceProfile = await new Balance({
_id: mongoose.Types.ObjectId(),
guildId: member.guild.id,
memberId: member.id,
});
await balanceProfile.save().catch(err => console.log(err));
return balanceProfile;
}
};
};
I hope all this information is helpful enough for someone to help... I've been struggling with this for about 9 hours now and it's killing me. I can't figure it out and we need to have this bot live this weekend. Any assistance you can give, I would greatly greatly appreciate! Like I mentioned what I'm trying to do is use the mongoDB database to store when someone does the /challenge command so that I can limit the command to being once per day, and assign an $FP balance reward with the reward role being given after 3 correct answers instead of just the first one.
Hey If your looking to schedule tasks please try this npm package
https://www.npmjs.com/package/cron
It will help.
const today = new Date();
const dd = String(today.getDate()).padStart(2, "0");
const mm = String(today.getMonth() + 1).padStart(2, "0");
const day = today.getDay();
cron.schedule(`30 30 23 ${dd} ${mm} ${day}`, async () => {
await IssuesModel.markIssuesAsOverdue();
});
There is an example how I used it to mark issues in my app as overdue at the middle of the night.
I have since been able to solve this issue. Here is the finished code, now I just have to create the event handler that will assign a new addition to the balance when someone gets a correct answer:
const {
SlashCommandBuilder
} = require('#discordjs/builders');
const {
MessageEmbed,
MessageAttachment,
Role
} = require('discord.js');
const {
$where
} = require('../../schemas/balance');
const Challenge = require('../../schemas/challenge');
const challenges = require('./challenges.json');
module.exports = {
data: new SlashCommandBuilder()
.setName('challenge')
.setDescription('Get your DAILY Fortune! Challenge and progress through the server!'),
async execute(interaction, message) {
const item = challenges[Math.floor(Math.random() * challenges.length)];
const filter = response => {
return response.author.id === interaction.user.id;
};
let user;
try {
//check if user has a challenge
user = await Challenge.findOne({
guildId: interaction.guild.id,
memberId: interaction.user.id
});
if (user) {
if (user.dateLastAnswered >= Date.now() - 86400000) {
let time = 86400000 - (Date.now() - user.dateLastAnswered);
let timeString = "";
if (time > 3600000) {
timeString = `${Math.floor(time / 3600000)} hours, `;
}
if (time > 60000) {
timeString = `${timeString}${Math.floor((time % 3600000) / 60000)} minutes, `;
}
if (time > 1000) {
timeString = `${timeString}${Math.floor((time % 60000) / 1000)} seconds`;
}
interaction.reply({
content: `You have already claimed and answered your challenge for the day!\n\nBe sure to come back in ${timeString} to receive your next Fortune! Challenge!`,
ephemeral: true
});
return;
}
} else {
if (!user) {
//if user doesn't exist, create new challenge
const newChallenge = new Challenge({
guildId: String(interaction.guild.id),
memberId: String(interaction.user.id),
amount: 0,
correctAnswers: 0,
wrongAnswers: 0,
dateLastAnswered: Date.now()
});
await newChallenge.save();
user = await Challenge.findOne({
guildId: interaction.guild.id,
memberId: interaction.user.id
});
}
}
} catch (err) {
console.log(err);
}
interaction.reply({
content: `${item.question}`,
ephemeral: true
})
.then(() => {
interaction.channel.awaitMessages({
filter,
max: 1,
time: 1800000,
errors: ['time']
})
.then(async collected => {
const response = collected.first().content;
await collected.first().delete();
if (item.answers.includes(response.toLowerCase())) {
await interaction.followUp({
content: `${collected.first().author} has completed the challenge!`,
ephemeral: true
});
console.log("Challenge Answered Correct");
let guild = message.guilds.cache.get('948892863926771722');
var role = guild.roles.cache.find(role => role.name === 'Fortune Hunters');
var member = guild.members.cache.get(collected.first().author.id);
//if user exists, update their challenge
if (user) {
user.amount = user.amount + 1;
user.correctAnswers = user.correctAnswers + 1;
user.dateLastAnswered = Date.now();
await user.save();
if (user.correctAnswers >= 4) {
await interaction.followUp({
content: `Congratulations ${collected.first().author}, you have answered ${user.correctAnswers} challenges correct!\n\nhttps://cdn.discordapp.com/attachments/961307478790922342/974345274883457084/correct.png`,
ephemeral: true
});
return;
}
if (user.correctAnswers === 3) {
await member.roles.add(role);
await interaction.followUp({
content: `Congratulations ${collected.first().author}, you have answered ${user.correctAnswers} out of THREE required challenges, and have earned the Fortune Hunters role!\n\nhttps://cdn.discordapp.com/attachments/961307478790922342/974345274883457084/correct.png`,
ephemeral: true
});
} else {
//show time remaining until they can do next challenge
let time = 86400000 - (Date.now() - user.dateLastAnswered);
let timeString = "";
if (time > 3600000) {
timeString = `${Math.floor(time / 3600000)} Hours, `;
}
if (time > 60000) {
timeString = `${timeString}${Math.floor((time % 3600000) / 60000)} Minutes, `;
}
if (time > 1000) {
timeString = `${timeString}${Math.floor((time % 60000) / 1000)} Seconds`;
}
await interaction.followUp({
content: `${collected.first().author} has completed ${user.correctAnswers} out of THREE challenges towards opening full server access! Come back tomorrow for more challenges, and continue your journey!\n\nTime Remaining Until Next Challenge: ${timeString}`,
ephemeral: true
});
}
}
} else {
//if user exists, update their challenge
if (user) {
user.amount = user.amount + 1;
user.wrongAnswers = user.wrongAnswers + 1;
user.dateLastAnswered = Date.now();
await user.save();
}
//show time remaining until they can do next challenge
let time = 86400000 - (Date.now() - user.dateLastAnswered);
let timeString = "";
if (time > 3600000) {
timeString = `${Math.floor(time / 3600000)} Hours, `;
}
if (time > 60000) {
timeString = `${timeString}${Math.floor((time % 3600000) / 60000)} Minutes, `;
}
if (time > 1000) {
timeString = `${timeString}${Math.floor((time % 60000) / 1000)} Seconds`;
}
await interaction.followUp({
content: `Looks like you didn't get it right this time Fortune Hunter, but be sure to come back tomorrow for another chance to find your Fortune! with our daily challenges!\n\nTime Remaining Until Next Challenge: ${timeString}\n\nhttps://cdn.discordapp.com/attachments/961307478790922342/974345275193831424/incorrect.png`,
ephemeral: true
});
console.log("Challenge Answered Incorrectly");
}
})
.catch(async collected => {
//show time remaining until they can do next challenge
let time = 86400000 - (Date.now() - user.dateLastAnswered);
let timeString = "";
if (time > 3600000) {
timeString = `${Math.floor(time / 3600000)} Hours, `;
}
if (time > 60000) {
timeString = `${timeString}${Math.floor((time % 3600000) / 60000)} Minutes, `;
}
if (time > 1000) {
timeString = `${timeString}${Math.floor((time % 60000) / 1000)} Seconds`;
}
await interaction.followUp({
content: `You ran out of time! Please come back and try again tomorrow with another challenge.\n\nTime Remaining Until Next Challenge: ${timeString}\n\nhttps://cdn.discordapp.com/attachments/961307478790922342/974345274635980900/timed_out.png`,
ephemeral: true
});
console.log("Timed Out");
});
});
},
};
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) => {
I am making a Seek command with YTDL-Core and Discord.js as part of my updated music commands and I am having issues with how I am seeking the song playing in the Voice Call.
What my seek command should exactly do is if I specify n!seek 2:00 for example, it should go to 2:00 timestamp from where the song is currently played to that specified timestamp.
Instead of that, the issue I am getting is if I specify any song timestamp (2:00 etc.) it will go back to the beginning of when the song is played, 0:00. There are no errors in the Console that I am aware of when I execute the command.
Seek.js: (Command used to seek song)
//Problem is seek will keep going back to start of song whenever it does.
const {handleVideo, queue, youtube}= require('../../util/music/handleVideo');
const { RichEmbed } = require("discord.js");
exports.run = async (client, msg, args) => {
const serverQueue = queue.get(msg.guild.id);
if (!msg.member.voiceChannel) return msg.channel.send("Join voice channel first");
if (!serverQueue) return msg.channel.send("No songs to seek");
if (serverQueue.voiceChannel.id !== msg.member.voiceChannel.id) return msg.chanel.send(`You must in **${serverQueue.voiceChannel.name}** to seek the song`);
try {
const curDuration = (serverQueue.songs[0].durationm * 60000) + ((serverQueue.songs[0].durations % 60000) * 1000);
const choiceDur = args.join(" ").split(":");
if (choiceDur.length < 2) return msg.channel.send("No duration provided or invalid ?");
const optDurr = (parseInt(choiceDur[0], 10) * 60000) + ((parseInt(choiceDur[1], 10) % 60000) * 1000);
if (optDurr > curDuration) return msg.channel.send("Your duration is too big");
serverQueue.songs.splice(1, 0, serverQueue.songs[0]);
return serverQueue.connection.dispatcher.end()
} catch (e) {
return msg.channel.send(`Oh no an error occured :( \`${e.message}\` try again later`);
}
};
exports.conf = {
aliases: [],
clientPerm: "",
authorPerm: ""
};
exports.help = {
name: "seek",
description: "Seek current songs",
usage: "seek <duration>",
example: ["seek 00:00"]
};
handleVideo.js: (How the music commands are handled)
const YouTube = require('simple-youtube-api');
const ytdl = require('ytdl-core');
const moment = require("moment");
let config = require('../../config.json');
const youtube = new YouTube(config.youtube_api);
const { Client, Util, RichEmbed} = require('discord.js');
var queue = new Map();
async function handleVideo(video, msg, voiceChannel, playlist = false) {
if (video.durationSeconds === 0) {
let livestreamembed = new RichEmbed()
.setTitle(`**Music 🎵**`)
.setDescription(`**Cannot play Livestreams...** ❌\n\nPlease use YouTube Links only instead.`)
.setColor(`#e05e7c`)
return msg.channel.send(livestreamembed);
return undefined;
}
const serverQueue = queue.get(msg.guild.id);
//console.log(video)
const song = {
id: video.id,
title: Util.escapeMarkdown(video.title),
url: `https://www.youtube.com/watch?v=${video.id}`,
durationmm: video.durationSeconds ? video.durationSeconds : video.duration / 1000,
channel: msg.member.voiceChannel.name,
uploadedby: video.channel.title,
channelurl: `https://www.youtube.com/channel/${video.channel.id}`,
author: msg.author,
durationh: video.duration.hours,
durationm: video.duration.minutes,
durations: video.duration.seconds,
duration: video.duration,
};
if (!serverQueue) {
const queueConstruct = {
textChannel: msg.channel,
voiceChannel: voiceChannel,
connection: null,
songs: [],
volume: 100,
playing: true,
loop: false,
};
queue.set(msg.guild.id, queueConstruct);
queueConstruct.songs.push(song);
try {
var connection = await voiceChannel.join();
queueConstruct.connection = connection;
play(msg.guild, queueConstruct.songs[0])
} catch (error) {
console.error(`NateBot » Cannot join Voice Channel: ${error}`);
queue.delete(msg.guild.id);
return msg.channel.send(`**NateBot |** Could not join the voice channel: ${error}`);
}
} else {
if (serverQueue.songs.some(song => song.id === video.id)) {
msg.channel.send(`**NateBot |** **Error Queuing this song...**\n\n**\`${Util.escapeMarkdown(video.title)}\`** is already queued/playing!\nCheck \`n!queue\` for Music Queue`);
return;
}
serverQueue.songs.push(song);
if (playlist) return undefined;
//Queue Message (Sent When song is requested 2nd time or more)
var queueembed = new RichEmbed()
.setTitle(`**Music 🎵**`)
.setColor(`#0xd677ff`)
.setDescription(`
__**Successfully Queued!**__ 👍🏻
**[${song.title}](https://www.youtube.com/watch?v=${song.id}})**
**Uploaded by »** **[${song.uploadedby}](${song.channelurl})**
**Video ID »** ${song.id}
**Duration »** **\`${require('../../util/util.js').timeString(song.durationmm)}\`**
**Published »** ${moment.utc(song.publishedAt).format('LLLL')}
`)
.setFooter(`Requested by » ${song.author.username}`, `${song.author.displayAvatarURL}`)
.setTimestamp()
.setImage(`https://i.ytimg.com/vi/${song.id}/maxresdefault.jpg`)
return msg.channel.send(queueembed);
}
return undefined;
}
function play(guild, song, msg) {
const serverQueue = queue.get(guild.id);
if (!song) {
queue.delete(guild.id);
return;
}
const dispatcher = serverQueue.connection.playStream(ytdl(song.url, { quality: 'highestaudio', filter: "audioonly", highWaterMark: 2000 }))
.on('end', reason => {
if (reason === 'Stream is not generating quickly enough.') console.log('NateBot » Song ended.');
else console.log(reason);
const shifed = serverQueue.songs.shift();
if(serverQueue.loop) serverQueue.songs.push(shifed);
play(guild, serverQueue.songs[0]);
})
.on('error', error => console.error(error));
dispatcher.setVolumeLogarithmic(serverQueue.volume / 100);
//Now Playing Embed (Sent when Bot starts playing music)
var pleyembed = new RichEmbed()
.setTitle(`**Music 🎵**`)
.setColor(`0x76d6ff`)
.setDescription(`
__**Now Playing!**__ 🎶
**[${song.title}](https://www.youtube.com/watch?v=${song.id}})**
**Uploaded by »** **[${song.uploadedby}](${song.channelurl})**
**Video ID »** ${song.id}
**Duration »** **\`${require('../../util/util.js').timeString(song.durationmm)}\`**
**Published »** ${moment.utc(song.publishedAt).format('LLLL')}
`)
.setImage(`https://i.ytimg.com/vi/${song.id}/maxresdefault.jpg`)
serverQueue.textChannel.send(pleyembed);
}
module.exports = {handleVideo, queue, youtube};
What i've tried to do is to change the following in seek.js
return serverQueue.connection.dispatcher.end()
to
return serverQueue.connection.dispatcher.seek()
As this was noted in https://discord.js.org/#/docs/main/stable/typedef/StreamOptions, I tried to do this method but to no avail...
I am not 100% sure why this is causing the issue. Perhaps its probably a discord.js version change. I currently use 11.5.1 as Discord.JS version.