Vote system to my discord bot with nodejs - node.js

I'm making a command .report #user that creates a simple poll with 2 buttons added "agree" and "disagree". After certain time i want the bot to register user if agree's is more than disagree.
How can i make my bot count the results of voting after 7 days and then based on this either register on DB an user or send "Report Voting Failed".
What I hope is to be able to store the expiration date of the voting and that on that date the voting stops working and the corresponding action is taken.

You can use setTimeout() for this. setTimeout() takes in two parameters. One, a function which holds your code that will be ran after the time has passed. Two, the amount of time in milliseconds to wait before executing your code.
Here is an example of how to use this.
console.log('1') // will console.log 1 instantly
setTimeout(() => {
console.log('2') // will console.log 2 after 1 second.
},
1000) // 1s = 1000ms
Furthermore, you can use buttons to accomplish the task of reporting. Check out the guide on buttons for more info. Once a button is pushed, see whether it is an Agree or Disagree then do what you must from there. After the seven days is up, make the buttons unable to press, or whatever you want.
You might want to employ a node.js module such as ms to convert 7d into ms. This could be useful as 7 days in milliseconds is 604,800,000. Using ms,
you could do
const sevenDays = ms('7d') // returns 604800000
and then pass that into your setTimeout() function.
like so:
setTimeout(() => {
console.log('The seven days has passed')
}, sevenDays)
Note however your bot will need to stay online for the duration of these 7 days, otherwise it will not run as it has forgotten that the setTimeout() function was used in an earlier instance.

Related

Timestamp For Discord Bot Status

I am using Discord.js Node V12 I am currently trying to find out how to say time elapsed in the status to show how long the bot has been playing game or any activity. But i cannot find anyone who has asked or answered any of these questions.
#client.event
async def on_connect():
await client.change_presence(status=discord.Status.dnd,activity = discord.Game(name = "VALORANT"))
I would like to break this answer into a few significant points:
• The sample code provided is from discord.py ( a discontinued python based library to interact with the API ) which is totally out of context of the whole question itself since you're asking it for discord.js
• There is no actual way to find the time elapsed since a particular activity as of now but you may resort to this:
var uptime = client.uptime; // returns uptime in milliseconds
var hours = uptime / 1000 / 60 / 60 // converts it to hours
/*
Then you may apply the following approach to change your status every hour passes
*/
setInterval(() => {
client.user.setActivity(`Valorant since ${hours} hour(s)`);
}, 3600000); // this would show up as Playing Valorant since 1 hour(s) and subsequently would change every hour if your bot isn't being restarted continuously.
I took a look at the discord.js documentation to examine setting activities and found no such information about timestamps. However, there was a section in the ActivityType that led me to the discord developers documentation and it indicates:
Bots are only able to send name, type, and optionally url.
So it doesn't seem as though you will be able to set the start or end timestamps for an activity as a bot.

Can I create my own successful response in Jasmine node.js?

I'm wanting to force a test returns failure, bring success, why this?
I am using the proctrator and I need to wait for a data that comes from the server to the screen, however I have to update the page every 1 minute, I could not do something that updates and at the same time wait for the answer, I had to make a "for" execute a promise with loop that repeats 14 times, which gives a total of 14 minutes and every minute it refreshes the page, when it arrives the dice throws me an exception that can end before the loop is over, so that I can move on to the next test .
To not fail in my test, I would like this exception to be true, but I could not put a function in the jasmine to modify it, I have a very simple example of what I would like to do.
describe('Start simulator False', () => {
it('expect a fake to turn true ', () => {
const addition = 5 + 5;
expect(addition).toBe(2);
});
});
This expectation that expects 10 instead of 2, I would like instead of seeing a fake would like to see a truth, I know it is wrong but I can create a unique function that only I can use when ignoring its basic logic because I I know it's true and the only alternative I have is this.
You can create your own custom equality testers. See the documentation : https://jasmine.github.io/tutorials/custom_equality
But i will replace the jasmine equality tester.
So maybe you want to add your own matcher : https://jasmine.github.io/tutorials/custom_matcher

