Skip to content

Instantly share code, notes, and snippets.

@avivace
Last active March 6, 2024 16:09
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • 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/

@neonda
Copy link

neonda commented Jun 20, 2021

hi, can i use this code to recover a message from my channel? or its just for the groups. cause i tried and didn't get any result.
and if not, is there any code to do so?

@Samtgboter
Copy link

wait i have a question the file will save as json how to get data from it if anyone can help ???

@MohammadJouza
Copy link

"""
STEPS TO RECOVER ALL THE MEDIA AND MESSAGES DELETED FROM TELEGRAM CHAT:

[STEP 0]
You need to have python on your machine https://docs.python.org/3/faq/ you can check if you have python using this command:
python --version

[STEP 1]
Create a folder (to save the backup inside it) using the normal way.
NOTE: OR using this command:mkdir backup_will_be_inside_me.

[STEP 2]
Copy and Paste this file inside the folder you created in [STEP 1] backup_will_be_inside_me THEN rename the file to backup_script THEN open it cause we need to change some lines (it should be with extension .py)

[STEP 3]
Open your terminal and install telethon using this command:
pip install telethon

[STEP 4]
Get your own api_id, api_hash and group_chat_id and put their values in the code below the sentence THE_CODE_START_AFTER_THIS_LINE:

A. How to get your own `api_id`, `api_hash`:
    1) Go to `https://my.telegram.org` and log in.
    2) Insert your phone number `+XXXXXXXXXXXX`.
    3) Insert the code you received in the Telegram application.
    4) Click on `API development tools`.
    5) Now you will find your `api_id`, `api_hash`.
    NOTE: or from `https://tjhorner.dev/webogram/#/login`.

B. How to get your `group_chat_id`:
    1) Go to `https://tjhorner.dev/webogram/#/login` and log in.
    2) Insert your phone number `XXXXXXXXX`.
    3) Insert the code you received in the Telegram application. 
    4) Click on the chat you want to recover messages from it (like you want to send a message).
    5) Click on the chat information.
    6) Now you will find your `api_id`.

[STEP 5]
Finally, recover the deleted media and messages:
1) Open the termenial inside the folder backup_will_be_inside_me (by hold SHIFT + Right-Click THEN pick Open Powershell here).
2) Run the code in the file backup_script.py by using this command:
python backup_script.py
3) Insert your phone number 00XXXXXXXXX.
4) Insert the code you received in the Telegram application.
5) NOW all you need to do is to wait till the process of recovering deleted media and messages is done.
NOTE: The process needs time depending on the size and the number of the media and the messages you will recover (look at the date to know where the process reaches).

=> Inside the folder `backup_will_be_inside_me` you will find all the media you lost (Images, voices, videos, etc).

=> Inside the file `dump.json` you will see the text that you deleted from the chat.

THE_CODE_START_AFTER_THIS_LINE

FOR ANY QUESTION [MOHAMMAD JOUZA]
LINKEDIN LINK: https://www.linkedin.com/in/mohammad-jouza/
"""

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

[STEP 4 - A]

api_id = REPLACE_ME_WITH_YOUR_API_ID
api_hash = 'REPLACE_ME_WITH_YOUR_API_HASH'

[STEP 4 - B]

group_chat_id=REPLACE_ME_WITH_YOUR_GROUP_CHAT_ID

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)

@Enough7
Copy link

Enough7 commented Oct 28, 2021

@dkovacs24 What's the TG-Support's answer?

@dkovacs24
Copy link

@dkovacs24 What's the TG-Support's answer?

@Enough7 Nothing. I also wrote them a couple months ago on another matter, twice, zero replies. In their defense, they are a volunteer support service, but zero answers, not even a "We got your message", is a disappointment.

@Enough7
Copy link

Enough7 commented Oct 28, 2021

Thanks

@yegr82
Copy link

yegr82 commented Dec 19, 2021

Does one have a script for converting the dumped json file into a more chat-like looking text?
From my experience, the "recent actions" section showed only the latest portion of the deleted messages. However, the script, after downloading this portion, automatically proceeded to the other, previous portion, which was not observable in Android and PC client. The overall volume was some 6 Gb. The messages from some 25 days (preceding the latest portion and, correspondingly, finalizing the earliest portion) were not downloaded because the claimed 48h period for copying the deleted messages turned out to be only some 24h (maybe precisely 24h), which is a certain nuisance.

@ronank7z
Copy link

ronank7z commented Dec 22, 2021

TypeError: '<' not supported between instances of 'int' and 'str', what happen?

Traceback (most recent call last):
File "C:\Users\hackr\anaconda3\lib\site-packages\telethon\sessions\memory.py", line 194, in get_input_entity
return utils.get_input_peer(key)
File "C:\Users\hackr\anaconda3\lib\site-packages\telethon\utils.py", line 235, in get_input_peer
_raise_cast_fail(entity, 'InputPeer')
File "C:\Users\hackr\anaconda3\lib\site-packages\telethon\utils.py", line 138, in _raise_cast_fail
raise TypeError('Cannot cast {} to any kind of {}.'.format(
TypeError: Cannot cast PeerChannel to any kind of InputPeer.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "c:\Users\hackr\Desktop\test.py", line 15, in
group = client.get_entity(PeerChannel('xxxxxxxxxx'))
File "C:\Users\hackr\anaconda3\lib\site-packages\telethon\sync.py", line 39, in syncified
return loop.run_until_complete(coro)
File "C:\Users\hackr\anaconda3\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "C:\Users\hackr\anaconda3\lib\site-packages\telethon\client\users.py", line 292, in get_entity
inputs.append(await self.get_input_entity(x))
File "C:\Users\hackr\anaconda3\lib\site-packages\telethon\client\users.py", line 430, in get_input_entity
return self.session.get_input_entity(peer)
File "C:\Users\hackr\anaconda3\lib\site-packages\telethon\sessions\memory.py", line 198, in get_input_entity
key = utils.get_peer_id(key)
File "C:\Users\hackr\anaconda3\lib\site-packages\telethon\utils.py", line 1038, in get_peer_id
if not (0 < peer.channel_id <= 9999999999):
TypeError: '<' not supported between instances of 'int' and 'str'

@SanariSan
Copy link

Saved my day, thanks so much, works just fine ✨✨✨

@Eye4GotMyNAme
Copy link

Eye4GotMyNAme commented Apr 13, 2022

""" STEPS TO RECOVER ALL THE MEDIA AND MESSAGES DELETED FROM TELEGRAM CHAT:

[STEP 0] You need to have python on your machine https://docs.python.org/3/faq/ you can check if you have python using this command: python --version

[STEP 1] Create a folder (to save the backup inside it) using the normal way. NOTE: OR using this command:mkdir backup_will_be_inside_me.

[STEP 2] Copy and Paste this file inside the folder you created in [STEP 1] backup_will_be_inside_me THEN rename the file to backup_script THEN open it cause we need to change some lines (it should be with extension .py)

[STEP 3] Open your terminal and install telethon using this command: pip install telethon

[STEP 4] Get your own api_id, api_hash and group_chat_id and put their values in the code below the sentence THE_CODE_START_AFTER_THIS_LINE:

A. How to get your own `api_id`, `api_hash`:
    1) Go to `https://my.telegram.org` and log in.
    2) Insert your phone number `+XXXXXXXXXXXX`.
    3) Insert the code you received in the Telegram application.
    4) Click on `API development tools`.
    5) Now you will find your `api_id`, `api_hash`.
    NOTE: or from `https://tjhorner.dev/webogram/#/login`.

B. How to get your `group_chat_id`:
    1) Go to `https://tjhorner.dev/webogram/#/login` and log in.
    2) Insert your phone number `XXXXXXXXX`.
    3) Insert the code you received in the Telegram application. 
    4) Click on the chat you want to recover messages from it (like you want to send a message).
    5) Click on the chat information.
    6) Now you will find your `api_id`.

[STEP 5] Finally, recover the deleted media and messages: 1) Open the termenial inside the folder backup_will_be_inside_me (by hold SHIFT + Right-Click THEN pick Open Powershell here). 2) Run the code in the file backup_script.py by using this command: python backup_script.py 3) Insert your phone number 00XXXXXXXXX. 4) Insert the code you received in the Telegram application. 5) NOW all you need to do is to wait till the process of recovering deleted media and messages is done. NOTE: The process needs time depending on the size and the number of the media and the messages you will recover (look at the date to know where the process reaches).

=> Inside the folder `backup_will_be_inside_me` you will find all the media you lost (Images, voices, videos, etc).

=> Inside the file `dump.json` you will see the text that you deleted from the chat.

THE_CODE_START_AFTER_THIS_LINE

FOR ANY QUESTION [MOHAMMAD JOUZA] LINKEDIN LINK: https://www.linkedin.com/in/mohammad-jouza/ """

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

[STEP 4 - A]

api_id = REPLACE_ME_WITH_YOUR_API_ID api_hash = 'REPLACE_ME_WITH_YOUR_API_HASH'

[STEP 4 - B]

group_chat_id=REPLACE_ME_WITH_YOUR_GROUP_CHAT_ID

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)

File "C:\Users\Artem\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\telethon\tl\tlobject.py", line 112, in serialize_bytes
raise TypeError(
TypeError: bytes or str expected, not <class 'int'>

what do i do with this?

@arthurclouds
Copy link

arthurclouds commented May 2, 2022

I tried to do like you wrote, but it shows this

how to solve this?

Traceback (most recent call last):
File "C:\Users\Arthu\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\sessions\memory.py", line 194, in get_input_entity
return utils.get_input_peer(key)
File "C:\Users\Arthu\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\utils.py", line 235, in get_input_peer
_raise_cast_fail(entity, 'InputPeer')
File "C:\Users\Arthu\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\utils.py", line 138, in _raise_cast_fail
raise TypeError('Cannot cast {} to any kind of {}.'.format(
TypeError: Cannot cast PeerChannel to any kind of InputPeer.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "H:\ackup_will_be_inside_m\backup_script.py", line 15, in
group = client.get_entity(PeerChannel('-1001654540914'))
File "C:\Users\Arthu\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\sync.py", line 39, in syncified
return loop.run_until_complete(coro)
File "C:\Users\Arthu\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete
return future.result()
File "C:\Users\Arthu\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\client\users.py", line 292, in get_entity
inputs.append(await self.get_input_entity(x))
File "C:\Users\Arthu\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\client\users.py", line 430, in get_input_entity
return self.session.get_input_entity(peer)
File "C:\Users\Arthu\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\sessions\memory.py", line 198, in get_input_entity
key = utils.get_peer_id(key)
File "C:\Users\Arthu\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\utils.py", line 1038, in get_peer_id
if not (0 < peer.channel_id <= 9999999999):
TypeError: '<' not supported between instances of 'int' and 'str'
PS H:\ackup_will_be_inside_m>

@arthurclouds
Copy link

ok, I just tried to remove quotes from group chat id, now i have only this

Traceback (most recent call last):
File "H:\ackup_will_be_inside_m\backup_script.py", line 15, in
group = client.get_entity(PeerChannel(-1001625426205))
File "C:\Users\Arthu\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\sync.py", line 39, in syncified
return loop.run_until_complete(coro)
File "C:\Users\Arthu\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete
return future.result()
File "C:\Users\Arthu\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\client\users.py", line 292, in get_entity
inputs.append(await self.get_input_entity(x))
File "C:\Users\Arthu\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\client\users.py", line 466, in get_input_entity
raise ValueError(
ValueError: Could not find the input entity for PeerChannel(channel_id=1625426205) (PeerChannel). Please read https://docs.telethon.dev/en/latest/concepts/entities.html to find out more details.
Segmentation fault

@victoriatrinita
Copy link

victoriatrinita commented Jul 24, 2022

ok, I just tried to remove quotes from group chat id, now i have only this

Traceback (most recent call last): File "H:\ackup_will_be_inside_m\backup_script.py", line 15, in group = client.get_entity(PeerChannel(-1001625426205)) File "C:\Users\Arthu\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\sync.py", line 39, in syncified return loop.run_until_complete(coro) File "C:\Users\Arthu\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete return future.result() File "C:\Users\Arthu\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\client\users.py", line 292, in get_entity inputs.append(await self.get_input_entity(x)) File "C:\Users\Arthu\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\client\users.py", line 466, in get_input_entity raise ValueError( ValueError: Could not find the input entity for PeerChannel(channel_id=1625426205) (PeerChannel). Please read https://docs.telethon.dev/en/latest/concepts/entities.html to find out more details. Segmentation fault

@arthurclouds Have you made sure that you've inserted the correct GROUP_CHAT_ID?

@samaypy
Copy link

samaypy commented Feb 3, 2023

Thank You so much, you saved my Life!

@AnarialPrescott
Copy link

Hello everyone Please help someone! It is very urgent to figure it out! Can someone tell me what these errors are related to:
Please enter your phone (or bot token): ********
Traceback (most recent call last):
File "D:\Telegram Desktop\backup_will_be_inside_me\backup_script.py", line 13, in
client.start()
File "C:\Users\Acer\AppData\Local\Programs\Python\Python311\Lib\site-packages\telethon\client\auth.py", line 128, in start
else self.loop.run_until_complete(coro)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Acer\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\Acer\AppData\Local\Programs\Python\Python311\Lib\site-packages\telethon\client\auth.py", line 184, in _start
await self.send_code_request(phone, force_sms=force_sms)
File "C:\Users\Acer\AppData\Local\Programs\Python\Python311\Lib\site-packages\telethon\client\auth.py", line 434, in send_code_request
result = await self(functions.auth.SendCodeRequest(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Acer\AppData\Local\Programs\Python\Python311\Lib\site-packages\telethon\client\users.py", line 30, in call
return await self._call(self._sender, request, ordered=ordered)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Acer\AppData\Local\Programs\Python\Python311\Lib\site-packages\telethon\client\users.py", line 67, in _call
future = sender.send(request, ordered=ordered)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Acer\AppData\Local\Programs\Python\Python311\Lib\site-packages\telethon\network\mtprotosender.py", line 181, in send
state = RequestState(request)
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Acer\AppData\Local\Programs\Python\Python311\Lib\site-packages\telethon\network\requeststate.py", line 17, in init
self.data = bytes(request)
^^^^^^^^^^^^^^
File "C:\Users\Acer\AppData\Local\Programs\Python\Python311\Lib\site-packages\telethon\tl\tlobject.py", line 194, in bytes
return self._bytes()
^^^^^^^^^^^^^
File "C:\Users\Acer\AppData\Local\Programs\Python\Python311\Lib\site-packages\telethon\tl\functions\auth.py", line 644, in _bytes
self.serialize_bytes(self.api_hash),
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Acer\AppData\Local\Programs\Python\Python311\Lib\site-packages\telethon\tl\tlobject.py", line 112, in serialize_bytes
raise TypeError(
TypeError: bytes or str expected, not <class 'int'>

@Enough7
Copy link

Enough7 commented Aug 11, 2023

@AnarialPrescott At some point the program gave telethon an int(eger) instead of a str(ing) or bytes.

@AnarialPrescott
Copy link

@Enough7 thank you! can you please tell me at what point this could have happened and how to fix it?

@Enough7
Copy link

Enough7 commented Aug 11, 2023

@AnarialPrescott Okay, just because you asked that nicely :).
The error is raised here.
Before the error occurred this line is executed.
That line is located in a function called edit_2fa.
It looks like that code segment is trying to change your password and fails because your E-Mail-Address is not confirmed.
So it is probably related to two factor authentication, try turning it off or test it with a different account if possible.

@AnarialPrescott
Copy link

AnarialPrescott commented Aug 11, 2023

@Enough7 Thank you very much for your answers! But, unfortunately, even with two-factor authentication disabled and with another account does not work and still the same mistake(
But still thank you very much for helping me!

@Enough7
Copy link

Enough7 commented Aug 11, 2023

@AnarialPrescott You can contact the developers of Telethon here

@AnarialPrescott
Copy link

@Enough7 Thank you very much for your help!!!

@avivace
Copy link
Author

avivace commented Aug 13, 2023

I've created a discord server to ease the conversation for people needing to install python/help in executing the script: https://discord.gg/zpu7YUP3Um

@gitneep
Copy link

gitneep commented Oct 10, 2023

Can this be altered so that it can also be run as a non-admin? E.g. a bot that sits in the group and records all messages and notices when a message has been deleted and flags this to the owner of the bot?

@a-zazell
Copy link

a-zazell commented Dec 9, 2023

How to restore data into the group?

@gasl20
Copy link

gasl20 commented Dec 14, 2023

Hi guys
I have
api_id = **
api_hash = **
group_id = **

But when I run
c:\1>python backup_script.py
I have
Please enter your phone (or bot token): ****
Traceback (most recent call last):
File "c:\1\backup_script.py", line 13, in
client.start()
File "C:\Users\hunny\AppData\Local\Programs\Python\Python312\Lib\site-packages\telethon\client\auth.py", line 128, in start
else self.loop.run_until_complete(coro)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\hunny\AppData\Local\Programs\Python\Python312\Lib\asyncio\base_events.py", line 684, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\hunny\AppData\Local\Programs\Python\Python312\Lib\site-packages\telethon\client\auth.py", line 184, in _start
await self.send_code_request(phone, force_sms=force_sms)
File "C:\Users\hunny\AppData\Local\Programs\Python\Python312\Lib\site-packages\telethon\client\auth.py", line 434, in send_code_request
result = await self(functions.auth.SendCodeRequest(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\hunny\AppData\Local\Programs\Python\Python312\Lib\site-packages\telethon\client\users.py", line 30, in call
return await self._call(self._sender, request, ordered=ordered)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\hunny\AppData\Local\Programs\Python\Python312\Lib\site-packages\telethon\client\users.py", line 67, in _call
future = sender.send(request, ordered=ordered)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\hunny\AppData\Local\Programs\Python\Python312\Lib\site-packages\telethon\network\mtprotosender.py", line 183, in send
state = RequestState(request)
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\hunny\AppData\Local\Programs\Python\Python312\Lib\site-packages\telethon\network\requeststate.py", line 17, in init
self.data = bytes(request)
^^^^^^^^^^^^^^
File "C:\Users\hunny\AppData\Local\Programs\Python\Python312\Lib\site-packages\telethon\tl\tlobject.py", line 194, in bytes
return self._bytes()
^^^^^^^^^^^^^
File "C:\Users\hunny\AppData\Local\Programs\Python\Python312\Lib\site-packages\telethon\tl\functions\auth.py", line 643, in _bytes
self.serialize_bytes(self.api_hash),
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\hunny\AppData\Local\Programs\Python\Python312\Lib\site-packages\telethon\tl\tlobject.py", line 112, in serialize_bytes
raise TypeError(
TypeError: bytes or str expected, not <class 'int'>

Any help, please

@AP-XD
Copy link

AP-XD commented Dec 24, 2023

I want to send it to some group/channel instead of downloading it

@astrorookie
Copy link

Can this be altered so that it can also be run as a non-admin? E.g. a bot that sits in the group and records all messages and notices when a message has been deleted and flags this to the owner of the bot?

I doubt this, as it uses your account so you would need admin access to view (and therefore) save the messages

@AP-XD
Copy link

AP-XD commented Feb 19, 2024

Can this be altered so that it can also be run as a non-admin? E.g. a bot that sits in the group and records all messages and notices when a message has been deleted and flags this to the owner of the bot?

I doubt this, as it uses your account so you would need admin access to view (and therefore) save the messages

I actually wrote the code which will download the file and then send it to desired channel via telethon

@dJani97
Copy link

dJani97 commented Feb 27, 2024

Can this be altered so that it can also be run as a non-admin? E.g. a bot that sits in the group and records all messages and notices when a message has been deleted and flags this to the owner of the bot?

I doubt this, as it uses your account so you would need admin access to view (and therefore) save the messages

I actually wrote the code which will download the file and then send it to desired channel via telethon

Hi, can you please share this code?

@dJani97
Copy link

dJani97 commented Feb 27, 2024

Here is my attempt at creating a "restore" script. Note that you cannot restore messages with their original date, so this script will send them as brand new messages, and append the original date to the message body. It will also send photo, video, audio, etc. media messages, and stickers correctly.

First of all, you will have to edit the dump.json file, because OP's script does not output valid json format. To fix this, append [ at the beginning, and ] at the end of the file.

Then run this script in the same folder where you ran OP's script. Don't forget to replace the api_id, api_hash and chat_id variables.

import json
import time
import glob
from telethon import TelegramClient
from telethon.tl.types import PeerChat
from datetime import datetime

with open("dump.json","r") as file:
    content = json.load(file)
    # sort by date:
    content = sorted(content, key=lambda x: x["date"])

    api_id = API_ID
    api_hash = API_HASH
    chat_id = GROUP_CHAT_ID

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

    group = client.get_entity(PeerChat(chat_id))

    for msg in content:

        message_id = msg["id"]
        message = msg["message"]
        has_media = msg['media'] != None
        has_message = message != ""
        date = datetime.fromisoformat(msg["date"]).strftime("%Y %b %d, %H:%M")

        # print message, date, and attachment info:
        print(f"{i} {message}, {date}, has_media: {has_media}")

        if (has_message):
            message = str(date) + "\n\n" + str(message)
        else:
            message = str(date)

        did_send_media_msg = False

        if has_media:
            file_names = glob.glob(f"{message_id}.*")
            for file_name in file_names:
                print(f"Sending Media: {file_name}")
                client.send_file(entity=group, file=file_name, caption=message, silent=True)
                did_send_media_msg = True

        elif has_message or (not did_send_media_msg):
            print(f"Sending Message: {message}")
            client.send_message(entity=group, message=message, silent=True)

        # sleep to avoid rate limiting, you may experiment with reducing this time:
        time.sleep(1)

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