OffstageAlmond
OffstageAlmond

Reputation: 323

Getting a user ID from a mention

I want to get a Users ID from a mention. I am making a user info command so the author of the message will not always be them so I cannot do message.author.id. I have used substrings to split the command into the command itself and the mention but I cannot turn the mention into an ID.

I am aware that discords mentions are actually <@USERID>, which is another way I could get the ID. Please tell me if I am able to get rid of the <@> so I am left with the ID, or turn the mention itself into an one using another method. I have looked through the docs and I am not aware of anything that could help me.

Upvotes: 4

Views: 26024

Answers (2)

Aristocles
Aristocles

Reputation: 39

I know the poster already got their answer, but those looking to get all of the ids, there is a different approach:

// Listen for messages
client.on( Events.MessageCreate, async ( message ) => {

    // Get any mentions
    const mentions = message.mentions;
    if ( !mentions ) {
        return;
    }

    // Get the mentioned users
    const usersList = Array.from( mentions.users );

    // Iter the users
    usersList.forEach( function ( user ) {

        // Check if they mentioned the bot
        const userID = user[0];

        // ... Do what you want with each id
        
    } );
    return;
});

Upvotes: 1

Federico Grandi
Federico Grandi

Reputation: 6806

You can do that in two ways: if you want to use the mention as an argument, you can remove the mention characters with regex, like this: yourstring.replace(/[\\<>@#&!]/g, "");.
The other way to do that is to get the first mention in the message and then the user's id: message.mentions.users.first().id.

Upvotes: 11

Related Questions