I am trying to implement a discord chatbot into my own bot, isn't good at handling some characters and stuff like the quotes of discord (type > and space to know that I mean). It often crashes becauses it thinks the message is empty. I wanted to use a try catch phrase so it won't crash. The complete function is asyncronous and I think that's why it isn't working how I want it to do. It still crashes without logging the thrown error.
client.on("message", async message => {
if(message.channel.id === "1006483461747527772" && !message.author.bot){
if(containsLetters(message.content)) {
//console.log(message.content.length)
try{
let reply = await chat.chat(message.content)
client.channels.cache.get("1006483461747527772").send(reply)
} catch(err){
client.channels.cache.get("1006483461747527772").send(err)
}
}
}
})
CodePudding user response:
I think the problem that you are running into here is that the object err
is not a String. Try appending .message
to err
so then it reads err.message
. If that doesn't work (or even if it does), I would recommend against sending the error message in discord since that presents more variables to interfere with debugging (what if something was wrong with the client object or with the channel id string?). Instead, I normally use console.error(err)
. Hope this helps!
CodePudding user response:
@Robotgozoooom's answer is correct that to send an error message to Discord you need to use error.message
, but there's another problem: when Discord throws the Cannot send empty message
error it is in an async function, so the try/catch doesn't actually catch the error. You need to add a .catch()
function to the end of your async function instead of using a try/catch at all:
if (containsLetters(message.content)) {
let reply = await chat.chat(message.content);
let channel = client.channels.cache.get("1006483461747527772");
channel.send(reply).catch((err) => channel.send(err.message));
}