Search code examples
javascriptdiscord.js

How to mention a user in a message with discord.js?


I am implementing a command to mute users. For example, the following command would mute the user @anon for 5 seconds:

!mute @anon 5

My program listens for the message event, mutes the user and sends a confirmation message like this:

@anon#1234 has now been muted for 5 s

Unfortunately Discord does not recognize the username in this message as a mention. How can I mention a specific user with the msg.channel.send function? This sample includes the code which sends the confirmation message:

bot.on("message", msg => {
    let args = msg.content.substring(PREFIX.length).split(" ")
    let time = args[2]
    let person = msg.guild.member(msg.mentions.users.first() || msg.guild.members.fetch(args[1]))

    // muting the user here and sending confirmation message
    msg.channel.send(`@${person.user.tag} has now been muted for ${time} s`)

    setTimeout(() => {
        // unmuting the user after specified time and 
        // sending confirmation message
        msg.channel.send(`@${person.user.tag} has been unmuted.`)
    }, time * 1000);
})

The muting is not included in this sample, it works. The messages are being sent correctly but the user is not mentioned, meaning the username is not clickable and doesn't get highlighted.


Solution

  • The documentation recommends this way to mention a user:

    const message = `${user} has been muted`;
    

    The example above uses template strings, therefore the toString method of the User object is called automatically. It can be called manually though:

    const message = user.toString() + "has been muted";
    

    The documentation states:

    When concatenated with a string, this [the user object] automatically returns the user's mention instead of the User object.

    Which means that every time toString is invoked, either by templates, string concatenation or by manually calling toString, the user object will be converted to a mention. Discord will interpret the output correctly, highlights it and makes it clickable.


    In your case you would use the above example like this:

    msg.channel.send(`${person.user} has now been muted for ${time} s`)
    setTimeout(() => {
        ...
        msg.channel.send(`${person.user} has been unmuted.`)
    }, time * 1000)