Обновление загрузчика аватарок
This commit is contained in:
@@ -1,15 +1,15 @@
|
||||
# BotCode/routers/downloads/download_avatar_all.py
|
||||
# Объединение закачки аватаров всех типов
|
||||
|
||||
from BotLibrary import write_user_info_to_file
|
||||
from .download_chat_avatar import download_chat_avatar
|
||||
from .download_user_avatar import download_user_photos
|
||||
|
||||
# Настройка экспорта модулей
|
||||
__all__ = ("download_avatar",)
|
||||
__all__ = ("download_avatar", "download_chat_avatar", "download_user_photos")
|
||||
|
||||
|
||||
# Функция объединения закачки аватарок
|
||||
async def download_avatar(message):
|
||||
await download_chat_avatar(message, message.chat)
|
||||
await download_chat_avatar(message)
|
||||
await download_user_photos(message)
|
||||
return f"Успешная закачка аватаров!"
|
||||
write_user_info_to_file(message.from_user)
|
||||
|
||||
@@ -1,32 +1,29 @@
|
||||
# BotCode/routers/downloads/download_chat_avatar.py
|
||||
# Функция скачивания аватара чата
|
||||
|
||||
import os
|
||||
import requests
|
||||
from aiogram import Router
|
||||
from aiogram.types import Chat
|
||||
import aiohttp
|
||||
from BotLibrary import *
|
||||
|
||||
# Создание роутера и настройка экспорта модулей
|
||||
__all__ = ("router", "download_chat_avatar",)
|
||||
router = Router(name="avatar_chat_router")
|
||||
__all__ = ("download_chat_avatar",)
|
||||
log_type = "AvatarChat"
|
||||
|
||||
|
||||
# Функция закачки аватарок чатов
|
||||
async def download_chat_avatar(message, chat: Chat):
|
||||
async def download_chat_avatar(message):
|
||||
try:
|
||||
chat = message.chat
|
||||
# Проверка типа чата (группа или супергруппа)
|
||||
if chat.type in ["group", "supergroup"]:
|
||||
# Получаем информацию о чате (включая фото)
|
||||
chat_info = await bot.get_chat(chat.id)
|
||||
|
||||
chat_id = chat.id
|
||||
|
||||
# Проверка наличия аватара
|
||||
# Проверка на наличие фотографий чата
|
||||
if not chat_info.photo:
|
||||
text_error = f"Чат с ID {chat_id} не имеет аватара."
|
||||
logger.bind(log_type=log_type, user=chat_id).error(text_error)
|
||||
text_error = f"Чат с ID {chat.id} не имеет аватара."
|
||||
logger.bind(log_type=log_type, user=chat.id).error(text_error)
|
||||
return text_error
|
||||
|
||||
# Получаем file_id для фото (высокое качество приоритетно)
|
||||
file_id = (
|
||||
getattr(chat_info.photo, 'big_file_id', None) or
|
||||
getattr(chat_info.photo, 'medium_file_id', None) or
|
||||
@@ -34,39 +31,41 @@ async def download_chat_avatar(message, chat: Chat):
|
||||
)
|
||||
|
||||
if not file_id:
|
||||
text_error = f"Не удалось получить file_id аватара чата с ID {chat_id}."
|
||||
logger.bind(log_type=log_type, user=chat_id).error(text_error)
|
||||
text_error = f"Не удалось получить file_id аватара чата с ID {chat.id}."
|
||||
logger.bind(log_type=log_type, user=chat.id).error(text_error)
|
||||
return text_error
|
||||
|
||||
# Получаем file_info для фото
|
||||
file_info = await bot.get_file(file_id)
|
||||
|
||||
# Строим URL для скачивания файла
|
||||
file_url = f"https://api.telegram.org/file/bot{bot.token}/{file_info.file_path}"
|
||||
|
||||
# Формируем путь для сохранения фото
|
||||
chat_id = find_chat_id(message)
|
||||
save_dir = f"{ImportantPath.chat_avatar}/{chat_id}"
|
||||
chat_id = find_imp_id(chat.id)
|
||||
save_dir = f"{ProjectPath.chat_avatar}/{chat_id}"
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
|
||||
file_extension = os.path.splitext(file_info.file_path)[-1]
|
||||
file_name = f"avatar{file_extension}"
|
||||
save_path = os.path.join(save_dir, file_name)
|
||||
|
||||
# Скачиваем аватар
|
||||
response = requests.get(file_url, stream=True)
|
||||
if response.status_code == 200:
|
||||
with open(save_path, "wb") as file:
|
||||
for chunk in response.iter_content(chunk_size=8192):
|
||||
file.write(chunk)
|
||||
return f"Фото аватара чата с ID {chat_id} успешно скачано."
|
||||
|
||||
else:
|
||||
text_error = f"Не удалось скачать фото аватара чата с ID {chat_id}. Статус: {response.status_code}"
|
||||
logger.bind(log_type=log_type, user=chat_id).error(text_error)
|
||||
return text_error
|
||||
# Асинхронное скачивание
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(file_url) as response:
|
||||
if response.status == 200:
|
||||
with open(save_path, "wb") as file:
|
||||
while True:
|
||||
chunk = await response.content.read(8192)
|
||||
if not chunk:
|
||||
break
|
||||
file.write(chunk)
|
||||
return f"Фото аватара чата с ID {chat_id} успешно скачано."
|
||||
else:
|
||||
text_error = f"Не удалось скачать фото аватара чата с ID {chat_id}. Статус: {response.status}"
|
||||
logger.bind(log_type=log_type, user=chat.id).error(text_error)
|
||||
return text_error
|
||||
else:
|
||||
return
|
||||
|
||||
except Exception as e:
|
||||
chat = message.chat
|
||||
text_error = f"Ошибка при скачивании фото аватара чата с ID {chat.id}: {e}"
|
||||
logger.bind(log_type=log_type, user=chat.id).exception(text_error)
|
||||
logger.bind(log_type=log_type, user=chat.id).error(text_error)
|
||||
return text_error
|
||||
|
||||
@@ -19,7 +19,7 @@ log_type = "Media"
|
||||
async def handle_media(message: types.Message):
|
||||
try:
|
||||
await download_avatar(message)
|
||||
name = find_chat_id(message)
|
||||
name = find_imp_id(message.from_user.id)
|
||||
await logginger(message)
|
||||
file_id = None
|
||||
|
||||
@@ -28,8 +28,8 @@ async def handle_media(message: types.Message):
|
||||
media = message.video if message.content_type == types.ContentType.VIDEO else message.animation
|
||||
file_extension = media.mime_type.split('/')[-1] # Получаем расширение файла (например, "mp4" или "gif")
|
||||
file_name = f"{media.file_id}.{file_extension}" # Используем file_id и расширение для имени
|
||||
save_dir = ImportantPath.video_directory if message.content_type == types.ContentType.VIDEO \
|
||||
else ImportantPath.gif_directory
|
||||
save_dir = ProjectPath.received_video if message.content_type == types.ContentType.VIDEO \
|
||||
else ProjectPath.received_gif
|
||||
|
||||
elif message.content_type == types.ContentType.PHOTO:
|
||||
media = message.photo
|
||||
@@ -38,22 +38,22 @@ async def handle_media(message: types.Message):
|
||||
file_info = await bot.get_file(file_id)
|
||||
# Имя файла будет взято из file_path, который содержит оригинальное имя файла
|
||||
file_name = file_info.file_path.split('/')[-1] # Используем имя файла из пути
|
||||
save_dir = ImportantPath.photo_directory
|
||||
save_dir = ProjectPath.received_photo
|
||||
|
||||
elif message.content_type == types.ContentType.VOICE:
|
||||
media = message.voice
|
||||
file_name = f"{media.file_id}.ogg" # Для голосовых сообщений используем file_id и расширение .ogg
|
||||
save_dir = ImportantPath.voice_directory
|
||||
save_dir = ProjectPath.received_voice
|
||||
|
||||
elif message.content_type == types.ContentType.VIDEO_NOTE:
|
||||
media = message.video_note
|
||||
file_name = f"{media.file_id}.mp4" # Для видеосообщений используем file_id и расширение .mp4
|
||||
save_dir = ImportantPath.videonote_directory
|
||||
save_dir = ProjectPath.received_videonote
|
||||
|
||||
elif message.content_type == types.ContentType.DOCUMENT:
|
||||
media = message.document
|
||||
file_name = media.file_name # Для видеосообщений используем file_id и расширение .mp4
|
||||
save_dir = ImportantPath.document_directory
|
||||
save_dir = ProjectPath.received_document
|
||||
|
||||
else:
|
||||
(logger.bind(log_type=log_type, user=message.from_user.username)
|
||||
|
||||
@@ -2,35 +2,31 @@
|
||||
# Закачка всех аватаров пользователей
|
||||
|
||||
import os
|
||||
from aiogram import Router, types
|
||||
from aiogram import types
|
||||
from aiogram.types import UserProfilePhotos
|
||||
from BotLibrary import *
|
||||
|
||||
|
||||
# Создание роутера и настройка экспорта модулей
|
||||
__all__ = ("router", "download_user_photos",)
|
||||
router = Router(name="avatar_router")
|
||||
__all__ = ("download_user_photos",)
|
||||
log_type = "AvatarUser"
|
||||
|
||||
|
||||
# Функция закачки аватарок пользователя
|
||||
async def download_user_photos(message: types.Message):
|
||||
try:
|
||||
# Получение ID пользователя
|
||||
user_id = message.from_user.id
|
||||
# Проверка на наличие в списке "важных" пользователей
|
||||
user_id = find_imp_id(message.from_user.id)
|
||||
|
||||
# Получение аватарок пользователя
|
||||
user_profile_photos: UserProfilePhotos = await bot.get_user_profile_photos(user_id)
|
||||
|
||||
# Проверка на наличие в списке "важных" пользователей
|
||||
user_id = find_people_id(user_id)
|
||||
user_profile_photos: UserProfilePhotos = await bot.get_user_profile_photos(message.from_user.id)
|
||||
|
||||
# Проверка наличия фотографий
|
||||
if user_profile_photos.total_count == 0:
|
||||
return f"У пользователя {user_id} нет аватарок."
|
||||
|
||||
# Объявление пути и создание директории
|
||||
user_directory = f'{ImportantPath.user_avatar}/{user_id}'
|
||||
user_directory = f'{ProjectPath.user_avatar}/{user_id}'
|
||||
os.makedirs(user_directory, exist_ok=True)
|
||||
|
||||
# Закачка аватарок пользователя
|
||||
|
||||
Reference in New Issue
Block a user