如何让discord等待脚本完成运行,以及如何在获得所需数据之前不回复discord ?



我是node.js和异步编程的新手,所以我对为什么会发生这种情况有点困惑。我正试图运行一个不和谐的机器人,这将给我从第三方网站的数据。我能够从第三方网站查询数据,我可以看到我的控制台上的数据。然而,数据不能够显示在不一致。

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)
});
});
}

我已经尝试使用Promise, async/await,但我要么看到这个错误

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

将我的代码更改为下面的代码,我会得到这个错误,在那里我能够查询数据,但当我得到数据不和谐将终止呼叫,认为我的机器人没有响应。(当我测试这个时,机器人是在线的)在这里输入图像描述

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)
});
});
}

我不明白,我想如果我使用await,那么脚本会等到runScript函数完成后才回复不和谐。但是脚本一直尝试将空输出字符串发送到不协调,从而导致RangeError错误。另一方面,当我使用第二个代码块时,我得到了Discord中的错误(在pic中看到的错误)。

这应该可以工作!

async execute(interaction) {
await runScript(scriptPath)
.then(output => interaction.reply(output))
}

它将await脚本,字面意思是等待它完成它的承诺,然后将从中获取输出并回复它。

最新更新