斗鱼加入了一个弹幕记录功能。会自动记录开播的弹幕信息

This commit is contained in:
liuwei
2026-02-24 16:40:51 +08:00
parent eabea2b4aa
commit 5cf5cbf713

View File

@@ -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: