Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

javascript - How can you check if the bot is being pinged?

I am creating a command that "kills" people. I want the bot to return the message "Ha! You thought! @Author died!" if they ping the bot. (How do I get the Bot to see if it is pinged?) Answer has been updated and now fully works.

const Discord = require('discord.js');
const bot = new Discord.Client();

module.exports = {
    name: 'kill',
    description: 'kills',
    execute(message, args, bot) {
      message.delete({ timeout: 30000 });
  
      if (message.content.startsWith('-kill')) {
        const target = message.mentions.users.first();
        const memberTarget = message.guild.members.cache.get(target.id);
  
        if (message.mentions.has(bot.user)) {
          return message.channel.send(`HA! SIKE! <@${message.author.id}> died.`);
        }
        message.channel.send(`<@${memberTarget.user.id}> has died!`);
        console.log(`<@${memberTarget.user.id} died.`);
      }
    },
  };
question from:https://stackoverflow.com/questions/65942391/how-can-you-check-if-the-bot-is-being-pinged

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use message.mentions.has(bot.user) to check if the bot is mentioned. Also, make sure you're passing the bot to your execute() method instead of instantiate a new one:

module.exports = {
  name: 'kill',
  description: 'kills',
  execute(message, args, bot) {
    message.delete({ timeout: 30000 });

    if (message.content.startsWith('!kill')) {
      const target = message.mentions.users.first();
      const memberTarget = message.guild.members.cache.get(target.id);

      if (message.mentions.has(bot.user)) {
        return message.channel.send(`HA! SIKE! <@${message.author.id}> died.`);
      }
      message.channel.send(`<@${memberTarget.user.id}> has died!`);
      console.log(`<@${memberTarget.user.id} died.`);
    }
  },
};

And in your main JS file pass down the bot object:

// ...
client.commands.get('kill').execute(message, args, bot) 
// ...

enter image description here enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...