简体   繁体   中英

Discord.js random role reactions

I'm trying to make a command that sends an embed and reacts with an emoji and when a member clicks the emoji it gives them a random role. any idea on how I would go about doing this?

const {Client, MessageEmbed} = require('discord.js')

const client = new Client()

client.on('message', async ({author, channel, guild, member}) => {
  // don't do anything if it's a bot
  if (author.bot) return

  // don't do it if it's a DM
  if (!guild) return

  // replace these with whatever you want
  const embed = new MessageEmbed({title: 'some embed'})
  const emoji = '😀'

  const roles = guild.roles.cache.filter(role =>
    // you can't add the @everyone role
    role.name !== '@everyone' &&
    // or managed roles
    !role.managed &&
    // or roles that the bot isn't above
    guild.me.roles.highest.comparePositionTo(role) > 0
  )

  try {
    if (!roles.size) return await channel.send('There are no roles that I can add!')

    const message = await message.channel.send(embed)
    await message.react(emoji)
    await message.awaitReactions(
      // only for await for the 😀 emoji from the message author
      (reaction, user) => reaction.emoji.name === emoji && user.id === author.id,
      // stop after 1 reaction
      {max: 1}
    )
    await member.roles.add(roles.random())
  } catch (error) {
    // log all errors
    console.error(error)
  }
})

client.login('your token')

Note: Your bot must have the MANAGE_ROLES permission to be able to add a role to a guild member.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM