blivechat/plugins/msg-logging/listener.py

140 lines
4.5 KiB
Python
Raw Normal View History

2023-11-05 16:29:11 +08:00
# -*- coding: utf-8 -*-
import __main__
2023-11-05 21:42:43 +08:00
import datetime
2023-11-05 16:29:11 +08:00
import logging
2023-11-05 21:42:43 +08:00
import os
2023-11-08 00:21:17 +08:00
import sys
2023-11-05 16:29:11 +08:00
from typing import *
import blcsdk
import blcsdk.models as sdk_models
2023-11-05 21:42:43 +08:00
import config
2023-11-05 16:29:11 +08:00
2023-11-08 00:21:17 +08:00
logger = logging.getLogger('msg-logging.' + __name__)
2023-11-05 16:29:11 +08:00
_msg_handler: Optional['MsgHandler'] = None
2023-11-05 21:42:43 +08:00
_id_room_dict: Dict[int, 'Room'] = {}
2023-11-05 16:29:11 +08:00
async def init():
global _msg_handler
_msg_handler = MsgHandler()
blcsdk.set_msg_handler(_msg_handler)
2023-11-08 00:21:17 +08:00
# 创建已有的房间。这一步失败了也没关系,只是有消息时才会创建文件
try:
blc_rooms = await blcsdk.get_rooms()
for blc_room in blc_rooms:
if blc_room.room_id is not None:
_get_or_add_room(blc_room.room_id)
except blcsdk.SdkError:
pass
2023-11-05 21:42:43 +08:00
def shut_down():
blcsdk.set_msg_handler(None)
2023-11-08 00:21:17 +08:00
while len(_id_room_dict) != 0:
2023-11-05 21:42:43 +08:00
room_id = next(iter(_id_room_dict))
_del_room(room_id)
2023-11-05 16:29:11 +08:00
class MsgHandler(blcsdk.BaseHandler):
2023-11-08 00:21:17 +08:00
def on_client_stopped(self, client: blcsdk.BlcPluginClient, exception: Optional[Exception]):
2023-11-05 16:29:11 +08:00
logger.info('blivechat disconnected')
__main__.start_shut_down()
2023-11-08 00:21:17 +08:00
def _on_open_plugin_admin_ui(
self, client: blcsdk.BlcPluginClient, message: sdk_models.OpenPluginAdminUiMsg, extra: sdk_models.ExtraData
):
if sys.platform == 'win32':
os.startfile(config.LOG_PATH)
else:
logger.info('Log path is "%s"', config.LOG_PATH)
def _on_room_init(
self, client: blcsdk.BlcPluginClient, message: sdk_models.RoomInitMsg, extra: sdk_models.ExtraData
):
if extra.is_from_plugin:
return
2023-11-05 21:42:43 +08:00
if message.is_success:
_get_or_add_room(extra.room_id)
2023-11-08 00:21:17 +08:00
def _on_del_room(self, client: blcsdk.BlcPluginClient, message: sdk_models.DelRoomMsg, extra: sdk_models.ExtraData):
if extra.is_from_plugin:
return
2023-11-05 21:42:43 +08:00
if extra.room_id is not None:
_del_room(extra.room_id)
2023-11-08 00:21:17 +08:00
def _on_add_text(self, client: blcsdk.BlcPluginClient, message: sdk_models.AddTextMsg, extra: sdk_models.ExtraData):
if extra.is_from_plugin:
return
2023-11-05 21:42:43 +08:00
room = _get_or_add_room(extra.room_id)
room.log(f'[dm] {message.author_name}{message.content}')
2023-11-08 00:21:17 +08:00
def _on_add_gift(self, client: blcsdk.BlcPluginClient, message: sdk_models.AddGiftMsg, extra: sdk_models.ExtraData):
if extra.is_from_plugin:
return
2023-11-05 21:42:43 +08:00
room = _get_or_add_room(extra.room_id)
room.log(
f'[gift] {message.author_name} 赠送了 {message.gift_name} x {message.num}'
f'总价 {message.total_coin / 1000}'
)
def _on_add_member(
2023-11-08 00:21:17 +08:00
self, client: blcsdk.BlcPluginClient, message: sdk_models.AddMemberMsg, extra: sdk_models.ExtraData
2023-11-05 21:42:43 +08:00
):
2023-11-08 00:21:17 +08:00
if extra.is_from_plugin:
return
2023-11-05 21:42:43 +08:00
room = _get_or_add_room(extra.room_id)
if message.privilege_type == sdk_models.GuardLevel.LV1:
guard_name = '舰长'
elif message.privilege_type == sdk_models.GuardLevel.LV2:
guard_name = '提督'
elif message.privilege_type == sdk_models.GuardLevel.LV3:
guard_name = '总督'
else:
guard_name = '未知舰队等级'
# TODO 可以加上时长
room.log(f'[guard] {message.author_name} 购买了 {guard_name}')
def _on_add_super_chat(
2023-11-08 00:21:17 +08:00
self, client: blcsdk.BlcPluginClient, message: sdk_models.AddSuperChatMsg, extra: sdk_models.ExtraData
2023-11-05 21:42:43 +08:00
):
2023-11-08 00:21:17 +08:00
if extra.is_from_plugin:
return
2023-11-05 21:42:43 +08:00
room = _get_or_add_room(extra.room_id)
room.log(f'[superchat] {message.author_name} 发送了 {message.price} 元的醒目留言:{message.content}')
def _get_or_add_room(room_id):
ctx = _id_room_dict.get(room_id, None)
if ctx is None:
2023-11-08 00:21:17 +08:00
if room_id is None:
raise TypeError('room_id is None')
2023-11-05 21:42:43 +08:00
ctx = _id_room_dict[room_id] = Room(room_id)
return ctx
def _del_room(room_id):
ctx = _id_room_dict.pop(room_id, None)
if ctx is not None:
ctx.close()
2023-11-05 16:29:11 +08:00
2023-11-05 21:42:43 +08:00
class Room:
def __init__(self, room_id):
cur_time = datetime.datetime.now()
time_str = cur_time.strftime('%Y%m%d_%H%M%S')
2023-11-08 00:21:17 +08:00
filename = f'room_{room_id}-{time_str}.txt'
self._file = open(os.path.join(config.LOG_PATH, filename), 'a', encoding='utf-8-sig')
2023-11-05 16:29:11 +08:00
2023-11-05 21:42:43 +08:00
def close(self):
2023-11-08 00:21:17 +08:00
self._file.close()
2023-11-05 16:29:11 +08:00
2023-11-05 21:42:43 +08:00
def log(self, content):
cur_time = datetime.datetime.now()
time_str = cur_time.strftime('%Y-%m-%d %H:%M:%S')
text = f'{time_str} {content}\n'
2023-11-08 00:21:17 +08:00
self._file.write(text)
self._file.flush()