Search code examples
node.jspointsdiscorduserid

Discord <@!userid> vs <@userid>


so I'm creating a bot using Node.JS / Discord.JS and I have a question.

On some servers, when you mention a user, it returns in the console as <@!userid> and on other it returns as <@userid>. My bot has a simple points / level system, and it saves in a JSON file as <@!userid>, so on some servers when trying to look at a users points by mentioning them will work, and on others it won't.

Does anyone have any idea how to fix this? I've tried to find an answer many times, and I don't want to have it save twice, once as <@!userid> and then <@userid>. If this is the only way to fix it then I understand.

Thanks for your help!


Solution

  • The exclamation mark in the <@!userID> means they have a nickname set in that server. Using it without the exclamation mark is more reliable as it works anywhere. Furthermore, you should save users with their id, not the whole mention (the "<@userid>"). Parse out the extra symbols using regex.

    var user = "<@!123456789>" //Just assuming that's their user id.
    var userID = user.replace(/[<@!>]/g, '');
    

    Which would give us 123456789. Their user id. Of course, you can easily obtain the user object (you most likely would to get their username) in two ways, if they're in the server where you're using the command, you can just

    var member = message.guild.member(userID);
    

    OR if they're not in the server and you still want to access their user object, then;

    client.fetchUser(userID)
        .then(user => {
            //Do some stuff with the user object.
        }, rejection => {
            //Handle the error in case one happens (that is, it could not find the user.)
        });
    

    You can ALSO simply access the member object directly from the tag (if they tagged them in the message).

    var member = message.mentions.members.first();
    

    And just like that, without any regex, you can get the full member object and save their id.

    var memberID = member.id;