check if message mentions users discord js

How to check if a message mentions a user using Discord.js?

If you are building a Discord bot using Discord.js, you may want to know if a message sent by a user mentions another user. This can be useful for various purposes like tracking user interactions, tagging users, or sending specific messages to certain users.

Method 1: Using message.mentions Property

The easiest way to check if a message mentions a user is by using the message.mentions property of the message object. This property returns a MessageMentions object that contains various mentions like users, roles, and channels.

client.on('message', message => {
  // check if message mentions any user
  if (message.mentions.users.size > 0) {
    // do something
  }
  
  // check if message mentions a specific user
  const mentionedUser = message.mentions.users.first();
  if (mentionedUser.id === 'user_id_here') {
    // do something
  }
});

In the above example, we are checking if the message mentions any user using the size() method of the message.mentions.users collection. If the size is greater than 0, it means at least one user is mentioned in the message.

We are also checking if the message mentions a specific user using the first() method of the message.mentions.users collection to get the first user mentioned, and then comparing its id property with the desired user ID.

Method 2: Using Regular Expressions

If you want to check if a message mentions a specific user without using the message.mentions property, you can use regular expressions to search for the user ID or username in the message content.

client.on('message', message => {
  // check if message mentions a specific user using regex
  const userIdRegex = /<@!?(.*?)>/;
  const usernameRegex = /@(\w+)/;
  
  const userIdMatch = message.content.match(userIdRegex);
  const usernameMatch = message.content.match(usernameRegex);
  
  if (userIdMatch && userIdMatch[1] === 'user_id_here') {
    // do something
  }
  
  if (usernameMatch && usernameMatch[1] === 'username_here') {
    // do something
  }
});

In the above example, we are using two regular expressions: /<@!?(.*?)>/ to match user IDs in the format of <@USER_ID> or <@!USER_ID>, and /@(\w+)/ to match usernames starting with @ symbol.

We are then using the match() method of the message content to get the matched string, and comparing it with the desired user ID or username.

Conclusion

These are two methods you can use to check if a message mentions a user using Discord.js. The first method is easier and more efficient, but may not suit all use cases. The second method is more flexible but requires more coding and may not be as reliable. Choose the method that suits your needs best.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe