Редактировать template.py

This commit is contained in:
Markov Andrey
2026-06-30 21:43:34 +00:00
parent 8be5efa71d
commit d4b7079c60

View File

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