Cooldown in every Commands - node.js

Why my command still not getting a cooldown when user used it?
Here's the code:
const cooldown = new Set();
const { MessageEmbed } = require('discord.js');
const eco = require('discord-mongoose-economy');
eco.connect("mongodb://localhost/database"); //this is not the main I hide it
const work = require('../../events/casino/work.json')
if(cooldown.has(message.author.id)) {
message.reply(`You're tired! Wait for 30 seconds to work again!`)
} else {
const total = Object.keys(work).length
var random = Math.floor(Math.random() * total + 1);
var workInfo = work[random];
const min = 10;
const max = 100;
const coin = Math.floor(Math.random() * (max - min + 1) ) + min;
if(message.author.bot) return;
await eco.give(message.author.id, message.guild.id, coin);
const workembed = new MessageEmbed()
.setDescription(workInfo.description + `and recieved ` + coin + ` coins`)
.setColor('RANDOM')
.setFooter({text: `Work #${random}`})
message.channel.send({embeds: [workembed]});
}
cooldown.add(message.author.id);
setTimeout(() => {
cooldown.delete(message.author.id)
}, 30000);
Is there any misplaced codes or something? Because there's still no cooldown, I'm using discord.js v13
I've edited my codes to this:
if(cooldown.has(message.author.id)) {
message.reply(`You're tired! Wait for 30 seconds to work again!`)
} else {
const total = Object.keys(work).length
var random = Math.floor(Math.random() * total + 1);
var workInfo = work[random];
const min = 10;
const max = 100;
const coin = Math.floor(Math.random() * (max - min + 1) ) + min;
if(message.author.bot) return;
await eco.give(message.author.id, message.guild.id, coin);
const workembed = new MessageEmbed()
.setDescription(workInfo.description + `and recieved ` + coin + ` coins`)
.setColor('RANDOM')
.setFooter({text: `Work #${random}`})
message.channel.send({embeds: [workembed]});
cooldown.add(message.author.id);
setTimeout(() => {
cooldown.delete(message.author.id)
}, 30000);
}
Still not working.
Last edit for my command and its finally working, I added a package called humanize-duration here is the final code of my work:
const cooldowns = new Map();
const humanizeDuration = require('humanize-duration');
const cooldown = cooldowns.get(message.author.id);
if(cooldown) {
const remaining = humanizeDuration(cooldown - Date.now(), {units: ['s'], round: true})
const cd = new MessageEmbed()
.setAuthor({iconURL: `${message.author.avatarURL()}`,name: `${message.member.user.tag}`})
.setDescription(`You need to wait ${remaining} to do work again, take some rest!`)
.setColor('RANDOM')
return message.channel.send({embeds: [cd]})
.catch(console.error);
} else {
const total = Object.keys(work).length
var random = Math.floor(Math.random() * total + 1);
var workInfo = work[random];
const min = 80000;
const max = 120000;
const coin = Math.floor(Math.random() * (max - min + 1) ) + min;
if(message.author.bot) return;
await eco.give(message.author.id, message.guild.id, coin);
const workembed = new MessageEmbed()
.setAuthor({iconURL: `${message.author.avatarURL()}`,name: `${message.member.user.tag}`})
.setDescription(workInfo.description + `and recieved ` + coin + ` coins`)
.setColor('RANDOM')
.setFooter({text: `Work #${random}`})
message.channel.send({embeds: [workembed]});
cooldowns.set(message.author.id, Date.now() + 30000);
setTimeout(() => cooldowns.delete(message.author.id), 30000);
}
If someone need this code I hope you guys can get some tips!

Related

wait until all the child processes are finished in NodeJS when using fork

