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)
}
}
}
})
#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));
}
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!
Related
I have been trying to find a way to save a message as a variable. After it is saved as variable, I will delete the variable. I am making a page-based command for my bot, where each page has a custom reaction that does a custom action. I decided to make a simple navigator for the first page. In the navigator, you react with an emoji and the bot sends a message telling you to choose a page and wait for your message. When the bot receives your message, I want the bot to delete the message it sent.
My code looks like this.
let qsend = message.channel.send("Choose a page to go to.");// sends the bot's message
// bot receives my message!
qsend.delete() // deletes the bot's message
When I run it, I get the error: UnhandledPromiseRejectionWarning: TypeError: qsend.delete is not a function.
I've tried many different solutions, but still nothing.
Sending a message returns a promise. You need to either await it or use Promise#then()
Using Async/Await
// Inside an async function
// .on('message' async message => ... For example
let qsend = await message.channel.send("Choose a page to go to.");
qsend.delete();
Using Promise#then()
message.channel.send("Choose a page to go to.")
.then(qsend => qsend.delete())
.catch(console.error);
Discord.JS Documentation on Message#delete() and Async/Await
message.channel.send() returns a promise (see here). To delete it shortly after, you should send the message, await the response and delete the returned message after that time.
message.channel.send('Foo bar')
.then(msg => msg.delete())
.catch(/* Error handling if the message isn't sent or returned.*/);
I know you can send a DM like this:
message.author.send("Go to example.com for help");
But some people have the setting that allows other server members to DM them off:
How do I find out if the DM actually sent or not? I know this is possible in the Discord API, since other bots do it.
If the user has that option, or isn't DMable, it will throw an error, namely:
DiscordAPIError: Cannot send messages to this user
Now, we can catch that error and run a command based on it, say replying in the channel that the user can't be DMed.
user.send(...).catch(async err => message.reply("I can't DM this user"));
// In the above, async is useless, but you can actually do what you want with it.
To run more than a single line of command, use a promise based catch.
user.send(...).catch(async err => {
console.log(err);
message.reply("I can't DM this user");
});
If a user has that option enabled, DMing them will return an error, so you'll be able to use a .catch() statement:
user.send().catch(() => console.log('Could not DM this user'));
You can get error notices aswell as information about the error using .catch()
In this example I log the error type and description
member.send(...).catch(error => {
console.error(`${error.name} :\n${error}`)
message.channel.send('There was an error when trying to DM this member')
})
I am coding a discord.js bot and need a command where the first argument is a Message-ID.
Because a fetch() returns a promise, it's not guaranteed that the message will be found (obviously if the ID is wrong), so only if finds the message, it goes into the .then(), if not, I just make .catch(msg.delete())
BUT, I still get a warning in the console UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Message
But if I change the catch block to .catch(console.error) the warnings vanish and I get a object-kinda output. But I dont that this error will be displayed in my console, neither I want those warnings. My bot should just remove the message, because it's the users fault to type an invalid id.
And one question: when exactly does the catch block trigger, if the ID (args[0]) is per se valid (18 chars and only numbers) but still not matching to any message, or if its just anything causing an error in the Promise.
Thanks in advance!
Here is a bit more code:
msg.channel.messages.fetch(args[0])
.then(message => {
console.log("then");
})
.catch(console.log("catch"));
what's really interesting, if my ID is valid, then it says first "catch", and then "then". If its invalid it says "catch" and then comes the warning message
Try .catch((err) => { console.log(err); msg.delete(); });
I have if (!message.guild.me.hasPermission("SEND_MESSAGES")) return; in my code but when I disable the bot's permission to Send Messages it gives me an error, (node:2504) UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions. How could I possibly solve this issue so I won't get the error when my bot cannot send messages into a chat.
Do this before the message event
Try this:
if (message.author.bot) {
return;
} else {
//do soemthing if user is not a bot
}
You could possibly use a try catch block to catch the exception and then just don't print the error.
like :
try{
if (!message.guild.me.hasPermission("SEND_MESSAGES")) return;
}catch{}
It might be because the permission required isn't SEND_MESSAGES.
For example, if you are coding a ban command, you would also need to check if the bot has the BAN_MEMBERS permissions.
If it was an add-role command, you would have to check if the bot highest role is higher than the role it needs to assign.
So I was developing Discord Bot for my customer and he wanted from me to make a bot that could send an events in his members DMs. I've made the code. Bot executes the function and does send DM to all the members. However, bot stops due an error "Cannot read property 'first' of null".
I tried a lot of things, such as catching console errors etc. But I still do not understand why does my bot stops and writes that console error after me adding that DM code. Console recognize some kind of problem at a line of code that has no actual connections with the Private Message command. It is not even under the same 'bot.on' ... Here is the problem:
if (msg.guild && msg.content.startsWith('!private')) {
let text = msg.content.slice('!private'.length);
msg.guild.members.forEach(member => {
if (member.id != bot.user.id && !member.user.bot) member.send(text).catch(err => {
message.reply('I was unable to kick the member');
console.log(err);
});
})
}
});
**//This right here is a code that can execute the function i wanted to make.^**
bot.on('message', message=> {
const member = message.mentions.members.first(); // <-- **Console says this property'first' cannot be read (Cannot read property 'first' of null)**
let args = message.content.substring(PREFIX.length).split(" ");
const user = message.mentions.users.first();
switch(args[0]) {
case 'ping':
message.channel.sendMessage('pong!');
break;
//**Above is a part of the code that has a console error after I added the first code above. Before I added first code there was no such errors and everything worked perfectly.**
I expected Bot to execute function and send everyone in the server private message (Event) and continue working.
But instead it executes the function sending everyone desired message but the bot stops as it has an console error.