# -*- coding: utf-8 -*- import os import hashlib import shutil import logging from core.commands.base import Command logger = logging.getLogger(__name__) class TemplateSaveCommand(Command): name = "!template_save" aliases = ["/template_save"] async def execute(self, msg, args: str, user_jid: str, room_jid: str = None): if not room_jid: reply = msg.reply("⚠️ Команда !template_save работает только в комнатах.") if reply: reply.send() return if args.startswith(self.name): args = args[len(self.name):].lstrip() name = args.strip() if name.startswith('"') and name.endswith('"'): name = name[1:-1] if not name: reply = msg.reply("Укажите название шаблона: !template_save \"Название\"") if reply: reply.send() return key = (user_jid, room_jid) if room_jid is not None else user_jid original_path = self.bot._last_file_path.get(key) if not original_path or not os.path.exists(original_path): reply = msg.reply("❌ Нет загруженного файла. Сначала отправьте DOCX-шаблон.") if reply: reply.send() return if not original_path.lower().endswith('.docx'): reply = msg.reply("❌ Шаблон должен быть в формате .docx.") if reply: reply.send() return with open(original_path, 'rb') as f: file_hash = hashlib.sha256(f.read()).hexdigest() templates_dir = self.bot.config.data_dir / "templates" templates_dir.mkdir(parents=True, exist_ok=True) safe_room = room_jid.replace('/', '_').replace('@', '_') dest_name = f"{safe_room}_{name}.docx" dest_path = templates_dir / dest_name shutil.copy2(original_path, dest_path) await self.bot.db.save_template(room_jid, name, str(dest_path), file_hash) reply = msg.reply(f"✅ Шаблон '{name}' сохранён.") if reply: reply.send() def get_help(self) -> str: return ( "Сохраняет текущий DOCX-файл как шаблон с указанным именем. " "Использование: `!template_save \"Имя шаблона\"` (только в комнате)" ) class TemplateListCommand(Command): name = "!template_list" aliases = ["/template_list"] async def execute(self, msg, args: str, user_jid: str, room_jid: str = None): if not room_jid: reply = msg.reply("⚠️ Команда !template_list работает только в комнатах.") if reply: reply.send() return if args.startswith(self.name): args = args[len(self.name):].lstrip() templates = await self.bot.db.list_templates(room_jid) if not templates: reply = msg.reply("📭 В этой комнате нет сохранённых шаблонов.") else: lines = ["📋 Шаблоны комнаты:"] + [f" • {t}" for t in templates] reply = msg.reply("\n".join(lines)) if reply: reply.send() def get_help(self) -> str: return ( "Показывает список сохранённых шаблонов в текущей комнате. " "Использование: `!template_list` (только в комнате)" ) class TemplateDeleteCommand(Command): name = "!template_delete" aliases = ["/template_delete"] async def execute(self, msg, args: str, user_jid: str, room_jid: str = None): if not room_jid: reply = msg.reply("⚠️ Команда !template_delete работает только в комнатах.") if reply: reply.send() return if args.startswith(self.name): args = args[len(self.name):].lstrip() name = args.strip() if name.startswith('"') and name.endswith('"'): name = name[1:-1] if not name: reply = msg.reply("Укажите название шаблона: !template_delete \"Название\"") if reply: reply.send() return if await self.bot.db.delete_template(room_jid, name): reply = msg.reply(f"🗑 Шаблон '{name}' удалён.") else: reply = msg.reply(f"❌ Шаблон '{name}' не найден.") if reply: reply.send() def get_help(self) -> str: return ( "Удаляет шаблон по имени. " "Использование: `!template_delete \"Имя шаблона\"` (только в комнате)" )