Skip to content

Instantly share code, notes, and snippets.

@avivace
Last active October 1, 2024 21:34
Show Gist options
  • Save avivace/4eb547067e364d416c074b68502e0136 to your computer and use it in GitHub Desktop.
Save avivace/4eb547067e364d416c074b68502e0136 to your computer and use it in GitHub Desktop.
Restore deleted Telegram messages from groups

Restore deleted Telegram messages, medias and files from groups

There's not telegram API method for this, we need to call MTProto methods to retrieve messages from the "Recent Actions" (Admin Log) since deleted messages (and medias) gets moved there for 48 hours before the permanent deletion.

from telethon import TelegramClient, events, sync
from telethon.tl.types import InputChannel, PeerChannel
from telethon.tl.types import Channel
import time

# Get your own api_id and
# api_hash from https://my.telegram.org, under API Development.
#  or from https://tjhorner.dev/webogram/#/login
api_id = API_ID
api_hash = API_HASH

client = TelegramClient('session_name', api_id, api_hash)
client.start()

group = client.get_entity(PeerChannel(GROUP_CHAT_ID))

#messages = client.get_admin_log(group)

file1 = open("dump.json","w") 
c = 0
m = 0
for event in client.iter_admin_log(group):
    if event.deleted_message:
        print("Dumping message",c, "(", event.old.id, event.old.date,")")
        file1.write(event.old.to_json() + ",") 
        c+=1
        if event.old.media:
            m+=1
            #print(event.old.media.to_dict()['Document']['id'])
            client.download_media(event.old.media, str(event.old.id))
            print(" Dumped media", m)
        time.sleep(0.1)

FAQ

How do I run this?

Please check https://docs.python.org/3/faq/

@shadowthevoronin
Copy link

can you help with that error?

Something happened with your JSON file. Please look at this point:

To fix this, append [ at the beginning, and ] at the end of the file.

yeah I checked it, no luck. Tried the same on windows and works just fine (except noticed the comma at the end of JSON and removed it maybe that was an issue). Thank you very much, regardless! That helped a lot

@Silenseo
Copy link

Thank you very much, regardless! That helped a lot

You're welcome)

@f-alex
Copy link

f-alex commented Aug 2, 2024

api_id = ''
api_hash = ''
chat_id = ''
I hope these are not real account )

@Kebble002
Copy link

Thank you very much, regardless! That helped a lot

You're welcome)

I mangaged to run the code successfully, but nothing is happening after i logged in. what could be wrong?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment