Skip to content

Instantly share code, notes, and snippets.

@obsessedcake
Last active April 14, 2024 04:30
Show Gist options
  • Save obsessedcake/da9825fa3b47eb7e1c51be4df3413551 to your computer and use it in GitHub Desktop.
Save obsessedcake/da9825fa3b47eb7e1c51be4df3413551 to your computer and use it in GitHub Desktop.
2019-11-09
#!/usr/bin/python3
# coding=utf-8
import pickle
import os.path
from telethon.sync import TelegramClient
from telethon.tl.types import InputMessagesFilterPhotoVideo
''' Settings '''
# Can be obtained on https://my.telegram.org/apps
api_id = 1234567
api_hash = '0123456789abcdef0123456789abcdef'
# Phone number or user id (e.g @MyUserId)
chat_id = 'chat_id'
download_path = '/your/os/depended/path/to/download/folder/'
''' Data '''
def load_saved_data():
messages_id = []
file_names = []
file_name = f'{download_path}messages_id.bin'
if os.path.exists(file_name):
with open (file_name, 'rb') as fp:
messages_id = pickle.load(fp)
file_name = f'{download_path}file_names.bin'
if os.path.exists(file_name):
with open (file_name, 'rb') as fp:
file_names = pickle.load(fp)
return messages_id, file_names
def save_data(messages_id, file_names):
with open('{download_path}messages_id.bin', 'wb') as f:
pickle.dump(messages_id, f)
with open('{download_path}file_names.bin', 'wb') as f:
pickle.dump(file_names, f)
''' Telegram client '''
def create_client(api_id, api_hash):
client = TelegramClient('test_session', api_id, api_hash)
client.start()
return client
def get_all_media_for(client, chat_id):
chat = client.get_input_entity(chat_id)
return client.get_messages(chat, None, filter=InputMessagesFilterPhotoVideo)
def filter_and_download(client, messages, messages_id, file_names):
i = 1
for message in messages:
if message.forward is not None:
continue
print(f'Downloading {i} photo...\r', end='', flush=True)
i += 1
date = message.date.strftime('%Y/%m-%B/%Y-%m-%d_%H-%M-%S')
file_name = f'{download_path}{date}{message.file.ext}'
if message.id in messages_id:
continue
if file_name in file_names:
j = 1
while True:
file_name = f'{download_path}{date}_{j}{message.file.ext}'
if file_name not in file_names:
break
j += 1
message.download_media(file=file_name)
messages_id.append(message.id)
file_names.append(file_name)
print('')
''' Main '''
client = create_client(api_id, api_hash)
print('Fetching all incoming messages with photo and video.')
messages = get_all_media_for(client, chat_id)
messages_id, file_names = load_saved_data()
try:
filter_and_download(client, messages, messages_id, file_names)
except:
print('Exception has been raised. Please rerun script.')
save_data(messages_id, file_names)
@obsessedcake
Copy link
Author

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