当用户在我的 Discord 机器人上触发错误时,我如何向用户回复消息?

How do I respond with a message to a user when they trigger an error on my Discord bot?

我正在尝试让我的 Discord 机器人回复用户,让他们知道如果在他们 运行 一个命令时发生了错误。我不确定我应该如何从命令的索引文件中的命令消息中获取我的消息变量。

我已经尝试在来自命令文件的 index.js 文件中 运行ning 的函数中使用消息变量,但是当它 运行s 时它说'message' 未定义。我怀疑它可能是我放置 .catch() 的地方。这是我正在使用的代码。

//This is the area in my index that handles errors
bot.on('error', (err, message) => {
  console.error();
  message.reply("error here, possibly a rich presence");
});

//Heres the function with the .catch()
http.request(options, function(res) {
    var body = '';

    res.on('data', function (chunk) {
        body+= chunk;
    });

    res.on('end', function() {
       var jsondata = JSON.parse(body);
       var converteddate = new Date(jsondata.toTimestamp*1000)
       console.log(converteddate)
       var hours = converteddate.getHours();
       var minutes = "0" + converteddate.getMinutes();
       var finishedtime = hours + ':' + minutes.substr(-2);
        message.reply(finishedtime + " EST.")
})
}).end()
.catch(err => bot.emit('error', err, message));
}

此命令的预期输出是 运行 命令,如果有任何错误,请通知用户。感谢您的帮助!

好的,首先你的'}'有问题(最后一个不应该在这里)

然后,一个简单的例子如何捕捉:

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function error() {
  await sleep(3000); // wait 5 sec for the sake of the example
  throw 'I have a problem';
}
console.log('starting')
error().catch((err) => console.log('The error:',err))

我不确定 .end() 是什么,但我认为你不需要它

所以在这里,你想做的是:

http.request(options, function(){
    // do something
    return 'text message'; // what you want to reply
}).catch((err) => err).then((msg) => message.reply(msg))

您可以访问该消息,因为 http.request 未正确关闭。确保您 运行 是 linter 和 bveautify 您的代码以轻松发现代码中的额外或未关闭的部分。

至于回复用户你可以简单地做:

message.author.send("There was an error: "+err);

我会尝试这样的事情:

http.request(options, (res) => {
    let body = '';
    res.on('data', (chunk) => {
        body+= chunk;
    });
    res.on('end', () => {
       const jsondata = JSON.parse(body);
       const converteddate = new Date(jsondata.toTimestamp*1000)
       console.log(converteddate)
       const hours = converteddate.getHours();
       const minutes = "0" + converteddate.getMinutes();
       const finishedtime = hours + ':' + minutes.substr(-2);
        message.reply(finishedtime + " EST.")
    })
}).catch(err => message.author.send("There was an error: "+err.toString()));

如果您想采用更全局的方法,我会创建一个 errorHandler 并将其导入。但是,我看不出有任何特别的理由需要一个通用的,因为您没有对它执行任何特定的操作。