简体   繁体   中英

How to get the username of a person you pinged in a message in discord.js

I am working on a code in which sends a hug embed in discord.js

this is my code: (the prefix is set to --> `

  if (message.content === prefix + "hug") {
      return
  }
});




client.on ("message", message => {
  const user = message.author.username;
  const bid = (message.content.replace(prefix + "hug ",''));
  const rex = bid.replace("@!", "");
  const rl = rex.replace("<", "");
  const rr = rl.replace(">", "");

  const idtoname = client.users.cache.get(rr);

  

  

  if (message.author.bot) return;
  if(message.content === prefix + "hug") return;

  if (message.content.startsWith(prefix + "hug")) {
  
      const hugembed = new Discord.MessageEmbed()
      .setTitle(user + " hugs " + idtoname.username)
      .setColor(0xbc13fe)
      .setImage("https://www.dropbox.com/s/450lk7apiuf0uk0/huggoooo.gif?dl=1");
      message.channel.send(hugembed);
  
      
  }
});

The code is basically sends an embed with a hug gif, and the title is (message.author.username) " hugs " (the person i pinged)

The problem is, i am using the sender's message, and replacing everything else except the id, and converting the id into username

but the problem arises when someone message prefix + hug (no ping, just text) , or prefix + hug (more than 1 pings) , the bot crashes in both the scenarios.

Is there any way i can store the username of the person i pinged using `hug command in a variable, and use that instead of replacing the message itself?

Define the mention, no need to check message content, there's already message.mentions (mentions = pings)

const mentionedUser = message.mentions.users.first();

Check for text only, no mentions

if (!mentionedUser) {
   return message.channel.send('Please mention a user')
}

Use the data

const hugembed = new Discord.MessageEmbed()
      .setTitle(`${user} hugs ${mentionedUser.username}`)
      .setColor(0xbc13fe)
      .setImage("https://www.dropbox.com/s/450lk7apiuf0uk0/huggoooo.gif?dl=1");
      message.channel.send(hugembed);

Try this:

client.on ("message", message => {
  if(message.author.bot) return;
  const user = message.author.username;

  if (message.content.startsWith(prefix + "hug")) {
    const mentioneduser = message.mentions.users.first();
    if(!mentionuser) return message.channel.send(`You need to mention a user to give a hug to!`)
  
      const hugembed = new Discord.MessageEmbed()
      .setTitle(`${user} hugs ${mentioneduser.user.username}`)
      .setColor(0xbc13fe)
      .setImage("https://www.dropbox.com/s/450lk7apiuf0uk0/huggoooo.gif?dl=1");
      message.channel.send(hugembed);  
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM