Home > Enterprise >  Check if first argument is a mention
Check if first argument is a mention

Time:03-20

I'm coding a discord bot and I'm trying to make a kick command right now. I managed to find how to check if there's any mention in the command message with message.mentions.members.first() but I couldn't find anything to check if a specific argument is a mention.

Code I have so far:

module.exports = {
    name: "kick", 
    category: "moderation",
    permissions: ["KICK_MEMBERS"], 
    devOnly: false, 
    run: async ({client, message, args}) => {
        if (args[0]){
            if(message.mentions.members.first())
                message.reply("yes ping thing")
            else message.reply("``"   args[0]   "`` isn't a mention. Please mention someone to kick.")
        }
        else
            message.reply("Please specify who you want to kick: g!kick @user123")
    }
}

I looked at the DJS guide but couldn't find how.

CodePudding user response:

MessageMentions has a USERS_PATTERN property that contains the regular expression that matches the user mentions (like <@!813230572179619871>). You can use it with String#match, or RegExp#test() to check if your argument matches the pattern.

Here is an example using String#match:

// make sure to import MessageMentions
const { MessageMentions } = require('discord.js')

module.exports = {
  name: 'kick',
  category: 'moderation',
  permissions: ['KICK_MEMBERS'],
  devOnly: false,
  run: async ({ client, message, args }) => {
    if (!args[0])
      return message.reply('Please specify who you want to kick: `g!kick @user123`')

    // returns null if args[0] is not a mention, an array otherwise
    let isMention = args[0].match(MessageMentions.USERS_PATTERN)

    if (!isMention)
      return message.reply(`First argument (_\`${args[0]}\`_) needs to be a member: \`g!kick @user123\``)

    // kick the member
    let member = message.mentions.members.first()
    if (!member.kickable)
      return message.reply(`You can't kick ${member}`)

    try {
      await member.kick()
      message.reply('yes ping thing')
    } catch (err) {
      console.log(err)
      message.reply('There was an error')
    }
  }
}
  • Related