随机选择文本渠道中的用户

时间:2020-04-15 17:40:19

标签: javascript random bots discord discord.js

我使用discord.js制作了一个discord机器人,它具有一些有用的命令。我想再添加一个,它将标记我使用该命令的文本通道中的随机人。例如,如果我在#test123频道中使用该命令,它将标记一个具有test123角色的随机人。

1 个答案:

答案 0 :(得分:0)

这仅适用于Discord.js v12:

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

const client = new Client()

client.on('message', async ({author, channel, content, guild}) => {
  if (
    // author of message is a bot
    author.bot ||
    // message is in a DM
    !guild ||
    // message doesn't start with #
    !content.startsWith('#')
  ) return

  // gets rid of the #
  const name = content.slice(1)

  try {
    // uncomment this out if you don't want people to be able to do this with @everyone
    // the backslash stops the bot from pinging everyone
    // if (name === '@everyone') return await channel.send("You can't do this with \\@everyone!")

    const role = guild.roles.cache.find(r => r.name === name)
    if (!role) return await channel.send(`${name} is not a valid role!`)
    if (!role.members.size) return await channel.send(`There are no members with the role ${role}.`)

    // discord.js automatically tags/mentions a member if it is converted to a string
    await channel.send(`${role.members.random()}`)
  } catch (error) {
    // you could also send a message or something
    console.error(error)
  }
})

client.login('your token')

对于v11,只需替换

    const role = guild.roles.cache.find(r => r.name === name)

使用

    const role = guild.roles.find(r => r.name === name)