jonah
jonah

Reputation: 21

In discord.js, how could i create a command that displays the avatar of a user tagged, or if not tagged - my avatar?

client.on("message", msg => {
      if (msg.content === `${prefix}pfp`) {
        var users = msg.mentions.users.first() || msg.author;
        msg.channel.send(users.displayAvatarURL());
  }
})

Usually, this code only sends the display of the message author's avatar, but not the person who was tagged in the command.

Upvotes: 0

Views: 80

Answers (1)

Mineko Kayui
Mineko Kayui

Reputation: 761

client.on("message", msg => {
      if (msg.content === `${prefix}pfp`) {
//    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        var users = msg.mentions.users.first() || msg.author;
        msg.channel.send(users.displayAvatarURL());
  }
})

You're using msg.content which is the overall content of the message. If you mention someone, the content will be ${prefix}pfp <@a_user's_id> instead of ${prefix}pfp which will then not call the command.

Try instead to use msg.startsWith() like shown below:

client.on("message", msg => {
      if (msg.content.startsWith(`${prefix}pfp`)) {
//    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        var users = msg.mentions.users.first() || msg.author;
        msg.channel.send(users.displayAvatarURL());
  }
})

This will call the function if it starts with ${prefix}pfp rather than it containing such. Which will allow them to mention someone.

Upvotes: 2

Related Questions