Live room join message

This commit is contained in:
zhbaor 2022-09-06 16:26:47 +08:00
parent f44a82c6bd
commit 18d0fae5da

70
main.py
View file

@ -1,11 +1,35 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from typing import Optional
import argparse import argparse
import asyncio
import httpx import httpx
from bilibili_api import live, sync 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__": if __name__ == "__main__":
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
description="将 B 站直播间弹幕通过 ServerTap 转发到 Spigot 服务器" description="将 B 站直播间弹幕通过 ServerTap 转发到 Spigot 服务器"
@ -17,23 +41,43 @@ if __name__ == "__main__":
args = parser.parse_args() args = parser.parse_args()
room = live.LiveDanmaku(args.room) 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" host = args.host if args.host else "127.0.0.1"
port = args.port if args.port else "4567" 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") @room.on("DANMU_MSG")
async def on_danmaku(event): async def _(event):
danmu = event["data"]["info"][1] danmu = event["data"]["info"][1]
user = event["data"]["info"][2][1] user = event["data"]["info"][2][1]
msg = f"[直播间弹幕]<{user}>{danmu}" msg = f"{msg_prefix}{mc_color['yellow']}{user}{mc_color['white']}: {danmu}"
async with httpx.AsyncClient() as client: await bc.broadcast_msg(msg)
response = await client.post(
f"http://{host}:{port}/v1/chat/broadcast", @room.on("INTERACT_WORD")
headers=headers, async def _(event):
data={"message": msg}, user = event["data"]["data"]["uname"]
) msg = f"{msg_prefix}{mc_color['yellow']}{user}进入了直播间"
if response.status_code != 200: await bc.broadcast_msg(msg)
print(msg)
print(response.text)
sync(room.connect()) sync(room.connect())