/
dmsav
/
ydvs
Обзор
Документация
Войти
/
dmsav
/
ydvs
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
develop
main.py
75 строк
4 KB
dimsav
v 0.0.1
30 апр 2024, 21:03
30 апр 2024, 21:03
76bf215
Код
Авторство
О чём код?
import logging import os import re import sys from datetime import datetime as dt from random import choice from aiogram import Bot, Dispatcher from aiogram.filters import CommandStart from aiogram.types import BotCommand, Message, InputFile, ReactionTypeEmoji from config import Config, load_config config: Config = load_config() BOT_TOKEN: str = config.tg_bot.token # список допустимых emoji emo = ["👍", "👎", "❤", "🔥", "🥰", "👏", "😁", "🤔", "🤯", "😱", "🤬", "😢", "🎉", "🤩", "🤮", "💩", "🙏", "👌", "🕊", "🤡", "🥱", "🥴", "😍", "🐳", "❤🔥", "🌚", "🌭", "💯", "🤣", "⚡", "🍌", "🏆", "💔", "🤨", "😐", "🍓", "🍾", "💋", "🖕", "😈", "😴", "😭", "🤓", "👻", "👨💻", "👀", "🎃", "🙈", "😇", "😨", "🤝", "✍", "🤗", "🫡", "🎅", "🎄", "☃", "💅", "🤪", "🗿", "🆒", "💘", "🙉", "🦄", "😘", "💊", "🙊", "😎", "👾", "🤷♂", "🤷", "🤷♀", "😡"] # Создаем объекты бота и диспетчера bot: Bot = Bot(BOT_TOKEN) dp: Dispatcher = Dispatcher() @dp.message(CommandStart()) async def process_start_command(message: Message): await bot.set_my_commands([BotCommand(command='/start', description='Перезапуск'), BotCommand(command='/stat', description='Показать статистику'),]) await message.answer(text='Бот сохраняет фотки из Канала или группы\n' '/start для перезапуска бота\n' '/stat для просмотра статистики') async def get_destination_path(message: Message): chat_id = str(message.chat.id).replace('-', '') chat_name = str(message.chat.title) # Убираем лишние символы из названия чата folder_name = ''.join(re.findall('[a-zA-Z]|[а-яА-Я]|[0-9]|[-_ ]', chat_name)).replace(' ', "_").strip('_')[0:50] get_destination_path = f'./images/{chat_id}_{folder_name}' os.makedirs(get_destination_path) if not os.path.exists(get_destination_path) else None return get_destination_path async def get_photo_name(message: Message): mess_id = str(message.message_id) mess_ts = message.date #dt.fromtimestamp(int(message.date)) return f"TG2YD_{mess_id}_{mess_ts.strftime('%Y%m%d_%H%M%S')}.jpg" @dp.channel_post() async def process_photo(message: Message): message_data = message.model_dump_json(exclude_none=True) logging.info(message_data) if message.photo: logging.info('Тип: фото') for photo in [message.photo[-1]]: file = await bot.get_file(photo.file_id) logging.info(f'{file=}') await message.bot.download_file(file_path = file.file_path, destination = os.path.join(await get_destination_path(message), await get_photo_name(message))) react = ReactionTypeEmoji(emoji=choice(emo)) await message.react(reaction=[react]) else: react = ReactionTypeEmoji(emoji=choice(emo)) await message.react(reaction=[react]) if config.botenv == 'DEV': await message.answer(text='Фоток в сообщении не обнаружил(') if __name__ == '__main__': print(f'starting bot {config.tg_bot.bot_name} {config.botenv=}') # logging.basicConfig(level=logging.INFO, stream=sys.stdout) logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', stream=sys.stdout, filename='bot.log') dp.run_polling(bot)