Problem with onMessageDelete

Hello Guys, Im facing a really weird problem. I have this 1. code where i have a normal message loggin what is working:
@On({ event: "messageDelete" })
async onMessageDelete(
[deletedMessage]: [Message | PartialMessage],
client: Client
) {
try {
const guildId = deletedMessage.guild?.id;
if (!guildId) return;

const configRepo = database.getRepository(ServerBotConfig);
const config = await configRepo.findOne({ where: { guildId } });

const { logChannel } = await this.getMessageLogChannel(client, guildId);
if (!logChannel) {
console.error("Message delete log channel not configured or not found");
return;
}

const userMention = `<@${deletedMessage.author?.id ?? "Unknown"}>`;
const content =
deletedMessage.content && deletedMessage.content.trim().length > 0 ?
deletedMessage.content
: "*Error: Message not found.*";

const embed = new EmbedBuilder()
.setColor(parseEmbedColor(config?.embedColor))
.setAuthor({
name: "Lizard - Message Logging",
iconURL: client.user?.avatarURL() ?? undefined,
})
.setThumbnail(deletedMessage.author?.avatarURL({ size: 128 }) || null)
.addFields(
{
name: "Member",
value: `${userMention} | ID: **${deletedMessage.author?.id}**`,
},
{
name: "Channel",
value: `<#${deletedMessage.channel?.id ?? "Unknown"}>`,
},
{ name: "Message", value: `**${content}**` }
)
.setTimestamp()
.setFooter({
text: "Lizard - Message Logging",
iconURL: client.user?.avatarURL() ?? undefined,
});

await logChannel.send({ embeds: [embed] });
} catch (error) {
console.error("Error in onMessageDelete:", error);
}
}
}
@On({ event: "messageDelete" })
async onMessageDelete(
[deletedMessage]: [Message | PartialMessage],
client: Client
) {
try {
const guildId = deletedMessage.guild?.id;
if (!guildId) return;

const configRepo = database.getRepository(ServerBotConfig);
const config = await configRepo.findOne({ where: { guildId } });

const { logChannel } = await this.getMessageLogChannel(client, guildId);
if (!logChannel) {
console.error("Message delete log channel not configured or not found");
return;
}

const userMention = `<@${deletedMessage.author?.id ?? "Unknown"}>`;
const content =
deletedMessage.content && deletedMessage.content.trim().length > 0 ?
deletedMessage.content
: "*Error: Message not found.*";

const embed = new EmbedBuilder()
.setColor(parseEmbedColor(config?.embedColor))
.setAuthor({
name: "Lizard - Message Logging",
iconURL: client.user?.avatarURL() ?? undefined,
})
.setThumbnail(deletedMessage.author?.avatarURL({ size: 128 }) || null)
.addFields(
{
name: "Member",
value: `${userMention} | ID: **${deletedMessage.author?.id}**`,
},
{
name: "Channel",
value: `<#${deletedMessage.channel?.id ?? "Unknown"}>`,
},
{ name: "Message", value: `**${content}**` }
)
.setTimestamp()
.setFooter({
text: "Lizard - Message Logging",
iconURL: client.user?.avatarURL() ?? undefined,
});

await logChannel.send({ embeds: [embed] });
} catch (error) {
console.error("Error in onMessageDelete:", error);
}
}
}
82 Replies
d.js toolkit
d.js toolkitβ€’6mo ago
- What's your exact discord.js npm list discord.js and node node -v version? - Not a discord.js issue? Check out #other-js-ts. - Consider reading #how-to-get-help to improve your question! - Explain what exactly your issue is. - Post the full error stack trace, not just the top part! - Show your code! - Issue solved? Press the button!
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
discord.js@14.19.3 v20.14.0
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
Yea i dont have nitro, i need to split the msgs cuz of the length
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
d.js docs
d.js docsβ€’6mo ago
To share long code snippets, use a service like gist, sourcebin, pastebin, or similar instead of posting them as large code blocks or files.
cRiZZly
cRiZZlyOPβ€’6mo ago
Writing it right now
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
I have a ticket panel creation command that creates a ticket panel and saves the channel ID, message ID, and other related data to the database. Additionally, I have a second event handler that listens for deleted messages: if the message ID of a ticket panel is deleted, it removes the corresponding entry from the database. However, if I create a panel, then restart the Discord bot, and afterwards delete the panel's message ID, the entry is not removed from the database. Code:
@On({ event: "messageDelete" })
async onMessageDelete(
[deletedMessage]: [Message | PartialMessage],
client: Client
) {
try {
const guildId = deletedMessage.guild?.id;
if (!guildId) return;

const configRepo = database.getRepository(ServerBotConfig);
const config = await configRepo.findOne({ where: { guildId } });
if (!config) return;

const ticketPlugin = config.pluginConfigs?.ticketPlugin;
const panels = ticketPlugin?.panels;
if (!panels || panels.length === 0) return;

const messageId = deletedMessage.id;
console.log(`messageDelete event for messageId: ${messageId}`);

const updatedPanels = panels.filter(
(panel) => panel.panelMessageId !== messageId
);

if (updatedPanels.length === panels.length) {
console.log("No matching panel found, no action taken.");
return;
}

if (updatedPanels.length === 0) {
console.log(
"No panels remaining, deleting ticketPlugin configuration."
);
delete config.pluginConfigs!.ticketPlugin;
} else {
config.pluginConfigs!.ticketPlugin!.panels = updatedPanels;
}

await configRepo.save(config);
console.log(
`Deleted panel with messageId ${messageId} for guild ${guildId}.`
);
} catch (error) {
console.error("Error in onMessageDelete:", error);
}
}
}
@On({ event: "messageDelete" })
async onMessageDelete(
[deletedMessage]: [Message | PartialMessage],
client: Client
) {
try {
const guildId = deletedMessage.guild?.id;
if (!guildId) return;

const configRepo = database.getRepository(ServerBotConfig);
const config = await configRepo.findOne({ where: { guildId } });
if (!config) return;

const ticketPlugin = config.pluginConfigs?.ticketPlugin;
const panels = ticketPlugin?.panels;
if (!panels || panels.length === 0) return;

const messageId = deletedMessage.id;
console.log(`messageDelete event for messageId: ${messageId}`);

const updatedPanels = panels.filter(
(panel) => panel.panelMessageId !== messageId
);

if (updatedPanels.length === panels.length) {
console.log("No matching panel found, no action taken.");
return;
}

if (updatedPanels.length === 0) {
console.log(
"No panels remaining, deleting ticketPlugin configuration."
);
delete config.pluginConfigs!.ticketPlugin;
} else {
config.pluginConfigs!.ticketPlugin!.panels = updatedPanels;
}

await configRepo.save(config);
console.log(
`Deleted panel with messageId ${messageId} for guild ${guildId}.`
);
} catch (error) {
console.error("Error in onMessageDelete:", error);
}
}
}
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
No?
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
Also Look:
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
its a discordjs issue afaik cuz that makes no sense its on my db cuz: if i create a ticket panel, -> data will be saved to the db, then delete the messageId of the panel -> the panel gets deleted out of the db but when i restart the bot after i created the panel and want to delete the message with the same messageId of a panel, nothing happens I cant understand why
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
Lemme show you everything
d.js docs
d.js docsβ€’6mo ago
To share long code snippets, use a service like gist, sourcebin, pastebin, or similar instead of posting them as large code blocks or files.
cRiZZly
cRiZZlyOPβ€’6mo ago
This embed is my "panel"
No description
cRiZZly
cRiZZlyOPβ€’6mo ago
and after creating the embed aka panel for my ticket system
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
No description
cRiZZly
cRiZZlyOPβ€’6mo ago
look it will be save everything good until and when the bot runtime is still the same like if i did not restart the bot when i delete now the panel aka the panelMessageId -> the entry from the array will be deleted but when i create a panel, stop the bot, start the bot and delete a panel, the panel entry in the db is not deleted thats my issue and i dont save anything in the memory cuz its all in the db and i even asked a other dev friend who dont even know it either
cRiZZly
cRiZZlyOPβ€’6mo ago
(bot still on) -> success
No description
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
it is its only working when the bot is still on thats my issue but if i restart it and delete a msg its not triggered
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
example if the bot crashed that will be a public bot example one day but i still wanna know why that thing is not working with the event also messageDelete when the bot restarts
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
no im waiting i got logs when the bot is ready etc and im waiting enough
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
enough that in this time other cmds are working you know
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
i even waited minutes and if other cmds are working etc why should not work the event handler
βœ… Lizard: Database initialized & synchronized. 🦎 Lizard: Modules imported successfully. 🦎 Lizard: Bot Ready: (πŸ’Ž Single/Unsharded)
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
also How does the Event handle the messages? Cuz if i write messages, and restart the bot after -> the messages are not getting deleted aka logged with my other event handler
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
only the messages getting logged when the bot is started and all after
cRiZZly
cRiZZlyOPβ€’6mo ago
No description
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
IntentsBitField.Flags.Guilds, IntentsBitField.Flags.GuildModeration, IntentsBitField.Flags.GuildPresences, IntentsBitField.Flags.GuildMembers, IntentsBitField.Flags.AutoModerationExecution, IntentsBitField.Flags.GuildMessages, IntentsBitField.Flags.GuildMessageReactions, IntentsBitField.Flags.GuildVoiceStates, IntentsBitField.Flags.MessageContent,
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
dont think so im not the best exp developer, what are partials exactly?
d.js docs
d.js docsβ€’6mo ago
:guide: Popular Topics: Partial Structures read more
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
yea the event handler are working but only for new messages after the login of the bot and thats why i cant delete the panel message id aka the code execution for the entry remove on the d
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
u see
cRiZZly
cRiZZlyOPβ€’6mo ago
No description
cRiZZly
cRiZZlyOPβ€’6mo ago
bot on i write message delete it
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
mb xd
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
okay so is it from my site a issue? i dont think so im using everything normal.
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
its the same yea im doing that no?
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
@On({ event: "messageDelete" })
async onMessageDelete(
[deletedMessage]: [Message | PartialMessage],
client: Client
) {
try {
const guildId = deletedMessage.guild?.id;
if (!guildId) return;

const configRepo = database.getRepository(ServerBotConfig);
const config = await configRepo.findOne({ where: { guildId } });
if (!config) return;

const ticketPlugin = config.pluginConfigs?.ticketPlugin;
const panels = ticketPlugin?.panels;
if (!panels || panels.length === 0) return;

const messageId = deletedMessage.id;
console.log(`messageDelete event for messageId: ${messageId}`);

const updatedPanels = panels.filter(
(panel) => panel.panelMessageId !== messageId
);

if (updatedPanels.length === panels.length) {
console.log("No matching panel found, no action taken.");
return;
}

if (updatedPanels.length === 0) {
console.log(
"No panels remaining, deleting ticketPlugin configuration."
);
delete config.pluginConfigs!.ticketPlugin;
} else {
config.pluginConfigs!.ticketPlugin!.panels = updatedPanels;
}

await configRepo.save(config);
console.log(
`Deleted panel with messageId ${messageId} for guild ${guildId}.`
);
} catch (error) {
console.error("Error in onMessageDelete:", error);
}
}
}
@On({ event: "messageDelete" })
async onMessageDelete(
[deletedMessage]: [Message | PartialMessage],
client: Client
) {
try {
const guildId = deletedMessage.guild?.id;
if (!guildId) return;

const configRepo = database.getRepository(ServerBotConfig);
const config = await configRepo.findOne({ where: { guildId } });
if (!config) return;

const ticketPlugin = config.pluginConfigs?.ticketPlugin;
const panels = ticketPlugin?.panels;
if (!panels || panels.length === 0) return;

const messageId = deletedMessage.id;
console.log(`messageDelete event for messageId: ${messageId}`);

const updatedPanels = panels.filter(
(panel) => panel.panelMessageId !== messageId
);

if (updatedPanels.length === panels.length) {
console.log("No matching panel found, no action taken.");
return;
}

if (updatedPanels.length === 0) {
console.log(
"No panels remaining, deleting ticketPlugin configuration."
);
delete config.pluginConfigs!.ticketPlugin;
} else {
config.pluginConfigs!.ticketPlugin!.panels = updatedPanels;
}

await configRepo.save(config);
console.log(
`Deleted panel with messageId ${messageId} for guild ${guildId}.`
);
} catch (error) {
console.error("Error in onMessageDelete:", error);
}
}
}
if the delete message is a panelMessageId remove the entry from db and its only works when the panel is created when bot is on or is still on you know
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
config.pluginConfigs?.ticketPlugin?.panels is this
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
"pluginConfigs": { "ticketPlugin": { "enabled": true, "panels": [ { "ticketCounter": "0", "categoryId": "1371240562677780612", "ticketRoleId": [ "1355351245006704952" ], "panelMessageId": "1379938637340348598" } ] } }, an array of this entity for the plugin:
@Column({ type: "simple-json", nullable: true })
pluginConfigs?: {
greetingPlugin?: {
enabled: boolean;
greetingMessage?: string;
greetingChannelId?: string;
};
levelPlugin?: {
enabled: boolean;
expPerMsg: number;
expCooldown: number;
levelUpMessage?: string;
levelUpChannelId?: string;
xpBase?: number;
xpGrowthRate?: number;
xpMinIncrease?: number;
};
ticketPlugin?: {
enabled: boolean;
panels: {
ticketCounter: string;
categoryId: string;
ticketRoleId: string[];
panelMessageId: string;
}[];
};
twitchPlugin?: {
enabled: boolean;
streamers: {
twitchUserName: string;
discordChannelId: string;
notifyRoleId?: string;
message?: string | null;
}[];
};
tempVoicePlugin?: {
enabled: boolean;
creatorChannelIds: string[];
};
};
@Column({ type: "simple-json", nullable: true })
pluginConfigs?: {
greetingPlugin?: {
enabled: boolean;
greetingMessage?: string;
greetingChannelId?: string;
};
levelPlugin?: {
enabled: boolean;
expPerMsg: number;
expCooldown: number;
levelUpMessage?: string;
levelUpChannelId?: string;
xpBase?: number;
xpGrowthRate?: number;
xpMinIncrease?: number;
};
ticketPlugin?: {
enabled: boolean;
panels: {
ticketCounter: string;
categoryId: string;
ticketRoleId: string[];
panelMessageId: string;
}[];
};
twitchPlugin?: {
enabled: boolean;
streamers: {
twitchUserName: string;
discordChannelId: string;
notifyRoleId?: string;
message?: string | null;
}[];
};
tempVoicePlugin?: {
enabled: boolean;
creatorChannelIds: string[];
};
};
d.js docs
d.js docsβ€’6mo ago
:mdn: Array.prototype.filter() The filter() method of Array instances creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
cRiZZly
cRiZZlyOPβ€’6mo ago
panels returns an array of panel objects or undefined if none exist
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
i mean thats the bot for testing nothing is live but the issue is, that the event is not triggering and the code works when the runtime is same
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
and how can i cache it
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
hm
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
oh man
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
hm so whats the best use case for this scenario i dont want to have then soon when the bot is live for everyone free to use that someone have like 500000 data of created ticket panels want to have it clear you know
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
hmmm how other bots handles that
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
Hm Yea idk man im struggling with this shit for some hrs gettin crashout soon
Unknown User
Unknown Userβ€’6mo ago
Message Not Public
Sign In & Join Server To View
cRiZZly
cRiZZlyOPβ€’6mo ago
okay i will see thank you very much @jâ 🌈 Omg i got it working.
@On({ event: "messageDelete" })
async onMessageDelete(
[deletedMessage]: [Message | PartialMessage],
client: Client
) {
try {
if (!deletedMessage.guild) {
const channel = await client.channels.fetch(deletedMessage.channelId);
if (!channel?.isTextBased()) return;
deletedMessage = await channel.messages.fetch(deletedMessage.id);
}

const guildId = deletedMessage.guild?.id;
if (!guildId) return;

const messageId = deletedMessage.id;

const configRepo = database.getRepository(ServerBotConfig);
const config = await configRepo.findOne({ where: { guildId } });
const panels = config?.pluginConfigs?.ticketPlugin?.panels;
if (!config || !panels?.length) return;

const index = panels.findIndex((p) => p.panelMessageId === messageId);
if (index === -1) return;

panels.splice(index, 1);

if (panels.length === 0) {
delete config.pluginConfigs!.ticketPlugin;
}

await configRepo.save(config);
console.log(
`Deleted panel with messageId ${messageId} from guild ${guildId}.`
);
} catch (error) {
console.error("Error in onMessageDelete:", error);
}
}
}
@On({ event: "messageDelete" })
async onMessageDelete(
[deletedMessage]: [Message | PartialMessage],
client: Client
) {
try {
if (!deletedMessage.guild) {
const channel = await client.channels.fetch(deletedMessage.channelId);
if (!channel?.isTextBased()) return;
deletedMessage = await channel.messages.fetch(deletedMessage.id);
}

const guildId = deletedMessage.guild?.id;
if (!guildId) return;

const messageId = deletedMessage.id;

const configRepo = database.getRepository(ServerBotConfig);
const config = await configRepo.findOne({ where: { guildId } });
const panels = config?.pluginConfigs?.ticketPlugin?.panels;
if (!config || !panels?.length) return;

const index = panels.findIndex((p) => p.panelMessageId === messageId);
if (index === -1) return;

panels.splice(index, 1);

if (panels.length === 0) {
delete config.pluginConfigs!.ticketPlugin;
}

await configRepo.save(config);
console.log(
`Deleted panel with messageId ${messageId} from guild ${guildId}.`
);
} catch (error) {
console.error("Error in onMessageDelete:", error);
}
}
}
& using:
partials: [Partials.Message, Partials.Channel, Partials.GuildMember],
partials: [Partials.Message, Partials.Channel, Partials.GuildMember],
& then i fetch the deleted msg -> Deleted panel with messageId 1379984623441809449 from guild 1355346662440173789. nice finally.
Mark
Markβ€’6mo ago
You can't fetch a deleted structure, there's nothing to retrieve from the API :Thonk:

Did you find this page helpful?