I have a nodeJS script where it goes through a list of URLs to download pdfs. Each Url contains 5 pdfs. So I used fork to download all 5 pdfs at once. What I need to do is to move to next URL only and only after all child processes (downloads) finished executing.
this is my main.js
const puppeteer = require('puppeteer');
const fs = require('fs');
const fork = require('child_process').fork;
const ls = fork("download.js");
var list = [];
var links = [];
var names = [];
(async () => {
const browser = await puppeteer.launch(({headless: false}));
const page = await browser.newPage();
/*
const list_arr = fs.readFileSync('link_list.csv').toString().split(",");
for(l = 1; l < list_arr.length; l+2){
links[(l - 1) / 2] = list_arr[l];
names([l - 1] / 2) = list_arr[l - 1];
}
for(let i = 0; i < links.length; i++){*/
// url = links[i];
// name = names[i];
url = 'https://www.responsibilityreports.com/Company/abb-ltd';
name = 'abcd';
await page.goto(url, { waitUntil: 'networkidle2' });
await page.waitForXPath('//li[#class="top_content_list"]/div[#class="left"]/span[#class="ticker_name"]');
let ticker_r = await page.$x('//li[#class="top_content_list"]/div[#class="left"]/span[#class="ticker_name"]');
let ticker = await (await ticker_r[0].getProperty('textContent')).jsonValue();
let cat = ticker[0].toLowerCase();
//console.log(ticker);
await page.waitForXPath('//li[#class="top_content_list"]/div[#class="right"]');
let exchange_r = await page.$x('//li[#class="top_content_list"]/div[#class="right"]');
let exchange = (await (await exchange_r[0].getProperty('textContent')).jsonValue()).split('Exchange').pop().split('More').shift().replace(/\n/gm, '').trim();
//console.log(exchange);
await page.waitForXPath('//div[#class="most_recent_content_block"]/span[#class="bold_txt"]');
let mr_res = await page.$x('//div[#class="most_recent_content_block"]/span[#class="bold_txt"]');
let mr_txt = await mr_res[0].getProperty('textContent');
let mr_text = await mr_txt.jsonValue();
console.log(mr_text);
let [mr_year, ...mr_rest] = mr_text.split(' ');
let mr_type = mr_rest.join(' ').trim();
mr_url = 'https://www.responsibilityreports.com/HostedData/ResponsibilityReports/PDF/'+ exchange + '_' + ticker + '_' + mr_year + '.pdf';
let mr_obj = {
"year" : mr_year,
"type" : mr_type.trim(),
"url" : mr_url
}
list.push(mr_obj);
await page.waitForXPath('//div[#class="archived_report_content_block"]/ul/li/div/span[#class="heading"]');
let ar_reps = await page.$x('//div[#class="archived_report_content_block"]/ul/li/div/span[#class="heading"]');
console.log(ar_reps.length);
for(let k = 0; k < ar_reps.length; k++){
let ar_txt = await ar_reps[k].getProperty('textContent');
let ar_text = await ar_txt.jsonValue();
let [ar_year, ...ar_rest] = ar_text.split(' ');
if(parseInt(ar_year) < 2017){
break;
}
let ar_type = ar_rest.join(' ');
ar_url = 'https://www.responsibilityreports.com/HostedData/ResponsibilityReportArchive/' + cat + '/'+ exchange + '_' + ticker + '_' + ar_year + '.pdf';
let ar_obj = {
"year" : ar_year,
"type" : ar_type,
"url" : ar_url
}
list.push(ar_obj);
console.log(ar_year);
}
/*}*/
for(f = 0; f < list.length; f++){
let url_s = list[f].url;
let type_s = list[f].type;
let year_s = list[f].year;
ls.on('exit', (code)=>{
console.log('child_process exited with code ${code}');
});
ls.on('message', (msg) => {
ls.send([url_s ,name,type_s,year_s]);
console.log(msg);
});
}
await browser.close();
console.log('done');
})();
and child.js
const down_path = 'downloads/';
const https = require('https');
const fs = require('fs');
process.on('message', async (arr)=> {
console.log("CHILD: url received from parent process", arr);
url = arr[0];
name = arr[1];
type = arr[2];
year = arr[3];
await download(url,name,type,year);
});
process.send('Executed');
async function download(url,name,type,year) {
https.get(url, res => {
const stream = fs.createWriteStream(down_path + name + '_' + type + '_' + year + '.pdf');
res.pipe(stream);
stream.on('finish', async() => {
console.log('done : ' + year);
stream.close();
});
});
}
is there anyway I can modify my code so that it'll only go ahead once the child processes finish executing?
EDIT: I also found that child.js are not exiting after stream.close();

Readline node.js undefined Math.floor function error

I want to build node js console asking tool.
Please help, I have an undefined error in the console. What is the problem?
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const ask = msg => new Promise(resolve =>
rl.question(msg, response => resolve(response))
);
const simpleInterest = (min, max) => {
const math = Math.floor(Math.random() * (max - min + 1)) + min;
};
const main = async () => {
const min = await ask("min numer: ");
const max = await ask("max number: ");
console.log(simpleInterest(+min, +max));
rl.close();
};
main();
The simpleInterest function is not returning anything. Try this:
const simpleInterest = (min, max) => {
return Math.floor(Math.random() * (max - min + 1)) + min;
};

