blive/example/with_fastapi.py

48 lines
1.1 KiB
Python
Raw Normal View History

2022-11-26 12:40:15 +08:00
import uvicorn
from fastapi import FastAPI
2022-04-26 13:01:01 +08:00
from blive import BLiver, Events
from blive.msg import DanMuMsg
app = FastAPI()
BLIVER_POOL = {}
2022-04-26 13:01:01 +08:00
def create_bliver(roomid):
# 定义弹幕事件handler
async def listen(ctx):
danmu = DanMuMsg(ctx.body)
print(
f'\n{danmu.sender.name} ({danmu.sender.medal.medal_name}:{danmu.sender.medal.medal_level}): "{danmu.content}"\n'
)
2022-04-26 13:01:01 +08:00
b = BLiver(roomid)
2022-04-26 13:01:01 +08:00
b.register_handler(Events.DANMU_MSG, listen)
return b
@app.get("/create")
2022-04-26 13:01:01 +08:00
async def create_new_bliver(roomid: int):
room = BLIVER_POOL.get(roomid, None)
if not room:
b = create_bliver(roomid)
BLIVER_POOL[roomid] = b.run_as_task()
2022-04-26 13:01:01 +08:00
return {"msg": "创建一个新直播间弹幕监听成功"}
@app.get("/del")
2022-04-26 13:01:01 +08:00
async def rm_bliver(roomid: int):
room = BLIVER_POOL.get(roomid, None)
if room:
room.cancel()
2022-08-23 11:57:14 +08:00
BLIVER_POOL.pop(roomid)
2022-04-26 13:01:01 +08:00
return {"msg": "移除直播间弹幕监听成功"}
@app.get("/show")
async def show():
return list(BLIVER_POOL.keys())
2022-11-26 12:40:15 +08:00
if __name__ == "__main__":
uvicorn.run(app)