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.