Confusion about setting Variables

OK, this may sound like a really simple question, but the below code keeps giving me an error on the console. After some research, it looks as though I may have messed up setting the variables, but I'm not sure how to fix.
For context, this module is to update channels with server stats.
Code:
function updateStats(client) {
const Discord = require('discord.js');
const config = require("../settings/configuration");
const settings = require("../settings/configuration");
const guild = client.guilds.cache.get(settings.BOT_SETTINGS.Guild_ID);
const totalUsers = client.channels.fetch('883654989271154728');
const onlineUsers = client.channels.fetch('883655041813200926');
setInterval(function() {
const interval = (async function() {
for await (const startTime of setInterval(interval, Date.now())) {
const now = Date.now();
console.log(now);
if ((now - startTime) > 1000)function updateStats(client) {
const Discord = require('discord.js');
const config = require("../settings/configuration");
const settings = require("../settings/configuration");
const guild = client.guilds.cache.get(settings.BOT_SETTINGS.Guild_ID);
const totalUsers = client.channels.fetch('883654989271154728');
const onlineUsers = client.channels.fetch('883655041813200926');
setInterval(function() {
const interval = (async function() {
for await (const startTime of setInterval(interval, Date.now())) {
const now = Date.now();
console.log(now);
if ((now - startTime) > 1000)
break;
}
console.log(Date.now());
})();
console.log('Getting stats update..')
var userCount = guild.memberCount;
var onlineCount = guild.members.filter(m => m.presence.status === 'online').size
$console.log("Total Users: " + userCount);
$console.log("Online Users: " + onlineCount);
totalUsers.setName("Total Users: " + userCount)
.then(newChannel => console.log(`Stat channel renamed to: ${newChannel.name}`))
.catch(console.error);
onlineUsers.setName("Online Users: " + onlineCount)
.then(newChannel => console.log(`Stat channel renamed to: ${newChannel.name}`))
.catch(console.error);
}, 30000)
}
module.exports = {
updateStats
}
break;
}
console.log(Date.now());
})();
console.log('Getting stats update..')
var userCount = guild.memberCount;
var onlineCount = guild.members.filter(m => m.presence.status === 'online').size
console.log("Total Users: " + userCount);
console.log("Online Users: " + onlineCount);
totalUsers.setName("Total Users: " + userCount)
.then(newChannel => console.log(`Stat channel renamed to: ${newChannel.name}`))
.catch(console.error);
onlineUsers.setName("Online Users: " + onlineCount)
.then(newChannel => console.log(`Stat channel renamed to: ${newChannel.name}`))
.catch(console.error);
}, 30000)
}
module.exports = {
updateStats
}
Error on console:
[Error] An error happened in process:
ReferenceError: Cannot access 'interval' before initialization
at /home/container/events/Stats.js:10:51
at Timeout._onTimeout (/home/container/events/Stats.js:49:9)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7)
Just change const interval = (async function() { to let interval = (async function() { and then just use interval = (async function() {
like that:
let interval = (async function() {
for await (const startTime of setInterval(interval, Date.now())) {
const now = Date.now();
console.log(now);
if ((now - startTime) > 1000)function updateStats(client) {
const Discord = require('discord.js');
const config = require("../settings/configuration");
const settings = require("../settings/configuration");
const guild = client.guilds.cache.get(settings.BOT_SETTINGS.Guild_ID);
const totalUsers = client.channels.fetch('883654989271154728');
const onlineUsers = client.channels.fetch('883655041813200926');
setInterval(function() {
interval = (async function() {

How to change discord-xp from giving XP per message to giving XP per minute?

The bot gives random XP between 50 and 100 points every random message, which is really slow. Having XP per minute would be better.
This is the code that gives XP, from levels.js in discord-xp:
client.on("message", async message => {
if (!message.guild) return;
if (message.author.bot) return;
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
const randomXp = Math.floor(Math.random() * 50) + 50;
console.log(randomXp);
const hasLeveledUp = await Levels.appendXp(message.author.id, message.guild.id, randomXp);
if (hasLeveledUp) {
const user = await Levels.fetch(message.author.id, message.guild.id);
message.channel.send(`<:GG:807231058507464735> ${message.author}, you just leveled up to **level ${user.level}!** Keep going!`);
}
});
I've tried to fit
const mongoose = require("mongoose");
const LevelSchema = new mongoose.Schema({
userID: { type: String },
guildID: { type: String },
xp: { type: Number, default: 0 },
level: { type: Number, default: 0 },
lastUpdated: { type: Date, default: new Date() },
last_message: 0,
});
module.exports = mongoose.model('Levels', LevelSchema);
and
if (Date.now() - levels.last_message > 60000) {
const randomXp = levels.xp += random.int(15, 25);
levels.last_message = Date.now();
}
in there, but it's not quite doing what I want.
I'm not sure if Mongoose is really necessary. I would start with something like this.
const checkpoint = {};
client.on("message", async message => {
if (!message.guild) return;
if (message.author.bot) return;
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
const authorKey = message.author.id + '|' + message.guild.id;
if (!(authorKey in checkpoint)) checkpoint[authorKey] = Date.now();
const minutes = Math.floor((Date.now() - checkpoint[authorKey]) / 60000);
if (!minutes) return; else checkpoint[authorKey] = Date.now();
// add a random XP amount for each minute (better than `minutes * random.int(15, 25)`)
let xpEarned = 0;
for (let m = 0; m < minutes; m++) xpEarned += random.int(15, 25);
const hasLeveledUp = await Levels.appendXp(message.author.id, message.guild.id, xpEarned);
if (hasLeveledUp) {
const user = await Levels.fetch(message.author.id, message.guild.id);
message.channel.send(`<:GG:807231058507464735> ${message.author}, you just leveled up to **level ${user.level}!** Keep going!`);
}
});

Firebase cloud function sending multiple notification on instanceId

Thats my code where i first get the laterrides. It checks that the any ride is schedule and if any ride is scheduled then it goes inside and get the list of drivers and sends them notification. But the issue is it send notification repeatedly again and again.Kindly help.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.testing = functions.https.onRequest((req, res) => {
console.log("start");
var newArray = [];
let date = new Date();
var hours = date.getHours() + 5;
var minute = date.getMinutes() ;
var year = date.getFullYear() ;
var month = date.getUTCMonth() + 1 ;
var day = date.getDate() ;
var total_date = day + "/" + month + "/" + year;
var total_time = hours + ":" + minute;
var ridelater = admin.database().ref("ridelater");
ridelater.orderByValue().on("value", function(snapshot) {
snapshot.forEach(function(data) {
var str = data.val().time;
const senderUid = data.val().client_key;
if(data.val().date == total_date){
var arr = str.split(":");
var start_minute = arr[0] * 60;
var val = parseInt(arr[1], 10);
var timing = val - 30;
var start = start_minute + timing ;
var end_minute = hours *60;
var end = end_minute + minute;
var diff = end - start;
if (diff <= 30){
var driver = admin.database().ref("user/driver");
driver.orderByValue().on("value", function(snapshot) {
snapshot.forEach(function(instnaceIds) {
//if(instnaceIds.val().status == "free"){
const promises = [];
const receiverUid = instnaceIds.key;
const getInstanceIdPromise =
admin.database().ref(`/user/driver/${receiverUid}/instanceId`)
.once('value');
const getSenderUidPromise = admin.auth().getUser(senderUid);
Promise.all([getInstanceIdPromise, getSenderUidPromise]).then(results =>
{
const instanceId = results[0].val();
//const sender = results[1];
console.log('notifying ' + receiverUid +' from ' + senderUid);
var data1={
'users_key': senderUid,
'org_address' : data.val().org_address,
'dest_address' : data.val().dest_address,
'status' : "request",
'Nodekey' : data.key,
'user_name' : data.val().user_name,
'org_lat' : data.val().org_lat,
'org_long' : data.val().org_long,
'dest_lat' : data.val().dest_lat,
'dest_long' : data.val().dest_long,
'payment' : data.val().payment_method,
'category' : data.val().category,
'Nodekey' : data.val().node_key,
};
var data2 = JSON.stringify(data1);
console.log(JSON.stringify(data1));
const payload = {
notification: {
title: "Qandeel Haider",
body: data2
}
};
console.log(payload);
return admin.messaging().sendToDevice(instanceId, payload)
.then(function (response) {
console.log("Successfully sent message:" + instanceId);
})
.catch(function (error) {
console.log("Error sending message:", error);
});
});
//}
});
});
}
else{
console.log("Not found" + data.val().time);
}
}
else{
console.log("Not found" + data.val().date);
}
console.log("IN");
});
});
console.log("end");
res.status(200).end();
});

Resources