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

时间:2019-05-27 20:15:52

标签: javascript node.js discord.js

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

我已经尝试过在命令文件的index.js文件中运行的函数中使用message变量,但是当它运行时,它说未定义'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));
}

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

2 个答案:

答案 0 :(得分:0)

好吧,首先,您的'}'出现了问题(最后不应该有一个问题)

然后是一个简单的示例:

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

答案 1 :(得分:0)

您可以访问该消息,因为http.request中的消息未正确关闭。确保运行lint并修饰代码,以轻松发现代码中多余或未关闭的部分。

要回复用户,您只需执行以下操作:

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并将其导入。但是,由于您没有对其进行任何特定的操作,因此我看不出有任何特殊的理由拥有通用的理由。

相关问题