Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
HsiangNianian committed Dec 12, 2022
1 parent 8e0c5c4 commit f779159
Show file tree
Hide file tree
Showing 9 changed files with 93 additions and 76 deletions.
6 changes: 3 additions & 3 deletions OlivaBiliLive/app.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
"name": "OlivaBiliLive",
"author": "简律纯",
"namespace": "OlivaBiliLive",
"info": "简介:\n一个B站机器人插件,尤其作用于弹幕互动。\n\nGithub:\ncypress0522/OlivaBiliLive",
"info": "简介:\n一个B站弹幕接口插件",
"priority": 30000,
"version": "0.2.0-alpha",
"svn": 15,
"version": "0.2.1-alpha",
"svn": 16,
"compatible_svn": 101,
"message_mode": "olivos_string",
"support": [
Expand Down
36 changes: 19 additions & 17 deletions OlivaBiliLive/bilibili_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

user_cookies = cookiejar.CookieJar()

def logging_info(msg:str,level=2):
def logg(msg:str,level=2):
OlivaBiliLive.main.GlobalProc.log(level,f"[OlivaBiliLive] : {msg}")

"""
Expand All @@ -30,7 +30,7 @@ def logging_info(msg:str,level=2):
"""
async def login(session: ClientSession): # -> bool:
if get_cookies('bili_jct') != None:
logging_info("已使用上次登录配置登录。")
logg("已使用上次登录配置登录。")

return True
try:
Expand All @@ -44,35 +44,37 @@ async def login(session: ClientSession): # -> bool:
url = res['data']['url']
qr = qrcode.QRCode()

logging_info("请扫描下方二维码登录... 或者到根目录(也就是OlivOS.exe所在目录)寻找 OlivaBiliLive_qrcode.png)")
logg("请扫描下方二维码登录... 或者到根目录(也就是OlivOS.exe所在目录)寻找 OlivaBiliLive_qrcode.png)")

qr.add_data(url)
qr.print_ascii(invert=True)
qr.make_image().save('OlivaBiliLive_qrcode.png')

os.startfile('OlivaBiliLive_qrcode.png') # Linux方案: subprocess.call(["xdg-open",file_path])

while True:

await asyncio.sleep(5)

if time.time() > outdated:

logging_info("已超时。")
logg("已超时。")

return False # 登入失敗

res = await _post(session, CHECK_LOGIN_RESULT, oauthKey=authKey)

if res['status']:
logging_info('登入成功。')
logg('登入成功。')
return True
else:
code = res['data']
if code in [-1, -2]:
logging_info(f'登入失敗: {res["message"]}')
logg(f'登入失敗: {res["message"]}')
return False

except ClientResponseError as e:
logging_info(f'请求时出现错误: {e}')
logg(f'请求时出现错误: {e}')
return False
finally:
os.remove('OlivaBiliLive_qrcode.png')
Expand All @@ -90,7 +92,7 @@ async def send_danmu(**fields) -> bool:
)
return 'data' in res
except Exception as e:
logging_info(f'发送弹幕时出现错误: {e}')
logg(f'发送弹幕时出现错误: {e}')
return False

def get_cookies(name: str) -> any:
Expand All @@ -113,19 +115,19 @@ async def mute_user(tuid: int, roomid: int) -> bool:
)
return res['code'] == 0
except Exception as e:
logging_info(f'禁言时出现错误: {e}')
logg(f'禁言时出现错误: {e}')
return False

async def room_slient(roomid: int, slientType: str, level: int, minute: int) -> bool:

type_availables = ['off', 'medal', 'member', 'level']
if slientType not in type_availables:
logging_info(f'未知的禁言类型: {slientType} ({type_availables})')
logg(f'未知的禁言类型: {slientType} ({type_availables})')
return False

minute_available = [0, 30, 60]
if minute not in minute_available:
logging_info(f'未知的静音时间: {minute} ({minute_available})')
logg(f'未知的静音时间: {minute} ({minute_available})')
return False

token = get_cookies('bili_jct')
Expand All @@ -142,7 +144,7 @@ async def room_slient(roomid: int, slientType: str, level: int, minute: int) ->
)
return res['code'] == 0
except Exception as e:
logging_info(f'房间静音时出现错误: {e}')
logg(f'房间静音时出现错误: {e}')
return False

async def add_badword(roomid: int, keyword: str) -> bool:
Expand All @@ -158,7 +160,7 @@ async def add_badword(roomid: int, keyword: str) -> bool:
)
return res['code'] == 0
except Exception as e:
logging_info(f'添加屏蔽字时出现错误: {e}')
logg(f'添加屏蔽字时出现错误: {e}')
return False

async def remove_badword(roomid: int, keyword: str) -> bool:
Expand All @@ -174,7 +176,7 @@ async def remove_badword(roomid: int, keyword: str) -> bool:
)
return res['code'] == 0
except Exception as e:
logging_info(f'删除屏蔽字时出现错误: {e}')
logg(f'删除屏蔽字时出现错误: {e}')
return False

def logout():
Expand All @@ -189,7 +191,7 @@ async def _get(session: ClientSession, url: str):
async with session.get(url) as resp:
resp.raise_for_status()
data = await resp.json()
logging_info(data)
logg(data)
if 'code' in data and data['code'] != 0:
raise Exception(data['message'] if 'message' in data else data['code'])
return data
Expand All @@ -199,11 +201,11 @@ async def _post(session: ClientSession, url: str, **data):
form = aiohttp.FormData()
for (k, v) in data.items():
form.add_field(k, v)
logging_info(f'正在发送 POST 请求: {url}, 内容: {data}')
logg(f'正在发送 POST 请求: {url}, 内容: {data}')
async with session.post(url, data=form) as resp:
resp.raise_for_status()
data = await resp.json()
logging_info(data)
logg(data)
if 'code' in data and data['code'] != 0:
raise Exception(data['message'] if 'message' in data else data['code'])
return data
Expand Down
12 changes: 6 additions & 6 deletions OlivaBiliLive/bilibili_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@
from .bilibili_api import add_badword, mute_user, remove_badword, room_slient, send_danmu, user_cookies
from .plugin import BotPlugin, DanmakuMessage, DanmakuPosition, SuperChatMessage

def logging_info(msg:str,level=2):
def logg(msg:str,level=2):
OlivaBiliLive.main.GlobalProc.log(level,f"[OlivaBiliLive] : {msg}")

class OlivaBiliLiveBot(BLiveClient):
class BiliLiveBot(BLiveClient):

BOT_PLUGINS: List[BotPlugin] = []

Expand Down Expand Up @@ -74,20 +74,20 @@ async def remove_badword(self, badword: str) -> bool:
async def on_command_received(self, cmd, data):
if self.is_bot_itself(cmd, data):
return
logging_info(f'从房间 {self.room_id} 收到指令: {cmd}')
logg(f'从房间 {self.room_id} 收到指令: {cmd}')
for bot_plugin in self.BOT_PLUGINS:
try:
await bot_plugin.on_command_received(cmd, data)
except Exception as e:
logging_info(f'执行插件 {get_type_name(bot_plugin)} 时出现错误({get_type_name(e)}): {e}')
logg(f'执行插件 {get_type_name(bot_plugin)} 时出现错误({get_type_name(e)}): {e}')

async def _on_receive_popularity(self, popularity: int):
logging_info(f'从房间 {self.room_id} 收到人气值: {popularity}')
logg(f'从房间 {self.room_id} 收到人气值: {popularity}')
for bot_plugin in self.BOT_PLUGINS:
try:
await bot_plugin.on_receive_popularity(popularity)
except Exception as e:
logging_info(f'执行插件 {get_type_name(bot_plugin)} 时出现错误({get_type_name(e)}): {e}')
logg(f'执行插件 {get_type_name(bot_plugin)} 时出现错误({get_type_name(e)}): {e}')


# 其餘的自己過濾
Expand Down
34 changes: 17 additions & 17 deletions OlivaBiliLive/blivedm.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

import aiohttp

def logging_info(msg:str,level=2):
def logg(msg:str,level=2):
OlivaBiliLive.main.GlobalProc.log(level,f"[OlivaBiliLive] : {msg}")

ROOM_INIT_URL = 'https://api.live.bilibili.com/xlive/web-room/v1/index/getInfoByRoom'
Expand Down Expand Up @@ -151,10 +151,10 @@ def start(self):

def __on_message_loop_done(self, future):
self._future = None
logging_info(f'room {self.room_id} 消息协程结束')
logg(f'room {self.room_id} 消息协程结束')
exception = future.exception()
if exception is not None:
logging_info(f'room {self.room_id} 消息协程异常结束:{sys.exc_info(type(exception), exception, exception.__traceback__)}')
logg(f'room {self.room_id} 消息协程异常结束:{sys.exc_info(type(exception), exception, exception.__traceback__)}')

