-1

I want it to count for each user on voice channel the time he is on it and send it to a db.

After looking through the docs for a while, I do not see a way to see how long they have been in a channel. My solution for this would be to store the time that they join the channel, and then subtract that from the time they leave. How to do it?

Would like to continue my code, I am using mongo db.

client.on('voiceStateUpdate', (oldState, newState) => {
    let newUserChannel = newMember.voiceChannel;
    let oldUserChannel = oldMember.voiceChannel;

    ...
  });
jksnDev
  • 9
  • 2
  • Does this answer your question? [Find elapsed time in javascript](https://stackoverflow.com/questions/31405996/find-elapsed-time-in-javascript) – Kaddath Apr 05 '23 at 15:30

1 Answers1

0

To get the total amount of time the user has been in the voice channel, you would have to save the timestamp of when the user joined the voice channel and when the user leaves the voice channel, subtract the saved timestamp from the timestamp when the user left the voice channel. You could save the timestamp with a Map for example, but you could also use a database for example. In the example below I've made use of a Map as it's an easy way to save values with a key.

const users = new Map();
...
client.on('voiceStateUpdate', (oldState, newState) => {
   const member = oldState.member || newState.member;
   if(!member) return;
   
   if(!newState.channel && oldState.channel){
      // User left the voice channel
      const joinedTimestamp = users.get(member.id); // Get the saved timestamp of when the user joined the voice channel
      if(!joinedTimestamp) return; // In case the bot restarted and the user left the voice channel after the restart (the Map will reset after a restart)
      const totalTime = new Date().getTime() - joinedTimestamp; // The total time the user has been i the voice channel in ms
      // Do what you want with the time
   } else if(oldState.channel && !newState.channel){
      // User joined the voice channel
      users.set(member.id, new Date().getTime()); // Save the timestamp of when the user joined the voice channel
   }
});
Luuk
  • 641
  • 4
  • 12