Skip to content

Instantly share code, notes, and snippets.

@SanariSan
Forked from avivace/telegramRestore.md
Created March 10, 2022 22:01
Show Gist options
  • Save SanariSan/8e3f4ac83dd65a9013056be7788b3ffc to your computer and use it in GitHub Desktop.
Save SanariSan/8e3f4ac83dd65a9013056be7788b3ffc 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/

@SanariSan
Copy link
Author

How to get GROUP_CHAT_ID - https://stackoverflow.com/a/38388851/15516769

//

1- Add the bot to the group.
2- Send a dummy message to the bot (tagging it)
3- Go to following url: https://api.telegram.org/botXXX:YYYY/getUpdates
4- Look for "chat":{"id":-zzzzzzzzzz,

to test id send message with curl -X POST "https://api.telegram.org/botXXX:YYYY/sendMessage" -d "chat_id=-zzzzzzzzzz&text=my sample text"

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