Files
WechatHookBot/database/messsagDB.py
2025-12-03 15:48:44 +08:00

59 lines
1.7 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.
"""
MessageDB - 消息数据库(简化版,仅使用 aiosqlite
"""
import aiosqlite
from loguru import logger
from utils.singleton import Singleton
class MessageDB(metaclass=Singleton):
"""消息存储数据库"""
def __init__(self):
self.db_path = "database/message.db"
self.conn = None
async def initialize(self):
"""初始化数据库"""
self.conn = await aiosqlite.connect(self.db_path)
await self.conn.execute("""
CREATE TABLE IF NOT EXISTS messages (
msg_id INTEGER PRIMARY KEY,
sender_wxid TEXT,
from_wxid TEXT,
msg_type INTEGER,
content TEXT,
is_group INTEGER,
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
await self.conn.commit()
logger.debug("MessageDB 初始化完成")
async def save_message(
self,
msg_id: int,
sender_wxid: str,
from_wxid: str,
msg_type: int,
content: str,
is_group: bool
):
"""保存消息"""
try:
await self.conn.execute(
"""INSERT OR REPLACE INTO messages
(msg_id, sender_wxid, from_wxid, msg_type, content, is_group)
VALUES (?, ?, ?, ?, ?, ?)""",
(msg_id, sender_wxid, from_wxid, msg_type, content, int(is_group))
)
await self.conn.commit()
except Exception as e:
logger.error(f"保存消息失败: {e}")
async def close(self):
"""关闭连接"""
if self.conn:
await self.conn.close()