def stop(self):
"""
Expand Down Expand Up @@ -189,16 +189,16 @@ async def _init_room_id_and_owner(self):
async with self._session.get(ROOM_INIT_URL, params={'room_id': self._tmp_room_id},
ssl=self._ssl) as res:
if res.status != 200:
logging_info(f'room {self._tmp_room_id} init_room失败:{res.status, res.reason}')
logg(f'room {self._tmp_room_id} init_room失败:{res.status, res.reason}')
return False
data = await res.json()
if data['code'] != 0:
logging_info(f'room {self._tmp_room_id} init_room失败: {data["message"]}')
logg(f'room {self._tmp_room_id} init_room失败: {data["message"]}')
return False
if not self._parse_room_init(data['data']):
return False
except (aiohttp.ClientConnectionError, asyncio.TimeoutError):
logging_info(f'room {self._tmp_room_id} init_room失败:')
logg(f'room {self._tmp_room_id} init_room失败:')
return False
return True

Expand All @@ -214,24 +214,24 @@ async def _init_host_server(self):
async with self._session.get(DANMAKU_SERVER_CONF_URL, params={'id': self._room_id, 'type': 0},
ssl=self._ssl) as res:
if res.status != 200:
logging_info(f'room {self._room_id} getConf失败: {res.status , res.reason}')
logg(f'room {self._room_id} getConf失败: {res.status , res.reason}')
return False
data = await res.json()
if data['code'] != 0:
logging_info(f'room {self._room_id} getConf失败: {data["message"]}')
logg(f'room {self._room_id} getConf失败: {data["message"]}')
return False
if not self._parse_danmaku_server_conf(data['data']):
return False
except (aiohttp.ClientConnectionError, asyncio.TimeoutError):
logging_info(f'room {self._room_id} getConf失败:')
logg(f'room {self._room_id} getConf失败:')
return False
return True

def _parse_danmaku_server_conf(self, data):
self._host_server_list = data['host_list']
self._host_server_token = data['token']
if not self._host_server_list:
logging_info(f'room {self._room_id} getConf失败:host_server_list为空')
logg(f'room {self._room_id} getConf失败:host_server_list为空')
return False
return True

Expand Down Expand Up @@ -286,24 +286,24 @@ async def _message_loop(self):
async for message in websocket: # type: aiohttp.WSMessage
retry_count = 0
if message.type != aiohttp.WSMsgType.BINARY:
logging_info(f'room {self.room_id} 未知的websocket消息:type={message.type, message.data}')
logg(f'room {self.room_id} 未知的websocket消息:type={message.type, message.data}')
continue

try:
await self._handle_message(message.data)
except asyncio.CancelledError:
logging_info(f"{self.room_id} 程序被強制取消。")
logg(f"{self.room_id} 程序被強制取消。")
raise
except Exception:
logging_info(f'room {self.room_id} 处理消息时发生错误:')
logg(f'room {self.room_id} 处理消息时发生错误:')

except asyncio.CancelledError:
break
except (aiohttp.ClientConnectionError, asyncio.TimeoutError):
# 重连
pass
except ssl_.SSLError:
logging_info('SSL错误:')
logg('SSL错误:')
# 证书错误时无法重连
break
finally:
Expand All @@ -313,7 +313,7 @@ async def _message_loop(self):
self._heartbeat_timer_handle = None

retry_count += 1
logging_info(f'room {self.room_id} 掉线重连中 {retry_count}')
logg(f'room {self.room_id} 掉线重连中 {retry_count}')
try:
await asyncio.sleep(1)
except asyncio.CancelledError:
Expand Down Expand Up @@ -348,15 +348,15 @@ async def _handle_message(self, data):
body = json.loads(body.decode('utf-8'))
await self._handle_command(body)
except Exception:
logging_info(f'body: {body}')
logg(f'body: {body}')
raise

elif header.operation == Operation.AUTH_REPLY:
await self._websocket.send_bytes(self._make_packet({}, Operation.HEARTBEAT))

else:
body = data[offset + HEADER_STRUCT.size: offset + header.pack_len]
logging_info(f'room {self.room_id,} 未知包类型:operation={header.operation, header, body}')
logg(f'room {self.room_id,} 未知包类型:operation={header.operation, header, body}')

offset += header.pack_len

Expand Down
4 changes: 4 additions & 0 deletions OlivaBiliLive/config/mute.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
bad_danmaku:
- 主播是个大伞兵
- 主播你寄吧谁啊
- 主播NMSL
2 changes: 1 addition & 1 deletion OlivaBiliLive/file_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
'roomid': 21752074
}

def logging_info(msg:str,level=2):
def logg(msg:str,level=2):
OlivaBiliLive.main.GlobalProc.log(level,f"[OlivaBiliLive] : {msg}")

def make_folder(folder: str) -> bool:
Expand Down
Loading

0 comments on commit f779159

Please sign in to comment.