109 lines
4.5 KiB
Python
109 lines
4.5 KiB
Python
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("⚠️ Команда работает только в комнатах.")
|
||
if reply: reply.send()
|
||
return
|
||
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)
|
||
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()
|
||
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 как шаблон в комнате."
|
||
|
||
|
||
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("⚠️ Команда работает только в комнатах.")
|
||
if reply: reply.send()
|
||
return
|
||
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 "Показывает список сохранённых шаблонов в комнате."
|
||
|
||
|
||
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("⚠️ Команда работает только в комнатах.")
|
||
if reply: reply.send()
|
||
return
|
||
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
|
||
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 "Удаляет шаблон по имени из комнаты." |