Search code examples
javascriptdiscorddiscord.js

Discord.js v13 check if button already has been pressed


is there a way using collectors/interactionCreate to detect if a user already pressed a specific button on a specific message? One way I tried doing it was to save it in an array like this

const alreadyPressed = []
const filter = m => m.customId === "No" && m.messageId === interaction.messageId && m.user.id === interaction.user.id;
collector = embedMsg.createMessageComponentCollector({filter: filter, time: 10000});//86400000

collector.on('collect', async i => {
    client.logger("collector1 collected")
    client.logger(alreadyPressed.indexOf(i.user.id, i.messageId))
    if (alreadyPressed.indexOf(i.user.id, i.messageId)) {
        return i.reply({ content: `You've already voted ${i.user.username}!`, ephemeral: true })
    } else {
        i.reply({ content: `Thank you for your vote ${i.user.username}!`, ephemeral: true });
        alreadyPressed.push(i.user.id, i.messageId)
    }
});   
collector.on('end', collected => {
    client.logger(collected.size)
    // if (collected.size < 10) {
        
    // }
    delete alreadyPressed[0]
    delete alreadyPressed[1]
});

but the bot always ends up responding with "You've already voted" so what would be a viable way of checking this?


Solution

  • as MrMythical said, Array#indexOf() will just return -1 since it can't find it, I tried this out a little bit and found out that using and storing the values in an array is probably what your looking for. I put them together too since putting them seperate is not needed then I use .find() to search the array if it matches the users id and the id of the message that the button is on. This would be a viable way of doing it

    const alreadyPressed = []
    const filter = m => m.customId === "No"
    collector = embedMsg.createMessageComponentCollector({filter: filter, time: 10000});//86400000
    
    collector.on('collect', async i => {
        if (!!alreadyPressed.find(id => {  
            return id.ID === i.user.id+i.message.id
          })) {
            i.reply({ content: `You've already voted ${i.user.username}!`, ephemeral: true })
          } else {
            i.reply({ content: `Thank you for your vote ${i.user.username}!`, ephemeral: true });
            alreadyPressed.push({ID: i.user.id+i.message.id})
        }
    });   
    collector.on('end', collected => {
        client.logger(collected.size)
        // if (collected.size < 10) {
            
        // }
        delete alreadyPressed
    });