Skip to content

Instantly share code, notes, and snippets.

@rama982
Last active August 14, 2020 04:10
Show Gist options
  • Save rama982/03d9d2df5744e92d85e5e8ea13110812 to your computer and use it in GitHub Desktop.
Save rama982/03d9d2df5744e92d85e5e8ea13110812 to your computer and use it in GitHub Desktop.
import sys, os, time
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetAllChatsRequest
from telethon import errors
import math
def callback(current, total):
curr = convert_size(current)
tot = convert_size(total)
print('Downloaded', curr, 'out of', tot,
'bytes: {:.2%}'.format(current / total), end='\r', flush=True)
def convert_size(size_bytes):
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size_bytes, 1024)))
p = math.pow(1024, i)
s = round(size_bytes / p, 2)
return "%s %s" % (s, size_name[i])
def initialize(api_id, api_hash):
try:
os.mkdir('downloaded_media')
except:
pass
client = TelegramClient('media_downloader', api_id, api_hash)
client.start()
return client
def download_media(client, chat_title, skip_min_id=0):
chats = client(GetAllChatsRequest(except_ids=[]))
for _, chat in enumerate(chats.chats):
if chat.title == chat_title:
print("found chat with title", chat_title)
print('attemping to iterate over messages to download media')
skip_min_id = skip_min_id and int(skip_min_id)
for message in client.iter_messages(chat, reverse=True, min_id=skip_min_id):
if message.media:
while True:
print(message.id, message.date, "message has media, downloading")
try:
client.download_media(message, 'downloaded_media', progress_callback=callback)
except errors.FloodWaitError as e:
print(message.id, message.date, "failed to download media: flood wait error, were asked to wait for", e.seconds, " but will be waiting for", e.seconds + 120)
time.sleep(e.seconds + 120)
continue
except Exception as e:
print(message.id, message.date, "failed to download media")
raise e
print(message.id, message.date, "media downloaded, waiting 1 seconds before the next one")
with open('last-message-id', 'w') as f:
f.write(str(message.id))
time.sleep(1)
break
else:
print(message.id, message.date, "message doesn't have media")
break
if __name__ == "__main__":
if len(sys.argv) == 2 and sys.argv[1] == "--help":
print("Example: python main.py --api-id 12345 --api-hash 1ab1ab1ab1ab1ab --chat-title 'Bunker Reborn' --min-id 0")
print(" --api-id and --api-hash you can generate your at https://my.telegram.org")
exit()
if len(sys.argv) < 7:
print("Missing arguments, check --help")
exit(1)
if not (sys.argv[1] == "--api-id" and sys.argv[2] and sys.argv[3] == "--api-hash" and sys.argv[4]):
print("Missing arguments --api-id and --api-hash (order can't differ from example in --help)")
exit(1)
api_id = sys.argv[2]
api_hash = sys.argv[4]
client = initialize(api_id, api_hash)
if not (sys.argv[5] == "--chat-title" and sys.argv[6]):
print("Missing argument --chat-title (order can't differ from example in --help)")
exit(1)
chat_title = sys.argv[6]
skip_min_id = None
if len(sys.argv) == 9 and sys.argv[7] == "--min-id" and sys.argv[8]:
skip_min_id = sys.argv[8]
download_media(client, chat_title, skip_min_id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment