How can one ensure that Discord waits for a script to complete running, and how can you prevent Discord from responding until all necessary data has been obtained?

I recently started working with node.js and asynchronous programming, and I'm facing a challenge that has me puzzled. My goal is to create a Discord bot that fetches data from a third-party website. While I can successfully retrieve the data and see it in my console, I'm struggling to display it on Discord.

const { SlashCommandBuilder } = require('@discordjs/builders');
const execFile = require('child_process').execFile;
const path = require('node:path');
const commandsPath = path.join(__dirname, '..', 'Folder_name');
let scriptPath = path.join(commandsPath, 'querydata.js');
let output = "";

module.exports = {
    data: new SlashCommandBuilder()
        .setName('cmdname')
        .setDescription('blank'),
    async execute(interaction) {
        await runScript(scriptPath)
        await interaction.reply(output)
    },
};

function runScript(scriptPath) {
    return new Promise((resolve, reject) => {
        execFile('node', [scriptPath], (error, stdout, stderr) => {
            if (error) {
                console.error('stderr', stderr);
                throw error;
            }
            console.log(stdout);
            output = stdout
            resolve(output)
        });
    });
}

Despite trying solutions like Promises and async/await, I keep encountering errors. For instance, when using the code snippet above, I receive the following error message:

RangeError [MESSAGE_CONTENT_TYPE]: Message content must be a non-empty string.

