Is there a way to determine if the bot is being pinged?

I need help creating a new command for my bot that simulates "killing" people. I want the bot to respond with the message "Ha! You thought! @Author died!" if someone pings the bot. (How can I make the Bot detect when it is pinged?) This answer has been updated and is now fully functional.

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.`);
            }
        },
    };

Answer №1

To determine if the bot is mentioned, you can utilize message.mentions.has(bot.user). It's also important to ensure that you pass the existing bot to your execute() function instead of creating 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.`);
    }
  },
};

In your main JS file, be sure to pass the bot object like this:

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

https://i.sstatic.net/gNZqZ.png https://i.sstatic.net/89mvn.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for switching out images depending on the time of day

Currently, I have a script that dynamically changes the background color of my webpage based on the time of day. However, I am facing issues trying to implement a similar functionality for replacing an image source. The current code is also time zone-based ...

Using external scripts that require access to the DOM and window object within a Javascript/Node.js Azure Function: Best practices

I am attempting to integrate external JavaScript into an Azure Function that uses the JavaScript/Node.js flavor. The external JavaScript library I need to use, Kendo, relies on a DOM and a window. To achieve this, I initially experimented with JSDOM, but I ...

Learn how to prevent the rendering of a specific section of code using JavaScript/TypeScript, similar to the functionality of *ngIf in Angular

When it comes to hiding specific parts of HTML code, using comments or CSS with display:none is one option, but these are still accessible in the developer tools. How can we leverage the features of JavaScript or TypeScript to prevent these sections from ...

Utilizing HTML and Javascript for streaming audio and recording voice

Working on a new project that involves streaming audio files (mp3) and recording voice messages. Initially considered using Flash, but the challenge is making the website iPhone-friendly as per the client's request. Is there a technology available th ...

Troubleshooting: Why is $watch failing to track changes on factory variables in Angular

I have created a factory named SharedService as shown below: angular.module('Fms').factory('SharedService', function() { var userdetails=false; return userdetails; }) Below controllers utilize this factory: angular.mod ...

What is the best way to inject child nodes into parent nodes without causing the view to shift to the location where the element is being

While I am rendering elements and appending them to a parent div, my screen keeps jumping to the bottom-most element as it loads instead of maintaining the current view. Ideally, it should start at the top of the screen and remain there without any sudden ...

What is the best way to tally the elements of a nested object within a group of objects?

I am working with an array of objects that contain nested arrays of objects, similar to what is shown in Code snippet 1. My goal is to calculate the number of records within the nested array where the parent_user_id matches the id. Based on this criteria, ...

How can I display a PDF in a browser using ASP.NET without allowing the user to copy or download the file?

Is there a way to view a PDF in the browser using ASP.NET without allowing users to copy or download it? Alternatively, how can we disable right-click functionality in a PDF viewer within the browser? ...

The Angular single-spa.js framework is altering the URLs of deep imports to localhost

I am currently utilizing the single-spa library (version 5.8.2) in conjunction with multiple Angular projects. Upon attempting to import ngx-quill (a library that itself imports another library, quill.js), I encountered an issue where the single spa librar ...

When calling a function within a for loop, the function receives the final value instead of iterating through the sequence

I need assistance with setting unique names for objects in an array. I have the following setup: this.array = [{name: null}, {name: null}, {name: null}] Along with a list of reserved names: this.reserved = ["name2", "name3"] My goal is to loop through th ...

Frustratingly Quiet S3 Upload Failures in Live Environment

Having trouble debugging a NextJS API that is functioning in development (via localhost) but encountering silent failures in production. The two console.log statements below are not producing any output, leading me to suspect that the textToSpeech call ma ...

Tips for validating forms using jQuery

Upon form submission, an alert is displayed before redirecting to a new page. I have implemented a function that triggers on button click. The alert will appear first, followed by the form submission. I would appreciate ideas on how to validate the form. ...

Locating a specific element in javascript using its id

I'm struggling to automate the process of downloading a CSV file from a website using Selenium. Specifically, I'm having trouble selecting the format of the file and clicking on export. Does anyone have any ideas on how to accomplish this? To acc ...

Having trouble getting my Leaflet map to display even after meticulously following the quick-start guide

I am experiencing an issue where the map is not displaying at all, leaving a blank space where it should be. Despite following Leaflet's quick-start guide, I have been unable to determine the cause of this problem. Here is the code that I currently h ...

Using AngularJS to send a $http.post request with Paypal integration

This form utilizes the standard PayPal format for making purchases. <form action="https://www.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="cmd" value="_xclick"> <input type="hidden" name="business" value="<a href= ...

After deploying a NextJs app on Github Pages, only the readme file is displayed

After creating a basic e-commerce web app using next js (with nextjs 14), I attempted to deploy it with github pages. Despite following a tutorial on YouTube and trying the gh-page branch and GitHub actions methods, all that would show up when visiting the ...

Is there a way to customize Angular's number filter?

I'm trying to achieve a consistent number format with Angular's number filter, regardless of the localization selected. After inspecting the Angular source code on GitHub, I found the implementation of the filter to be like this: function number ...

Error encountered: ReferenceError when using node.js, express, ejs, bcrypt,

Recently started diving into node.js and encountered an issue when trying to merge code from various projects. Everything was functioning smoothly until I switched the route path from '/dashboard' to '/store' along with the correspondin ...

Opting for Bootstrap modal over Colorbox for a better user experience

Here is a script that uses JavaScript to trigger Colorbox and open specific PHP pages with parameters on the server: $(document).ready(function() { $('#example tbody').on( 'click', 'input', function () { var d ...

`Why should you nest promises in Vuex?`

I've taken over the responsibility of maintaining code written in Vue by my former programmer. While going through his Vuex module, I came across this piece of code. import axios from "axios"; import qs from "qs"; import httpi fro ...