From 5cf5cbf7137a652880f668ddac3d9e322db0d442 Mon Sep 17 00:00:00 2001 From: liuwei Date: Tue, 24 Feb 2026 16:40:51 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=97=E9=B1=BC=E5=8A=A0=E5=85=A5=E4=BA=86?= =?UTF-8?q?=E4=B8=80=E4=B8=AA=E5=BC=B9=E5=B9=95=E8=AE=B0=E5=BD=95=E5=8A=9F?= =?UTF-8?q?=E8=83=BD=E3=80=82=E4=BC=9A=E8=87=AA=E5=8A=A8=E8=AE=B0=E5=BD=95?= =?UTF-8?q?=E5=BC=80=E6=92=AD=E7=9A=84=E5=BC=B9=E5=B9=95=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugins/douyu/main.py | 40 ++++++++++++++++++++++++++++++++++------ 1 file changed, 34 insertions(+), 6 deletions(-) diff --git a/plugins/douyu/main.py b/plugins/douyu/main.py index 78c982f..b0c8172 100644 --- a/plugins/douyu/main.py +++ b/plugins/douyu/main.py @@ -30,6 +30,10 @@ class DouyuDanmuRecorder: self._thread: Optional[threading.Thread] = None self._stop_event = threading.Event() self._ws: Optional[websocket.WebSocketApp] = None + self._buffer: List[str] = [] + self._buffer_limit = 50 + self._buffer_date: Optional[str] = None + self._lock = threading.Lock() def _encode(self, msg: str) -> bytes: content = msg.encode("utf-8") + b"\x00" @@ -82,12 +86,35 @@ class DouyuDanmuRecorder: if fan_group: output += f" / {fan_group} Lv{fan_level}" output += f"):{txt}" - date_str = datetime.now().strftime("%Y%m%d") - dir_path = os.path.join("temp", "douyu_danmu", date_str) - os.makedirs(dir_path, exist_ok=True) - file_name = os.path.join(dir_path, f"{self.room_id}_{date_str}.txt") - with open(file_name, "a", encoding="utf-8") as f: - f.write(output + "\n") + self._append_and_maybe_flush(output) + + def _flush_locked(self): + if not self._buffer or self._buffer_date is None: + return + dir_path = os.path.join("temp", "douyu_danmu", self._buffer_date) + os.makedirs(dir_path, exist_ok=True) + file_name = os.path.join(dir_path, f"{self.room_id}_{self._buffer_date}.txt") + data = "\n".join(self._buffer) + "\n" + with open(file_name, "a", encoding="utf-8") as f: + f.write(data) + self._buffer.clear() + + def _append_and_maybe_flush(self, line: str): + now = datetime.now() + date_str = now.strftime("%Y%m%d") + with self._lock: + if self._buffer_date is None: + self._buffer_date = date_str + elif date_str != self._buffer_date: + self._flush_locked() + self._buffer_date = date_str + self._buffer.append(line) + if len(self._buffer) >= self._buffer_limit: + self._flush_locked() + + def _flush(self): + with self._lock: + self._flush_locked() def _on_open(self, ws): ws.send(self._encode(f"type@=loginreq/roomid@={self.room_id}/dmbt@=chrome/dmbv@=0/")) @@ -158,6 +185,7 @@ class DouyuDanmuRecorder: self._thread.start() def stop(self): + self._flush() self._stop_event.set() if self._ws: try: