Detailed cooldown for commands - node.js

I saw in some discord servers that they have a detailed cooldown and that they can exactly see how long it takes before they can use that command again
but I don't know how add this, can someone help me?
I have this now
const talkedRecently = new Set();
if (talkedRecently.has(msg.author.id)) {
msg.channel.send("Wait 1 minute before getting typing this again. - " + msg.author);
} else {
talkedRecently.add(msg.author.id);
setTimeout(() => {
talkedRecently.delete(msg.author.id);
}, 60000);
}
but here you can't see exactly how long you have to wait. I want it like this:

If you create an object of cooldowns you can get how much time they would have left by subtracting the date from the cooldown.
Like so:
//Start of code or something
var cooldowns = {}
var minute = 60000;
var hour = minute * 24;
//Set cooldown
cooldowns[message.author.id] = Date.now() + hour * 24; //Set a 24 hour cooldown
//At command check
if(cooldowns[message.author.id]){
if(cooldowns[message.author.id] > Date.now()) delete cooldowns[message.author.id];
else console.log("user still has " + Math.round((cooldowns[message.author.id] - Date.now)/minute) + " minutes left"
}

I haven't tested it, but the simplest way to do this is something like:
const talkedRecently = new Set();
const seconds = "60";
loopnum = 0
while (loopnum <= seconds)) {
loopnum = loopnum + 1;
if (talkedRecently.has(msg.author.id + "-" + loopnum)) {
msg.channel.send("Wait **" + loopnum + " **seconds before getting typing this again. - " + msg.author);
return;
}
}
loopnum = seconds;
while (loopnum = 0) {
setTimeout(() => {
if (talkedRecently.has(msg.author.id + "-" + (loopnum+1))) {
talkedRecently.delete(msg.author.id "-" + (loopnum+1));
}
talkedRecently.add(msg.author.id + "-" + loopnum);
}, 1000);
loopnum = loopnum - 1;
}
if (talkedRecently.has(msg.author.id + "-1")) {
talkedRecently.delete(msg.author.id "-1");
}
return;

Related

Time left until you can use a command change 60 seconds to 1 minute

I made a 5 minute(300 seconds) cooldown for my discord.js bot, but when someone uses it more than once in under 5 minutes, it sends something like:
#Edward, please wait 250.32 second(s) until you can use this command!
Is there any way to change 250.32 seconds to something like 4 minutes 10 seconds or something close to that? I'm a noob at Node.js so help would be greatly appreciated.
if (!cooldowns.has(command)) {
cooldowns.set(command, new Discord.Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command);
const cooldownAmount = 1 * 300 * 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}\` command.`);
}
}
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
Read this discussion.
Basically you need to divide seconds with 60 to get minutes and then you use % to get the reminder:
const cooldownAmount = 1 * 275.45 * 1000;
const timeLeft = cooldownAmount / 1000;
var quotient = Math.floor(timeLeft / 60); //minutes
var remainder = Math.floor(timeLeft % 60); //seconds
console.log(quotient); // 4
console.log(remainder); // 35
This code should work in your case:
if (!cooldowns.has(command)) {
cooldowns.set(command, new Discord.Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command);
const cooldownAmount = 1 * 300 * 1000;
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
var quotient = Math.floor(timeLeft / 60); //minutes
var remainder = Math.floor(timeLeft % 60); //seconds
return message.reply(`Please wait ${quotient} minutes and ${remainder} seconds before reusing the \`${command}\` command.`);
}
}
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);

Instagram Auto-Like JavaScript BOT

This code brings back an error of
Uncaught TypeError: Cannot read property 'innerHTML' of null
at doLike (<anonymous>:20:21)
at <anonymous>:35:1
doLike # VM1269:20
(anonymous) # VM1269:35
It has worked in the past, I got it from this website : https://blog.joeldare.com/simple-instagram-like-bot/
function getHeartElement() {
var knownHeartElementNames = ["coreSpriteHeartOpen", "coreSpriteLikeHeartOpen"];
var i = 0;
// Loop through the known heart elements until one works
for (i = 0; i < knownHeartElementNames.length; i++) {
var heartElement = document.querySelector("." + knownHeartElementNames[i]);
if (heartElement != undefined) {
break;
}
}
return heartElement;
}
function doLike() {
var likeMax = 100;
var likeElement = getHeartElement();
var nextElement = document.querySelector(".coreSpriteRightPaginationArrow");
likeCount++;
var nextTime = Math.random() * (14000 - 4000) + 4000;
if (likeElement.innerHTML.match("Unlike") == null) {
likeElement.click();
console.log(likeCount + " - liked");
} else {
console.log(likeCount + " - skipped");
}
setTimeout(function() {nextElement.click();}, 1000);
if (likeCount < likeMax) {
setTimeout(doLike, nextTime);
} else {
console.log("Nice! Time for a break.");
}
}
var likeCount = 0;
doLike();
You may want to use a tool such a Keygram - https://www.thekeygram.com
It works really well for me to gain followers

App doesn't broadcast when wakeLocks added

I have a geoLocation app for a Firefox OS device (ZTE Open v1.1), that broadcasts to a web server its location details.
However, my code doesn't run if I minimise the app and turn the screen off.
I thought adding the following requestWakeLocks to the code would sort the problem, but it doesn't seem to help:
var lock = window.navigator.requestWakeLock('gps');
var lock = window.navigator.requestWakeLock('wifi');
Do you have any idea what I am doing wrong?
Code:
function init() {
document.addEventListener("DOMContentLoaded", watchPosition, false); // to test on web browser
//document.addEventListener("deviceready", watchPosition, false); // deviceready is a cordova event
}
/* ---------------------------------- Local Variables ---------------------------------- */
var checkPeriodically;
var watchPositionOutput = document.getElementById('watchPositionOutput');
var ajaxVars; // HTTP POST data values
/* ---------------------------------- Local Functions ---------------------------------- */
function watchPosition() {
var lock = window.navigator.requestWakeLock('gps'); // FireFox-OS only - keeps the gps active when screen is off
var lock = window.navigator.requestWakeLock('wifi');
checkPeriodically = setInterval(checkTime, 10000);
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
var options = {
enableHighAccuracy: true,
}
function onSuccess(position) {
ajaxVars =
"lt=" + position.coords.latitude +
"&lg=" + position.coords.longitude +
"&ac=" + position.coords.accuracy +
"&sp=" + position.coords.speed +
"&ts=" + position.timestamp +
"&sec=SEC_TOKEN";
var dt = new Date(position.timestamp);
date_time =
dt.getFullYear() + '-' +
(dt.getMonth() + 1) + '-' +
dt.getDate() + ' ' +
dt.getHours() + ':' +
dt.getMinutes() + ':' +
dt.getSeconds();
watchPositionOutput.innerHTML =
'Latitude: ' + position.coords.latitude + '<br>' +
'Longitude: ' + position.coords.longitude + '<br>' +
'Accuracy: ' + position.coords.accuracy + '<br>' +
'Speed: ' + position.coords.speed + '<br>' +
'Timestamp: ' + date_time + '<br>';
}
function onError(error) {
watchPositionOutput.innerHTML = 'code: ' + error.code + '<br>' +'message: ' + error.message + '<br>';
}
}
// update the server with location data
function ajax_post(postData){
// when there is no data in postData
if (typeof(postData) === 'undefined') { return false; } // exit the function
var req = new XMLHttpRequest(); // Create XMLHttpRequest object
var url = "http://example.com/locate-me/post.php";
//var url = "http://localhost/locate-me/post.php";
req.open("POST", url, true);
// Set content type header info for sending url encoded variables in the request
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
req.onreadystatechange = function() {
if(req.readyState == 4 && req.status == 200) {
var return_data = req.responseText; // return whatever php echos
var date_time = new Date(return_data * 1000); // php is currently returning the time (timestamp)
document.getElementById("status").innerHTML = "Server time: " + date_time;
}
}
// Send data to PHP, and wait for response to update the status div
req.send(postData); // execute the request
document.getElementById("status").innerHTML = "processing...";
}
// schedule to post the position data to a php script during certain times on certain days
function checkTime(){
// for example a day (day 0 == Sun) between 06:00 abd 23:45
var d = new Date();
var today = d.getDay();
var hms = d.getHours()+":"+d.getMinutes();
// mon - thurs
if( (today === 1 || today === 2 || today === 3 || today === 4) && hms > "10:23" && hms < "15:40") {
ajax_post(ajaxVars);
}
// friday
else if( today === 5 && hms > "13:00" && hms < "13:40") {
ajax_post(ajaxVars);
}
// testing: run all the time
else if( today < 7 ) {
ajax_post(ajaxVars);
}
else {
document.getElementById("status").innerHTML = "Data not scheduled to be posted to the server yet";
}
}
init();
Have you tried?
navigator.requestWakeLock('cpu');
If that still does not work, maybe you should follow the discussion in:
Firefox OS Background services

