Редактировать 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 hashlib
import shutil
@@ -7,64 +6,48 @@ 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()
reply = msg.reply("⚠️ Команда работает только в комнатах.")
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()
if reply: reply.send()
return
key = (user_jid, room_jid) if room_jid is not None else user_jid
key = (user_jid, room_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()
if reply: reply.send()
return
if not original_path.lower().endswith('.docx'):
reply = msg.reply("❌ Шаблон должен быть в формате .docx.")
if reply:
reply.send()
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}' сохранён.")
try:
result = await self.bot.rag_client.template_save(room_jid, name, original_path, file_hash)
if result.get('status') == 'ok':
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:
reply.send()
def get_help(self) -> str:
return (
"Сохраняет текущий DOCX-файл как шаблон с указанным именем. "
"Использование: `!template_save \"Имя шаблона\"` (только в комнате)"
)
return "Сохраняет текущий DOCX как шаблон в комнате."
class TemplateListCommand(Command):
@@ -73,27 +56,25 @@ class TemplateListCommand(Command):
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()
reply = msg.reply("⚠️ Команда работает только в комнатах.")
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))
try:
result = await self.bot.rag_client.template_list(room_jid)
templates = result.get('templates', [])
if not templates:
reply = msg.reply("📭 В этой комнате нет шаблонов.")
else:
lines = ["📋 Шаблоны комнаты:"] + [f"{t}" for t in templates]
reply = msg.reply("\n".join(lines))
except Exception as e:
logger.exception(f"Ошибка в !template_list: {e}")
reply = msg.reply(f"❌ Ошибка: {e}")
if reply:
reply.send()
def get_help(self) -> str:
return (
"Показывает список сохранённых шаблонов в текущей комнате. "
"Использование: `!template_list` (только в комнате)"
)
return "Показывает список сохранённых шаблонов в комнате."
class TemplateDeleteCommand(Command):
@@ -102,31 +83,27 @@ class TemplateDeleteCommand(Command):
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()
reply = msg.reply("⚠️ Команда работает только в комнатах.")
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()
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}' не найден.")
try:
result = await self.bot.rag_client.template_delete(room_jid, name)
if result.get('status') == 'ok':
reply = msg.reply(f"🗑 Шаблон '{name}' удалён.")
else:
reply = msg.reply(f"❌ Ошибка удаления: {result}")
except Exception as e:
logger.exception(f"Ошибка в !template_delete: {e}")
reply = msg.reply(f"❌ Ошибка: {e}")
if reply:
reply.send()
def get_help(self) -> str:
return (
"Удаляет шаблон по имени. "
"Использование: `!template_delete \"Имя шаблона\"` (только в комнате)"
)
return "Удаляет шаблон по имени из комнаты."