How do I count the number of users in my quiz bot?

I am using bot framework where I proactively start a quiz game every 24 hours. The code for this looks like
bot.beginDialog(user.address, '/runChallenge', args, (error) => {
if (error) {
// error ocurred while starting new conversation. Channel not supported?
console.log(JSON.stringify(error), user.address)
bot.send(new builder.Message()
.text("The rat nibbled the wires before we could start the game for you. Sorry about that :(")
.address(user.address));
}
})
A couple of questions
How do i count the number of players in the game?
I could make a global variable called players inside my bot.js file
and increment it by 1 each time the bot.dialog('/quiz') is called
inside its 1st waterfall step. Given the file is included once at
the beginning, once I increment it, I guess i ll have to reset it
back to 0 somewhere.
Or I could use a local variable inside the cron job function which
can pass another parameter called playersCount as args to the dialog
where it will be a local variable but I am not sure if this is the
right approach
Everytime, a person answers incorrectly, they are out of the
challenge. I would like to count how many people answered
incorrectly. What would be a good way to go about this?
I would also like to declare the results of the quiz after say
everyone is done with it, The maximum time taken by anyone and
everyone is 15 mins for the round. I am planning to use a setTimeout
after 15 mins of initiating the game since I already use a CronJob
every 23 hours to trigger the quiz. Any suggestions?

NodeJs throttle data

I would like to know, how to use javascript to achieve my use case,
My app receives a post request, then it incr memcache key, then it publish the increased value straightaway to users(mobile app) using third party API.
Eg. first requst value become 1, publish 1.
second request value become 2, publish 2 ...
It works fine with requests less than 2k within 30 secs.
If the requests number goes up to 10k, users(mobile app) may receive too many messages from publisher(battery consuming)
So I have to the throttle publishing calls, instead of publishing per request, I want to publish the value every second. In 1 second, the value can be 1, then publish 1. In 2 second then value can be 100, then publish 100. So that I saved 99 publish calls.
When requests are not coming anymore, I don't want a worker keep running every second.
Each time it increments, cache the new value to a global variable and post it to clients using setInterval. Here is a simple example:
var key = 0;
// Update the cache to the present
// value on application start
memcache.get('key', updateKey);
// Handle increment request and
// save the new value
app.post('/post', function(req, res){
memcache.incr('key', updateKey);
});
// Update the cached key
function updateKey(err, val){
key = val;
}
// Publish to clients once
// a second
function publish(){
clients.emit(key);
}
setInterval(publish, 1000);
Starting and stopping this routine is a little more involved and may depend on how you're serving requests / incrementing the value.
Take a look at node-rate-limiter
You can implement it in a number of ways to solve your problem...

how can I remove/delete data from server node.js using interval time/ settimeout?

hi I'm trying create chat using node.js
I see example in http://chat.nodejs.org/
I have tried it and it works but how can I remove/delete data from server using interval time like in javascript without have to restart node.js/ terminal prompt?....
example:
time:
17:14
17:12
16:13
15:11
14:17
function del(){
if(time<timenow-1000){delete time;}}
setInterval("del()",10000);
I want to delete data less than two hours ago every one hours using interval time...thanks
First off, I would highly recommend against using the setInterval overload you are using that takes an eval string. Instead, always use the version that takes a callback. For example:
setInterval(1000, function () {
// do something
});
Take a look at the source and you will see that messages are stored in the messages array:
https://github.com/ry/node_chat/blob/master/server.js
Your function just needs to inspect this array and remove messages whose timestamp is older than your desired date. For example:
setInterval(1000, function () {
while (messages.length && messages[0].timestamp < someTime) {
messages.shift();
}
});
This will keep removing the oldest message while it is older than someTime, which is a time you will need to specify.

Resources