Kamal Muradov
Kamal Muradov

Reputation: 49

How can I delete all chat history using Telegram Bot?

Is it possible to delete all chat history(messages) of my chat with bot.

So the console version be like:

import os
os.sys("clear") - if Linux
os.sys("cls") - if Windows

All I want is to delete all messages in chat using bot.

def deleteChat(message):
    #delete chat code

Upvotes: 0

Views: 31904

Answers (1)

Davide
Davide

Reputation: 484

First of all, if you want to delete history with a bot you should save message ids. Otherwise, you could use an userbot (using an user account) for clearing it. You can iter all chat messages and get their ids, and delete them in chunks of 100 messages each iteration.

Warning: itering message history of a chat is not possible with bots and BotAPI, because of Telegram limits. So you should use an MTProto API framework, with an user account as said before.

First of all, pyrogram library is needed for doing this (you could also use telethon), and instance a Client, then you can add an handler or start Client using with keyword. Then get all messages ids by itering the chat, and save them in a list. Finally, delete them using delete_messages Client method:

import time, asyncio
from pyrogram import Client, filters
    
    app = Client(
        "filename", # Will create a file named filename.session which will contain userbot "cache"
        # You could also change "filename" to ":memory:" for better performance as it will write userbot session in ram
        api_id=0, # You can get api_hash and api_id by creating an app on
        api_hash="", # my.telegram.org/apps (needed if you use MTProto instead of BotAPI)
    )


@app.on_message(filters.me & filters.command("clearchat") & ~filters.private)
async def clearchat(app_, msg):
    start = time.time()

    async for x in app_.iter_history(msg.chat.id, limit=1, reverse=True):
          first = x.message_id

    chunk = 98

    ids = range(first, msg.message_id)

    for _ in (ids[i:i+chunk] for i in range(0, len(ids), chunk)):
        try:
            asyncio.create_task(app_.delete_messages(msg.chat.id, _))
        except:
            pass
    
    end = time.time() - start

    vel = len(ids) / end
    await msg.edit_text(f"{len(ids)} messages were successfully deleted in {end-start}s.\n{round(vel, 2)}mex/s")


app.run()

Once you start the userbot, add it in a group, and send "/clearchat". If the userbot has delete messages permission, it will start deleting all messages.

For pyrogram documentation see https://docs.pyrogram.org.


(however, you should not print all messages in the terminal, to avoid server overloading)

And the right code for clearing the console is this:

import os

def clear():
    os.system("cls" if os.name == "nt" else "clear")

as seen in How to clear the interpreter console?.

P.S. You can use the same code, adding bot_token="" parameter to Client, and deleting iter_history part, for deleting messages with a bot if you have the messages ids.

If in the future you'll want to receive messages from a group and print them, but you don't receive the message update, add the bot as admin in the group or disable bot privacy mode in BotFather.

For better pyrogram performance, you should install tgcrypto library.

Upvotes: 11

Related Questions