Skip to content

Instantly share code, notes, and snippets.

@toshiks
Created May 6, 2024 21:55
Show Gist options
  • Save toshiks/ae2c500008c6cece718aef046b5ca888 to your computer and use it in GitHub Desktop.
Save toshiks/ae2c500008c6cece718aef046b5ca888 to your computer and use it in GitHub Desktop.
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetHistoryRequest
import os
import asyncio
# Ваши учетные данные API Telegram
api_id = ''
api_hash = ''
# Путь для сохранения изображений
output_folder = 'images'
# Список каналов, из которых вы хотите скачать изображения
channels = [
# Добавьте здесь остальные каналы
]
# Максимальное общее количество изображений для скачивания
max_total_images = 100 * len(channels)
# Максимальное количество сообщений для получения истории сообщений
max_messages = 100000
# Установка соединения с Telegram
client = TelegramClient('session_name', api_id, api_hash)
client.start()
# Создание папки для сохранения изображений
if not os.path.exists(output_folder):
os.makedirs(output_folder)
total_images = 0
lock = asyncio.Lock()
barrier = asyncio.Barrier(len(channels))
async def download_images_from_channel(channel_username):
global total_images
local_total_images = 0
local_offset = 0
channel_entity = await client.get_entity(channel_username)
await barrier.wait()
while True:
messages = await client(GetHistoryRequest(
peer=channel_entity,
limit=max_messages,
offset_date=None,
offset_id=0,
max_id=0,
min_id=0,
add_offset=local_offset,
hash=0
))
local_offset += len(messages.messages)
if len(messages.messages) == 0:
break
for message in messages.messages:
if message.media:
media = message.media
if hasattr(media, 'photo'):
photo = media.photo
file_path = os.path.join(output_folder, f"{channel_username}_{local_total_images}.jpg")
try:
await client.download_media(photo, file_path)
local_total_images += 1
async with lock:
total_images += 1
if total_images > max_total_images:
break
except:
os.remove(file_path)
if total_images > max_total_images:
break
print(f"Total images downloaded from {channel_username}: {min(local_total_images, max_total_images)}")
async def main():
tasks = [download_images_from_channel(channel) for channel in channels]
await asyncio.gather(*tasks)
with client:
client.loop.run_until_complete(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment