Loyalty points system unexpectedly distributed points | Node.js Tmi.js

Asked

Viewed 232 times

0

I am currently developing a chat bot for my Twitch channel. I want to implement a system of loyalty points that are distributed after a while only to those who are present in the chat, so I have to check if a user has entered or left the chat and change the values that are stored in a .json. file. json will be stored the user points and whether they are in chat or not.

This is the code:

    let data = fs.readFileSync('./data/data.json');
    let viewer = JSON.parse(data);

    function givePoints(user){
    function intervalFunc() {
    if(viewer[user].online === 1){
    viewer[user].points += 10;
    fs.writeFileSync('./data/data.json', JSON.stringify(viewer, null, 2));
    console.log("+10 Points - " + user);
};
};
setInterval(intervalFunc, 30000);
};

client.on('join', function(channel, user){
    console.log("JOINED:  " + user);

    if(!viewer[user]){
        viewer[user] = {
            online: 1,
            points: 0
        };
    };

    viewer[user].online = 1;            
    fs.writeFileSync('./data/data.json', JSON.stringify(viewer, null, 2));

    givePoints(user);
});

client.on('part', function(channel, user){
    console.log("PARTED:  " + user);
    viewer[user].online = 0;
    fs.writeFileSync('./data/data.json', JSON.stringify(viewer, null, 2));
});

This is the . json:

    {
  "streamelements": {
    "online": 0,
    "points": 0
  },
  "jptron": {
    "online": 0,
    "points": 0
  }
}

The program successfully detects whether the user exists in . json and if Join or part. The problem is when someone leaves the chat and comes back in. When this happens the program distributes the points to that user more times than it should.

I added a.log console whenever the bot distributes the points: Logs dos pontos The user streamelements is another bot connected to my channel.

I wonder what I might be changing in my code for this to work the way intended.

1 answer

0


When the user enters vc triggers the setInterval function, but when the user leaves vc does not cancel it.

What happens is that the client enters, before giving the time he leaves and enters again. So he will stay with 2 timers associated to him. When he reaches the time of the first timer he wins the points, when he reaches the time of the second he wins again.

I think of 2 options:

  1. Save the variable of each user’s setInterval and a clearInterval when the user leaves.
  2. Save in your json the last input date and beyond the validation if the client is online in the intervalFunc validates how much time has passed, if it is less than the configured timer does not give the points.
  • Thank you very much. I don’t know why I didn’t think of it before, I added a clearInterval to the function and it’s working fine.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.