Files
abot/db/group_virtual_redis.py
2025-04-30 13:22:33 +08:00

57 lines
2.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import json
from loguru import logger
from typing import Dict, Any, List, Optional
from db.connection import DBConnectionManager
class GroupVirtualRedisDB:
"""群组虚拟聊天Redis数据库操作类"""
def __init__(self, db_manager: DBConnectionManager):
self.db_manager = db_manager
self.redis_client = db_manager.get_redis_connection()
self.LOG = logger
self.chat_groups_key = "group_virtual:chat_groups"
def load_chat_groups(self) -> Dict[str, Any]:
"""从Redis加载虚拟聊天组数据"""
try:
chat_groups_json = self.redis_client.get(self.chat_groups_key)
if chat_groups_json:
return json.loads(chat_groups_json)
else:
# 如果Redis中没有数据返回空结构
return {"chatGroups": []}
except Exception as e:
self.LOG.error(f"从Redis加载虚拟聊天组数据失败: {e}")
return {"chatGroups": []}
def save_chat_groups(self, chat_groups: Dict[str, Any]) -> bool:
"""保存虚拟聊天组数据到Redis"""
try:
chat_groups_json = json.dumps(chat_groups, ensure_ascii=False)
self.redis_client.set(self.chat_groups_key, chat_groups_json)
return True
except Exception as e:
self.LOG.error(f"保存虚拟聊天组数据到Redis失败: {e}")
return False
def get_chat_group(self, chat_group_id: str) -> Optional[Dict[str, Any]]:
"""获取指定ID的虚拟聊天组"""
chat_groups = self.load_chat_groups()
for group in chat_groups.get("chatGroups", []):
if group["id"] == chat_group_id:
return group
return None
def get_chat_groups_by_group_id(self, group_id: str) -> List[Dict[str, Any]]:
"""获取包含指定群的所有虚拟聊天组"""
result = []
chat_groups = self.load_chat_groups()
for chat_group in chat_groups.get("chatGroups", []):
for group in chat_group.get("groups", []):
if group["id"] == group_id:
result.append(chat_group)
break
return result