From 4aefb184352a0bb5777dc4b8c952bd7f863a573c Mon Sep 17 00:00:00 2001 From: "Mr.Xia" <1424473282@qq.com> Date: Mon, 6 Apr 2026 23:28:23 +0800 Subject: [PATCH] =?UTF-8?q?refactor(room=5Fstore):=20=E5=B0=86=E4=B8=8A?= =?UTF-8?q?=E6=AC=A1=E9=A9=AC=E5=90=8D=E5=AD=98=E5=82=A8=E4=BB=8E=E5=86=85?= =?UTF-8?q?=E5=AD=98=E8=BF=81=E7=A7=BB=E8=87=B3=E6=95=B0=E6=8D=AE=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 移除内存字典 `_last_horse_names`,改为使用 SQLite 表 `user_horse_names` - 修改 `get_last_horse_name` 和 `set_last_horse_name` 方法以操作数据库 - 提升数据持久化能力,防止重启后数据丢失 --- .../plugins/group_horse_racing/room_store.py | 24 ++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/danding_bot/plugins/group_horse_racing/room_store.py b/danding_bot/plugins/group_horse_racing/room_store.py index c62fc4d..df2d403 100644 --- a/danding_bot/plugins/group_horse_racing/room_store.py +++ b/danding_bot/plugins/group_horse_racing/room_store.py @@ -13,7 +13,6 @@ class RoomStore: self.config = config self.rooms: dict[str, Room] = {} self._locks: dict[str, asyncio.Lock] = {} - self._last_horse_names: dict[str, str] = {} self.db_path = Path(config.RACE_DB_FILE) self.db_path.parent.mkdir(parents=True, exist_ok=True) self._init_db() @@ -48,6 +47,13 @@ class RoomStore: ) """) + cursor.execute(""" + CREATE TABLE IF NOT EXISTS user_horse_names ( + user_id TEXT PRIMARY KEY, + horse_name TEXT NOT NULL + ) + """) + conn.commit() conn.close() @@ -74,10 +80,22 @@ class RoomStore: del self.rooms[scope] def get_last_horse_name(self, user_id: str) -> Optional[str]: - return self._last_horse_names.get(user_id) + conn = sqlite3.connect(self.db_path) + cursor = conn.cursor() + cursor.execute("SELECT horse_name FROM user_horse_names WHERE user_id = ?", (user_id,)) + row = cursor.fetchone() + conn.close() + return row[0] if row else None def set_last_horse_name(self, user_id: str, horse_name: str): - self._last_horse_names[user_id] = horse_name + conn = sqlite3.connect(self.db_path) + cursor = conn.cursor() + cursor.execute( + "INSERT OR REPLACE INTO user_horse_names (user_id, horse_name) VALUES (?, ?)", + (user_id, horse_name), + ) + conn.commit() + conn.close() def _save_snapshot(self, room: Room): """Save room snapshot to database."""