I made a discord bot using discord.js and it has some useful commands to it. I want to add one more, one that will tag a random person from the text channel I used that command. For example, if I use that command in #test123 channel, it will tag a random person that has test123 as a role.
This only works for Discord.js v12/v13:
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')
For v11 just replace
const role = guild.roles.cache.find(r => r.name === name)
with
const role = guild.roles.find(r => r.name === name)