Search code examples
javascriptnode.jsdiscorddiscord.js

How can I execute certain part of code from a reaction on a private message (not a channel message) with Discord.JS?


I am creating a Discord bot that sends private welcome messages to users that enter my server.

My Discord bot private message screen

I want to execute some lines of code (I want to add different roles to the users) which differ if the user reacts with those three emojis.
Online I found guides that refer to channel messages only and I don't understand which approach to use with private messages.
Thank you!


Solution

  • The approach for private messages should be the same as channel messages.

    // Create a reaction filter that only will collect those three emojis
    const filter = (reaction, user) => ['🇮🇹', '🇬🇧', '🤫'].includes(reaction.emoji.name)
    
    // Create reaction collector (message is the message the bot sent).
    // The time is the time in milliseconds that the collector should run for
    // (i.e. how long the user has to react).
    // Discord.js v12:
    // const collector = message.createReactionCollector(filter, {time: 15000})
    // Discord.js v13:
    const collector = message.createReactionCollector({filter, time: 15000})
    
    // Fired when the user reacts
    collector.on('collect', (reaction, user) => {
      switch (reaction.name) {
        case '🇮🇹':
          message.reply('you chose Italian!')
          break
        case '🇬🇧':
          message.reply('you chose English!')
          break
        case '🤫':
          message.reply('you have a secret code!')
      }
    })
    

    For more information see the Discord.js guide (archive).