How to correctly make a VoiceState event using eventHandler

I created the voiceXP.js event, which was supposed to grant experience every minute while in the Voice Chat. However, for some reason, the added console.log statements are not working, and XP is not being awarded. It's as if the "VoiceState" event is not triggering at all


voiceXP.js:
const { VoiceState } = require('discord.js');
const calculateLevelXp = require('../../utils/calculateLevelXp');
const Level = require('../../models/Level');
const cooldowns = new Set();
console.log(`WORK`);

function getRandomXp(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

/**
 *
 * @param {VoiceState} oldState
 * @param {VoiceState} newState
 */
module.exports = async (oldState, newState) => {
  console.log(`WORK`);
  if (!newState.member || newState.member.user.bot || cooldowns.has(newState.member.user.id)) return;

  const xpToGive = getRandomXp(10, 25); // Adjust the XP range as needed

  const query = {
    userId: newState.member.user.id,
    guildId: newState.guild.id,
  };

  try {
    const level = await Level.findOne(query);

    if (level) {
      level.xp += xpToGive;
      console.log(`WORK CLAIM`);
      if (level.xp > calculateLevelXp(level.level)) {
        level.xp = 0;
        level.level += 1;

        newState.guild.systemChannel.send(`${newState.member} you have leveled up to **level ${level.level}**.`);
      }

      await level.save().catch((e) => {
        console.log(`Error saving updated level ${e}`);
        return;
      });

      cooldowns.add(newState.member.user.id);
      setTimeout(() => {
        cooldowns.delete(newState.member.user.id);
      }, 60000);
    } else {
      const newLevel = new Level({
        userId: newState.member.user.id,
        guildId: newState.guild.id,
        xp: xpToGive,
      });

      await newLevel.save();

      cooldowns.add(newState.member.user.id);
      setTimeout(() => {
        cooldowns.delete(newState.member.user.id);
      }, 60000);
    }
  } catch (error) {
    console.log(`Error giving xp: ${error}`);
  }
  console.log(`WORK OUT`);
};


If you add
      client.on('voiceStateUpdate', (oldState, newState) => {
        // console.log(oldState, newState)
        console.log("Test")
      })
it to index.js, it produces messages normally
image.png
Was this page helpful?