From 18d0fae5da013f5a60e1a076e5afce4aa236ff76 Mon Sep 17 00:00:00 2001 From: Zhao Zuohong <1040110848@qq.com> Date: Tue, 6 Sep 2022 16:26:47 +0800 Subject: [PATCH] :sparkles: Live room join message --- main.py | 70 ++++++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 57 insertions(+), 13 deletions(-) diff --git a/main.py b/main.py index c9b175b..e154765 100755 --- a/main.py +++ b/main.py @@ -1,11 +1,35 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- +from typing import Optional + import argparse -import asyncio import httpx from bilibili_api import live, sync + +class Broadcaster: + def __init__( + self, + key: Optional[str] = "", + host: Optional[str] = "127.0.0.1", + port: Optional[int] = 4567, + ): + self.url = f"http://{host}:{port}/v1/chat/broadcast" + self.headers = {"key": key} if key else {} + + async def broadcast_msg(self, msg: str): + async with httpx.AsyncClient() as client: + response = await client.post( + self.url, + headers=self.headers, + data={"message": msg}, + ) + if response.status_code != 200: + print(msg) + print(response.text) + + if __name__ == "__main__": parser = argparse.ArgumentParser( description="将 B 站直播间弹幕通过 ServerTap 转发到 Spigot 服务器" @@ -17,23 +41,43 @@ if __name__ == "__main__": args = parser.parse_args() room = live.LiveDanmaku(args.room) - headers = {"key": args.key} if args.key else {} + key = args.key if args.key else "" host = args.host if args.host else "127.0.0.1" port = args.port if args.port else "4567" + bc = Broadcaster(key, host, port) + + mc_color = { + "dark_red": "§4", + "red": "§c", + "gold": "§6", + "yellow": "§e", + "dark_green": "§2", + "green": "§a", + "aqua": "§b", + "dark_aqua": "§3", + "dark_blue": "§1", + "blue": "§9", + "light_purple": "§d", + "dark_purple": "§5", + "white": "§f", + "gray": "§7", + "dark_gray": "§8", + "black": "§0", + } + msg_prefix = f"[{mc_color['light_purple']}BiliBili{mc_color['white']}]" + @room.on("DANMU_MSG") - async def on_danmaku(event): + async def _(event): danmu = event["data"]["info"][1] user = event["data"]["info"][2][1] - msg = f"[直播间弹幕]<{user}>{danmu}" - async with httpx.AsyncClient() as client: - response = await client.post( - f"http://{host}:{port}/v1/chat/broadcast", - headers=headers, - data={"message": msg}, - ) - if response.status_code != 200: - print(msg) - print(response.text) + msg = f"{msg_prefix}{mc_color['yellow']}{user}{mc_color['white']}: {danmu}" + await bc.broadcast_msg(msg) + + @room.on("INTERACT_WORD") + async def _(event): + user = event["data"]["data"]["uname"] + msg = f"{msg_prefix}{mc_color['yellow']}{user}进入了直播间" + await bc.broadcast_msg(msg) sync(room.connect())