"My discord.js bot seems to be sending multiple GIFs in one go instead of just one. Any ideas on how to

Can anyone assist me with a Discord bot command issue? I'm trying to make a command that sends a random Kirby gif using the Giphy API, but it keeps sending multiple gifs instead of just one. Here is the code snippet:

client.on('message', message => {
    if (message.content === 'k!gif')

    giphy.search('gifs', {"q": "kirby"})
    .then((response) => {
        var totalResponses = response.data.length
        var responseIndex = Math.floor((Math.random() * 10) + 1) % totalResponses;
        var responseFinal = response.data[responseIndex]

        message.channel.send("We stan kirby gifs", {
            files: [responseFinal.images.fixed_height.url]
        })
    }).catch(() => {
        message.channel.send('Kirby has run into a roadblock and was unable to complete his task.');
    })

})

Your help is greatly appreciated!

Answer №1

It has been pointed out by @Giuiopime that a requirement for the command is missing. As a result, each time a message is sent, the current code is triggered and a gif is sent. This cycle repeats continuously as new messages are received by the bot.

To address this issue, ensure to enclose the current code within an if statement and validate that the player is not a bot. While untested, the following code may resolve the issue:

client.on('message', message => {
  if(message.author.bot) return;
  if (message.content === 'k!gif'){
    giphy.search('gifs', {"q": "kirby"}).then((response) => {
      
        var totalResponses = response.data.length
        var responseIndex = Math.floor((Math.random() * 10) + 1) % totalResponses;
        var responseFinal = response.data[responseIndex]

        message.channel.send("We stan kirby gifs", {
            files: [responseFinal.images.fixed_height.url]
        })
    }).catch(() => {
        message.channel.send('Kirby has run into a roadblock and was unable to complete his task.');
    })
  }
})

Answer №2

The proper way to use the code if (message.content === 'k!gif') would be to ensure that you include all your code within the curly braces of the if statement.

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

The strange behavior of !important, display:none, and .height()

While working with a piece of JS code yesterday, I stumbled upon something peculiar. There was a div element that was initially hidden using display:none, and I was utilizing its height in some JavaScript calculations. Everything was functioning properly u ...

What causes performance issues when utilizing mouseover events in JQuery?

var mouseX; var mouseY; $(document).mousemove( function(e) { mouseX = e.pageX; mouseY = e.pageY; }); $(".test").mouseover(function(){ $('#DivToShow').css({'top':mouseY,'left':mouseX, 'display':'block&ap ...

JavaScript basic calculator app failed to generate an error as anticipated

For my homework assignment, I am developing a basic calculator application using JavaScript. My main task is to ensure that the input numbers are limited to only two and that they are valid numbers; otherwise, an error should be thrown. Initially, concern ...

Is there a hover function in jQuery that works with both mouseenter and mouseout events?

I've been facing a slight issue with a list of items using the <li> element. I have a plugin running that dynamically adds a data-tag ID to the data-* attribute of these items. As a result, all items are dynamically added and another function I ...

Can the value returned by .resolve() be accessed outside of the .then() block?

Currently, I am utilizing Node.js along with the q library. My code snippet appears as follows: checkIfThingExists(function(idForAThing){ if(idForAThing){ updateThingData(idForAThing); } else { createThing(function(idForAThing){ updateT ...

Error Message "Alexa.create is not a valid function" encountered while using the Alexa HTML Web API on the Echo Show 10

Here is the HTML code for my custom Alexa Skill. <head> <script src="https://cdn.myalexaskills.com/latest/alexa-html.js"> </script> </head> <body> var alexaClient; Alexa.create({version: '1.0'}) .t ...

Ways to attach the close event to the jquery script

Hello, I'm having trouble reloading the parent page when the close button is clicked on a modal dialog. Here's my code snippet: //customer edit start $( ".modal-customeredit" ).click(function() { var myGroupId = $(this).attr('data- ...

FancyBox: Struggling to adjust dimensions accurately

Currently using Fancybox 1.2.6 in conjunction with JQuery 1.2.6, Sample Code: <script type="text/javascript> $(document).ready(function() { $("a.iframe").fancybox({ 'width' : 300, 'hei ...

Exploring the world of AngularJS, repeating fields and handling special characters

I am looking to showcase the batters and their statistics from a JSON file for my team in a table using AngularJS. HTML: <table class="table" ng-controller="players"> <tr ng-repeat="x in player | orderBy:orderByField:reverseSort"> ...

Creating a sequence of dependent HTTP requests in Angular

Is it possible to execute multiple http get requests sequentially in Angular, where the endpoint URL for the second request depends on the response of the first request? I attempted to nest the requests using the following code snippet: this.http.get(end ...

Disabling data-scroll-speed on mobile devices

As a beginner in JavaScript/jQuery, I am working on incorporating code that changes the scrolling speed of specific elements on my webpage. However, I am struggling to disable this code for smaller screen widths. Here is the code snippet I have so far: &l ...

A Step-by-Step Guide to Retrieving the Route of a Controller Function in Express

When working with Express.js, it is possible to retrieve the names of all controllers from an app. However, these names are usually in an unfamiliar format (such as handle: [AsyncFunction: login]). I have been unable to figure out how to destructure this i ...

Is there a way to send an AJAX request to an MVC action from a JavaScript file?

In a file named job.js, there is code that works perfectly when run on localhost but results in a 404 error when run on an intranet server with an application name. Job.updateJob = function () { $.post('/Builder/ListJobItems', function (dat ...

Utilizing IonicSafeString for Alert Box Messages in Event Handling

.ts private async displayTermsOfServiceAlert(): Promise<void> { const alert = await this.alertController.create({ header: 'Updated Terms of Service', //problem lies here message: new IonicSafeString(`<ion-button i ...

The act of exporting a chart results in a RangeError being thrown: Maximum Call Stack Size Exceeded within the highcharts-more

I am encountering an issue with one of my packedbubble charts throwing a RangeError in the title when attempting to export the graph, while the others work fine. The chart builder remains the same for all graphs; only the data and title text are appended t ...

Using Nextjs Image as the Background for Layout

I have a question regarding implementing a common background image for all pages in my app. Currently, I have the main page.js code that displays an image as the background using Next Image component. However, I would like this background to be present thr ...

The map function appears to be malfunctioning or there may be an issue with the retrieved data

Encountering an error message that says "Cannot read properties of undefined (reading 'map')" while attempting to render a list. Below is the code snippet, seeking assistance. import React, { Component } from 'react' // import axios fro ...

Include backing for the trial syntax 'classProperties' within an npm module

I am facing a challenge while trying to publish an npm package containing some functions for my create-react-app project. The functions work fine when I import them from the js file within the create-react-app project, but I encounter an error once I insta ...

Methods for setting the value of a scope variable within a controller's function

I have a goal of presenting a page that calculates a balance in the background and displays it. To achieve this, I decided to separate the balance into its own directive. Here is the directive I have created: app.directive('smBalanceInfo', fun ...

The tags are showing unexpected strings after the v-for directive

Currently, I am in the process of designing a new web page using Vue on Nuxt to replace the existing one (using VScode). However, I have encountered an issue while utilizing v-for to generate lists. Within the tag, there is an unknown string(attribute) tha ...