Alternatively, switching to the code below leads to a different issue where Discord terminates the call before the data is displayed, assuming my bot is unresponsive (even though it's online). enter image description here

module.exports = {
    data: new SlashCommandBuilder()
        .setName('cmd')
        .setDescription('blank'),
    async execute(interaction) {
        runScript(scriptPath)
            .then(interaction.reply(output))
    },
};

function runScript(scriptPath) {
    return new Promise((resolve, reject) => {
        execFile('node', [scriptPath], (error, stdout, stderr) => {
            if (error) {
                console.error('stderr', stderr);
                throw error;
            }
            console.log(stdout);
            output = stdout
            resolve(output)
        });
    });
}

I'm confused because I expected the use of 'await' to ensure that Discord receives the data only after the runScript function completes. However, instead of waiting for the process to finish, the script attempts to send an empty output string to Discord, triggering the RangeError. Meanwhile, employing the second code block results in the error shown in the screenshot within Discord.

Answer №1

Here's a solution that should suit your needs!

async processRequest(interaction) {
  await executeScript(scriptPath)
    .then(result => interaction.respond(result))
}

This function will use the await keyword to pause execution until the script has completed its tasks, then it will retrieve the output and send it as a response.

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

Accessing User Input Data with JQuery

Can someone help me figure out how to store the input value from a Materialize select form in HTML using a variable in javascript/jquery? Here is the HTML code for the form: <div class="input-field col s12"> <select> <option va ...

Data modifications in polymer are not being accurately displayed

I need help with hiding/unhiding a UI element using a button in Polymer. Despite having the necessary elements and code set up, it is not working as expected: <button id="runPredictionButton"> <i>Button text</i> </button> <p ...

Develop an interactive AngularJS application with a dynamic Bootstrap table feature

I'm in the process of transitioning my existing jQuery code to AngularJS. One part of the code involves creating a dynamic Bootstrap table based on JSON data retrieved from a Spring REST service. The snippet below shows the jQuery code used to create ...

Using Promise.all within an async function to handle variables inside of Lambda functions

I've spent the past couple of days trying to find a solution to this issue. I've simplified my code to mostly pseudo code for ease of understanding. What I'm struggling with is creating an async function that acts as a trigger for an SQS qu ...

Tips for showcasing all values in a nested array

In my Vue application, I am dealing with a nested array where users can select one date and multiple times which are saved as one object. The challenge I am facing now is how to display the selected date as a header (which works fine) and then list all the ...

Exploring the use of data attributes in jQuery to access JSON objects

I have set a data-attribute for multiple elements and I am looking to access the JSON object using this data attribute in jQuery. <div class="content"> <div class="plans" data-plan="state-1"><span class="pricing-symbol">$</span> ...

Sending the .pom file to Bintray using the Node package

I've encountered a peculiar problem while trying to upload a .pom file using the node-bintray package - it consistently results in a 400 error. All other files upload without any issues, and I haven't been able to find any documentation that she ...

What is the process for generating a new object by outputting key-value pairs?

I have an array that I'm trying to use to create a new object with specific keys and values. const arr = [ { name: 'ab', key: '584577', }, { name: 'cd', key: '344926', }, { name: &a ...

Issue with Angular controller not refreshingalternatively:Angular

I just started reading an AngularJS book by O'Reilly and I encountered a problem with the first example. Instead of seeing "hello" as expected in place of "{{greeting.text}}", it displays exactly that. I have double-checked my angular linking and even ...

Issue with rendering partials in ExpressHandlebars in NodeJS

I am currently facing an issue while working with express-handlebars. I am attempting to use partials, but I keep encountering the following error message: The partial header could not be found. In my app.js file, the code appears as follows: var expr ...

Ensure that the user remains within the current div when they click the submit button, even if the textbox is

For the past 48 hours, I've been grappling with an issue on my HTML page that features four divs. Each div contains three input fields and a button. The problem arises when a user leaves a text box empty upon submitting - instead of staying in the sam ...

Unusual behavior: Jest throws a `Cannot find module` error when attempting to import components using absolute paths

Configuration of my jest: clearMocks: true, rootDir: '../../', cacheDirectory: 'cache', testEnvironment: 'jsdom', modulePaths: [ '<rootDir>' ], setupFilesAfterEnv: [ '<rootDir>/ ...

Combine an array of arrays with its elements reversed within the same array

I am working with an array of numbers that is structured like this: const arrayOfArrays: number[][] = [[1, 2], [1, 3]]; The desired outcome is to have [[1, 2], [2, 1], [1, 3], [3, 1]]. I found a solution using the following approach: // initialize an e ...

Troubleshooting the error "The 'listener' argument must be a function" in Node.js HTTP applications

I'm facing an issue resolving this error in my code. It works perfectly fine on my local environment, but once it reaches the 'http.get' call, it keeps throwing the error: "listener argument must be a function." Both Nodejs versions are iden ...

When the user clicks, the template data should be displayed on the current page

I need help with rendering data from a template on the same HTML page. I want to hide the data when the back button is clicked and show it when the view button is clicked. Here is my code: <h2>Saved Deals</h2> <p>This includes deals wh ...

What is the best way to transform a JS const into TSX within a Next.js application?

Exploring the code in a captivating project on GitHub has been quite an adventure. The project, located at https://github.com/MaximeHeckel/linear-vaporwave-react-three-fiber, showcases a 3D next.js application that enables 3D rendering and animation of mes ...

Transforming a string representation of a nested array into an actual nested array with the help of JavaScript

My database stores a nested array as a string, which is then returned as a string when fetched. I am facing the challenge of converting this string back into a nested array. Despite attempting to use JSON.parse for this purpose, I encountered the following ...

Using the class attribute for Pagedown instead of the id keyword

I am utilizing Pagedown, which necessitates giving the id wmd-input to a textarea. This requirement is outlined in Markdown.Editor.js as follows: function PanelCollection(postfix) { this.buttonBar = doc.getElementById("wmd-button-bar" + postfix); ...

Ways to determine whether a DOM textnode is a hyperlink

Is there a more foolproof method for determining if a DOM textnode represents a hyperlink? The code snippet below currently only checks if the node is directly enclosed in an anchor tag, which may not be sufficient if the <a> element is higher up i ...

JavaScript comparing elements within an array

I need help extracting all the names from an array with URLs containing '/blekinge' and presenting them in a list. Here's what I have so far: const allLocations = locations.map((location) => <li>{location.url}</li> ) I&a ...