Asterisk 11 active calls event over AMI

Data I would like to have:
Num From , Num To , Duration, Codec, Context, Hold status
ofc in realtime update
I using node.js + nami
what the best way to get this information?
tried use an action Status(), but this gives me not full information about call and if I run it every second browser dies.
here is what I have:
updateCallList();
function updateCallList() {
socket.emit('GET_ACTIVE_CALLS', function(calls) {
$("#callsList").find("tr:gt(0)").remove();
if (calls.response != 'Success') return;
var calls = calls.events;
for (call in calls) {
if (calls[call].privilege == 'Call') {
var callFrom = calls[call].calleridnum + '<' + calls[call].calleridname + '>';
var callTo = calls[call].extension;
var callDuration = calls[call].seconds;
var callRoute = calls[call].context;
var tmpRow = '<tr>';
tmpRow = tmpRow + '<td>' + callFrom + '</td>';
tmpRow = tmpRow + '<td>' + callTo + '</td>';
tmpRow = tmpRow + '<td>' + callDuration + '</td>';
tmpRow = tmpRow + '<td>' + callRoute + '</td>';
tmpRow = tmpRow + '</tr>';
$('#callsList tr:last').after(tmpRow);
}
}
setInterval(function(){
updateCallList();
},1000);
});
}
server side
socket.on('GET_ACTIVE_CALLS', function (callback) {
action = new namiLib.Actions.Status();
nami.send(action, function (response) {
callback(response);
});
});
You need start daemon which will collect NewExten, Link, Unlink, Hangup events and create list of channels.
http://www.voip-info.org/wiki/view/asterisk+manager+events
Also you can do action command with "core show channels" "core show channel XXXXX", but asterisk will die if you do alot of that.
http://www.voip-info.org/wiki/view/Asterisk+Manager+API+Action+Command

Count down timer which don't reset on page refresh

How can I create a count down timer in JSF? I don't want the timer reset when refresh the page.
You can simply use Java Script for it.
Or
You can use RichFaces a4j:poll and poll count data from server where your timer will be running
You can use simply this script
var seconds = readCookie('countdown') || 60;
alert(seconds);
function secondPassed()
{
seconds--;
var minutes = parseInt(seconds / 60);
var remainingSeconds = parseInt(seconds % 60);
if (remainingSeconds < 10) {
remainingSeconds = "0" + parseInt(remainingSeconds);
}
document.getElementById('countdown').innerHTML = minutes + " mins : " + remainingSeconds + " secs";
if (parseInt(seconds) === 0)
{
alert("Time is over");
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Time is Over";
document.forms["myForm"].submit();
document.location.href = "examresult.jsp";
}
}
var countdownTimer = setInterval(function() {
secondPassed();
if (seconds === 0) {
eraseCookie(seconds);
} else {
createCookie(seconds, seconds, 7);
}
}, 1000);

Resources