Published on

How to delete all previous messages in grammY Telegram Bot

Authors

grammY is a framework to create a Telegram bot pretty easily in Node.js or Deno environments.

It provides lots of features out of the box, using which you can build a Telegram bot almost instantly.

Today, let's see how to delete all the previous messages 🤐

import { Bot } from "grammy";
const bot = new Bot("YOUR_BOT_TOKEN_HERE");

bot.command('deleteAll', async (ctx) => {
    let res = await ctx.reply('deleting');
    console.log(res);
    for(let i = res.message_id; i >= 0; i--) {
        console.log(`chat_id: ${ctx.chat.id}, message_id: ${i}`);
        try {
            let res = await ctx.api.deleteMessage(ctx.chat.id, i);
            console.log(res);
        } catch (e) {
            console.error(e);
        }
    }
 });

Happy deleting messages!