48 lines
1.2 KiB
Python
48 lines
1.2 KiB
Python
import asyncio
|
|
import threading
|
|
from typing import Callable, Awaitable
|
|
|
|
import redis
|
|
|
|
room_set_key = "bilibili:live:danmu:room_set"
|
|
r: redis.Redis | None = None
|
|
on_room_changed: Callable[[list[int]], Awaitable[None]] | None = None
|
|
|
|
|
|
async def init(redis_conf: dict | None) -> None:
|
|
global r
|
|
|
|
if redis_conf is None:
|
|
return
|
|
|
|
r = redis.Redis(
|
|
host=redis_conf.get("host", "127.0.0.1"),
|
|
port=redis_conf.get("port", 6379),
|
|
db=redis_conf.get("port", 0),
|
|
)
|
|
|
|
asyncio.create_task(_subscribe_redis_async())
|
|
|
|
|
|
def get_room_list() -> list[int]:
|
|
if r is None:
|
|
return []
|
|
|
|
return [int(room_id) for room_id in r.smembers(room_set_key)]
|
|
|
|
|
|
def _subscribe_redis():
|
|
loop = asyncio.new_event_loop()
|
|
asyncio.set_event_loop(loop)
|
|
loop.run_until_complete(_subscribe_redis_async())
|
|
loop.close()
|
|
|
|
|
|
async def _subscribe_redis_async():
|
|
p = r.pubsub()
|
|
p.subscribe(f"__keyspace@0__:{room_set_key}")
|
|
while p.subscribed:
|
|
msg = await asyncio.to_thread(p.get_message, ignore_subscribe_messages=True, timeout=1)
|
|
if msg and on_room_changed is not None:
|
|
await on_room_changed(get_room_list())
|