Last active
June 17, 2025 11:42
-
-
Save ivan-hilckov/6d7409ecb4c46ac3f72a2d716e1afd47 to your computer and use it in GitHub Desktop.
Deletes all previous messages stored in session and the triggering message
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { BotContext } from '../../types/bot.types'; | |
/** | |
* Deletes all previous messages stored in session and the triggering message | |
*/ | |
export async function deletePreviousMessages(ctx: BotContext): Promise<void> { | |
try { | |
// Delete the triggering message (works for both commands and callback queries) | |
if (ctx.callbackQuery?.message) { | |
// For callback queries, use hydrate method | |
await (ctx.callbackQuery.message as any).delete(); | |
} else { | |
// For commands, use standard delete | |
await ctx.deleteMessage(); | |
} | |
// Delete all stored messages from session | |
if ( | |
ctx.session?.messagesToDelete && | |
ctx.session.messagesToDelete.length > 0 | |
) { | |
for (const messageId of ctx.session.messagesToDelete) { | |
try { | |
await ctx.api.deleteMessage(ctx.chat!.id, messageId); | |
} catch (error) { | |
console.log(`Failed to delete message ${messageId}:`, error); | |
} | |
} | |
// Clear the array after deletion | |
ctx.session.messagesToDelete = []; | |
} | |
} catch (error) { | |
console.error('Error deleting previous messages:', error); | |
} | |
} | |
/** | |
* Initializes session with message tracking if needed | |
*/ | |
export function initializeSession(ctx: BotContext): void { | |
if (!ctx.session) { | |
ctx.session = { | |
userId: 0, | |
username: undefined, | |
currentScene: undefined, | |
messagesToDelete: [], | |
}; | |
} | |
if (!ctx.session.messagesToDelete) { | |
ctx.session.messagesToDelete = []; | |
} | |
} | |
/** | |
* Stores message ID in session for later deletion | |
*/ | |
export function storeMessageForDeletion( | |
ctx: BotContext, | |
messageId: number | |
): void { | |
if (ctx.session?.messagesToDelete) { | |
ctx.session.messagesToDelete.push(messageId); | |
} | |
} | |
/** | |
* Stores multiple message IDs in session for later deletion | |
*/ | |
export function storeMessagesForDeletion( | |
ctx: BotContext, | |
messageIds: number[] | |
): void { | |
if (ctx.session?.messagesToDelete) { | |
ctx.session.messagesToDelete.push(...messageIds); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment