Check if a message has been deleted in discordjs - javascript

I have a bot in discordjs and I'm trying to check if the interaction.reply message has been deleted or not to avoid "Unknown Message" Errors

using a try-catch you can catch the error if the message was deleted
try {
const message = await interaction.reply('message');
console.log('Message not deleted');
} catch (error) {
console.error('Message deleted');
}

Related

Node.js - Discord.js v14 - fetching a channel returns undefined / does not work

Attempting to define channel with this code will return undefined.
const { Events, InteractionType, Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
],
})
module.exports = {
name: Events.InteractionCreate,
async execute(interaction) {
if(interaction.type == InteractionType.ApplicationCommand){
const command = interaction.client.commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(`Error executing ${interaction.commandName}`);
console.error(error);
}
}
else if(interaction.isAutocomplete()){
const command = interaction.client.commands.get(interaction.commandName);
if(!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try{
await command.autocomplete(interaction);
} catch(error) {
console.error(error);
}
}
else if(interaction.isButton()){
console.log(client.channels);
const channel = await client.channels.fetch('1074044721535656016 ');
console.log(client.channels);
console.log(channel);
}
},
};
const channel = await client.channels.fetch('1074044721535656016 '); Is the main line here.
At the bottom and top of the code is where the important stuff for this question is. I believe I am not properly using the fetch method.
As evidenced by console.log(client.channels); I'm trying to look at the channels cache, but for some reason the channel isn't there, hence I'm using fetch() instead of cache.get().
Thank you for the help!
Other info:
Running npm list shows:
discord.js#14.7.1, dotenv#16.0.3
Node.js v19.6.0
How I got my channel id
Error Message:
ChannelManager {} //<--- this is from the first console.log
node:events:491
throw er; // Unhandled 'error' event
^
Error: Expected token to be set for this request, but none was present
Is the problem because the channel is undefined or because it hasn't resolved yet?
Check your channel ID it may be formatted like:
guild id / channel id
Use interaction.client instead of making a new client object. The interaction already has its own client object with the related properties.

Trouble handling all errors in Telegraf js (TelegramError: 400: Bad Request: message to delete not found)

I have a button in a telegraf telegram bot that call this action
bot.action("clear", async ctx => {
let id = (await bot.telegram.sendMessage(ctx.chat.id, "Clearing console")).message_id;
console.log(id);
for(let i = 0; i <= 100; i++ ){
try {
ctx.deleteMessage(id - i);
} catch (error) {
console.log(error);
break;
}
}
});
But when I click the button that calls the action above, I have this error and Nodemon crashes :
TelegramError: 400: Bad Request: message to delete not found
I already have these lines
const bot: Telegraf<Context> = new Telegraf(token);
bot.catch(err => {
console.log("Ooops, encountered an error", err);
});
How can I fix this ? Thanks

How do I check if a user has their DM's open? | discord.js v 14

I am making a bot that can dm a user. If the dm's of the user are off it says the message is successfully sent but in the console it returns an error.
So, what can I do to check if a user's dm is open?
The code I'm trying to run:
const rec = interaction.options.getUser('user')
const user = interaction.user.id
try {
rec.send({ embeds:[ new EmbedBuilder().setDescription(`<#${user}> says to you: ${message} `).setColor("#f05c51")
.then(interaction.reply(({ content: 'Successfully sent', ephemeral: true })))
] })
} catch (error) {
interaction.reply(({ content: `Could not send message, maybe dm's off? -> ${error}`, ephemeral: true }))
}
You can't. You need to use .catch()
rec.send({ embeds: [YOUREMBED] })
.then(message => console.log(`Sent message: ${message.content}`))
.catch(console.error);
I used unhandledRejection to know if my bot can't send a message to a specific user, also can use it all of unhandledRejection errors
process.on('unhandledRejection', async(error) => {
const admin = client.channels.cache.get('-----')
const embed = new MessageEmbed()
.setDescription(`\`\`\`\j\s\n${error.message || error.name || error }\n\`\`\``)
.setColor('RANDOM')
.setTimestamp()
admin.send({embeds: [embed]})
console.log(error)
});
You can also try it on your code.

Discord.js UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send an empty message

Ok, so I just started working on a discord bot and implemented a command handler, and I immediately ran into some problems.
const Discord = require("discord.js");
module.exports = {
name: "kick",
description: "Kicks the mentioned user",
execute(message, args) {
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
try {
const kickEmbed = new Discord.RichEmbed()
.setTitle("You were Kicked")
.setDescription("You were kicked from Bot Testing Server.");
user.send({ kickEmbed }).then(() => {
member.kick();
});
} catch (err) {
console.log("failed to kick user");
}
}
}
};
when i execute the kick command in my server, I get the following error
UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send an empty message
I can't seem to find anything wrong with the code so, where's the error
When sending an embed that uses the Discord Rich Embed builder you don't need to use the curly brackets.
Instead of user.send({ kickEmbed }) you should do user.send(kickEmbed). I ran into that issue before and it helped in my case.

Fetch bot messages from bots Discord.js

I am trying to make a bot that fetches previous bot messages in the channel and then deletes them. I have this code currently that deletes all messages in the channel when !clearMessages is entered:
if (message.channel.type == 'text') {
message.channel.fetchMessages().then(messages => {
message.channel.bulkDelete(messages);
messagesDeleted = messages.array().length; // number of messages deleted
// Logging the number of messages deleted on both the channel and console.
message.channel.send("Deletion of messages successful. Total messages deleted: "+messagesDeleted);
console.log('Deletion of messages successful. Total messages deleted: '+messagesDeleted)
}).catch(err => {
console.log('Error while doing Bulk Delete');
console.log(err);
});
}
I would like the bot to only fetch messages from all bot messages in that channel, and then delete those messages.
How would I do this?
Each Message has an author property that represents a User. Each User has a bot property that indicates if the user is a bot.
Using that information, we can filter out messages that are not bot messages with messages.filter(msg => msg.author.bot):
if (message.channel.type == 'text') {
message.channel.fetchMessages().then(messages => {
const botMessages = messages.filter(msg => msg.author.bot);
message.channel.bulkDelete(botMessages);
messagesDeleted = botMessages.array().length; // number of messages deleted
// Logging the number of messages deleted on both the channel and console.
message.channel.send("Deletion of messages successful. Total messages deleted: " + messagesDeleted);
console.log('Deletion of messages successful. Total messages deleted: ' + messagesDeleted)
}).catch(err => {
console.log('Error while doing Bulk Delete');
console.log(err);
});
}

Categories