How to prevent duplicate votes in a Discord music bot's skip feature?

Hey everyone! I’m working on a Discord bot for music playback. I’ve got a skip feature, but I’m stumped on how to stop users from voting multiple times. Here’s what I’ve got so far:

function handleSkipCommand(message) {
  const guild = guilds.get(message.guild.id);
  if (hasSpecialRole(message.author, 'SkipMaster')) {
    resetVotes();
    skipCurrentTrack(guild);
    return;
  }
  
  incrementVotes();
  if (getTotalVotes() < REQUIRED_VOTES) {
    notifyRemainingVotes();
  } else {
    resetVotes();
    skipCurrentTrack(guild);
  }
}

This works, but it doesn’t stop people from voting more than once. Any ideas on how to fix this? Thanks in advance for your help!

hey there! u could try storing user IDs in a Set for each song. when someone votes, check if their ID is already in the Set. if not, add it and count the vote. if it is, ignore it. clear the Set when the song changes. this way each person can only vote once per song. hope that helps!

I’ve dealt with this exact issue before in my own Discord bot. What worked for me was using a Map to keep track of votes. The key is the user’s ID, and the value is a boolean indicating if they’ve voted. Something like this:

const voteMap = new Map();

function handleSkipCommand(message) {
  const userId = message.author.id;
  if (voteMap.has(userId)) {
    message.reply('You've already voted to skip!');
    return;
  }

  voteMap.set(userId, true);
  // Rest of your logic here

  if (voteMap.size >= REQUIRED_VOTES) {
    resetVotes();
    skipCurrentTrack(guild);
  }
}

function resetVotes() {
  voteMap.clear();
}

This way, each user can only vote once per track. Don’t forget to clear the Map when the song changes or when skipping occurs. It’s simple but effective!

When implementing a skip feature, it is important to ensure each user vote is recorded uniquely. One effective approach is to track the user IDs internally. Before counting a vote, check whether the user’s ID has already been recorded. If it has not, add the ID and count the vote; if it has, simply ignore the additional vote. Once a track is skipped, clear these records to prepare for the next voting session. Be mindful of edge cases, such as users leaving and rejoining, and consider incorporating a brief cooldown period for added protection.