From 90f5e26d69eff3928e029df9249333ac643cd0af Mon Sep 17 00:00:00 2001 From: yawwwwwn <40122222+yawwwwwn@users.noreply.github.com> Date: Wed, 3 Apr 2019 21:54:04 +0800 Subject: [PATCH] Add log mode MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 可选只存错误信息(在 user.conf 中设置) 修复若干 json() 出错问题 解决勋章查询 bug 添加 raffleid 的输出,解决因B站错误返回造成的抽奖结果查询失败 --- OnlineHeart.py | 4 ++-- Tasks.py | 2 +- bilibili.py | 2 +- bilibiliCilent.py | 4 ++-- conf/user.conf | 6 +++++- connect.py | 4 ++-- printer.py | 17 ++++++++++++++-- statistics.py | 51 ++++++++++++++++++++++++----------------------- utils.py | 2 +- 9 files changed, 55 insertions(+), 37 deletions(-) diff --git a/OnlineHeart.py b/OnlineHeart.py index 85aab06..97a71fd 100644 --- a/OnlineHeart.py +++ b/OnlineHeart.py @@ -111,7 +111,7 @@ async def run(self): try: Printer().printer("心跳", "Info","green") response = await self.pcpost_heartbeat() - json_response = await response.json() + json_response = await response.json(content_type=None) if json_response['code'] == 3: Printer().printer(f"cookie过期,将重新登录","Error","red") login().login() @@ -122,4 +122,4 @@ async def run(self): await asyncio.sleep(300) except: await asyncio.sleep(10) - traceback.print_exc() + Printer().printer(traceback.format_exc(), "Error", "red") diff --git a/Tasks.py b/Tasks.py index bff9045..f70cf76 100644 --- a/Tasks.py +++ b/Tasks.py @@ -139,4 +139,4 @@ async def run(self): await asyncio.sleep(21600) except: await asyncio.sleep(10) - traceback.print_exc() + Printer().printer(traceback.format_exc(), "Error", "red") diff --git a/bilibili.py b/bilibili.py index 24a4738..8ec76a8 100644 --- a/bilibili.py +++ b/bilibili.py @@ -212,7 +212,7 @@ def request_load_img(self, url): async def request_fetchmedal(self): url = 'https://api.live.bilibili.com/i/api/medal?page=1&pageSize=50' - response = await self.bili_section_post(url, headers=self.dic_bilibili['pcheaders']) + response = await self.bili_section_get(url, headers=self.dic_bilibili['pcheaders']) return response def request_getkey(self): diff --git a/bilibiliCilent.py b/bilibiliCilent.py index bfcd74f..2953a8f 100644 --- a/bilibiliCilent.py +++ b/bilibiliCilent.py @@ -13,9 +13,9 @@ async def handle_1_TV_raffle(type, num, real_roomid, raffleid): await asyncio.sleep(random.uniform(0, min(num, 30))) response2 = await bilibili().get_gift_of_TV(type, real_roomid, raffleid) - Printer().printer(f"参与了房间 {real_roomid} 的广播抽奖", "Lottery", "cyan") + # Printer().printer(f"参与了房间 {real_roomid} 的广播抽奖 {raffleid}", "Lottery", "cyan") json_response2 = await response2.json(content_type=None) - Printer().printer(f"房间 {real_roomid} 广播道具抽奖状态: {json_response2['msg']}", "Lottery", "cyan") + Printer().printer(f"参与房间 {real_roomid} 广播道具抽奖 {raffleid} 状态: {json_response2['msg']}", "Lottery", "cyan") if json_response2['code'] == 0: Statistics().append_to_TVlist(raffleid, real_roomid) else: diff --git a/conf/user.conf b/conf/user.conf index 63525b2..2981c26 100644 --- a/conf/user.conf +++ b/conf/user.conf @@ -13,4 +13,8 @@ on/off = 0 # 硬币换瓜子 [doublegain_coin2silver] -on/off = 0 \ No newline at end of file +on/off = 0 + +# 保存所有运行信息到log文件,0为只保存Error和Warning信息 +[thoroughly_log] +on/off = 1 diff --git a/connect.py b/connect.py index b15ded2..292198a 100644 --- a/connect.py +++ b/connect.py @@ -55,7 +55,7 @@ async def create(self): # Printer().printer(f"[{area}分区] 房间 {roomid} 任务保持正常", "Info", "green") pass except Exception: - traceback.print_exc() + Printer().printer(traceback.format_exc(), "Error", "red") async def check_connect(self, skip_area=None): if self.tag_reconnect: @@ -133,6 +133,6 @@ async def recreate(self, area, new_roomid=None): task21 = asyncio.ensure_future(self.danmuji.HeartbeatLoop()) connect.tasks[new_roomid] = [task11, task21] except Exception: - traceback.print_exc() + Printer().printer(traceback.format_exc(), "Error", "red") # Printer().printer(f"[{area}分区] 重连任务处理完毕", "Info", "green") self.handle_area.remove(area) diff --git a/printer.py b/printer.py index 56ac4e6..9ee1214 100644 --- a/printer.py +++ b/printer.py @@ -1,11 +1,23 @@ from colorama import init from termcolor import * import time +import configloader init() class Printer(): + instance = None + + def __new__(cls, *args, **kw): + if not cls.instance: + cls.instance = super(Printer, cls).__new__(cls, *args, **kw) + fileDir = os.path.dirname(os.path.realpath('__file__')) + file_user = fileDir + "/conf/user.conf" + cls.instance.dic_user = configloader.load_user(file_user) + cls.instance.thoroughly_log = True \ + if cls.instance.dic_user['thoroughly_log']['on/off'] == "1" else False + return cls.instance def current_time(self): tmp = str( @@ -18,7 +30,8 @@ def printer(self, string, info, color,printable=True): if printable: msg = ("{:<22}{:<10}{:<20}".format(str(ctm), str(tmp), str(string))) print(colored(msg, color), flush=True) - with open("log.txt","a+",encoding="utf-8")as f: - f.write(msg+"\n") + if self.thoroughly_log or info in ["Error", "Warning"]: + with open("log.txt", "a+", encoding="utf-8") as f: + f.write(msg+"\n") else: pass diff --git a/statistics.py b/statistics.py index be619d1..451d488 100644 --- a/statistics.py +++ b/statistics.py @@ -56,30 +56,31 @@ def delete_0st_TVlist(self): del self.TV_raffleid_list[0] async def clean_TV(self): - printlist = [] - - if self.TV_raffleid_list: - for i in range(0, len(self.TV_roomid_list)): - - response = await bilibili().get_TV_result(self.TV_roomid_list[0], self.TV_raffleid_list[0]) - json_response = await response.json() - try: - - if json_response['data']['gift_id'] == '-1': - if json_response['msg'] == '正在抽奖中..': - break - else: - Printer().printer(f"房间 {self.TV_roomid_list[0]} 广播道具抽奖结果: {json_response['msg']}", - "Lottery", "cyan") - else: - data = json_response['data'] - Printer().printer(f"房间 {self.TV_roomid_list[0]} 广播道具抽奖结果: {data['gift_name']}X{data['gift_num']}", - "Lottery", "cyan") - self.add_to_result(data['gift_name'], int(data['gift_num'])) - - self.delete_0st_TVlist() - except: - print(json_response) + while len(self.TV_raffleid_list): + await asyncio.sleep(0.2) + + response = await bilibili().get_TV_result(self.TV_roomid_list[0], self.TV_raffleid_list[0]) + json_response = await response.json() + try: + if json_response['msg'] == '正在抽奖中..': + break + data = json_response['data'] + if not len(data): + # Printer().printer(f"房间 {self.TV_roomid_list[0]} 广播道具抽奖 {self.TV_raffleid_list[0]} 结果: {json_response['msg']}", + # "Lottery", "cyan") + # print('B站错误返回,报已错过') + continue + if data['gift_id'] != '-1': + Printer().printer(f"房间 {self.TV_roomid_list[0]} 广播道具抽奖 {self.TV_raffleid_list[0]} 结果: {data['gift_name']}X{data['gift_num']}", + "Lottery", "cyan") + self.add_to_result(data['gift_name'], int(data['gift_num'])) + else: + Printer().printer(f"房间 {self.TV_roomid_list[0]} 广播道具抽奖 {self.TV_raffleid_list[0]} 结果: {json_response['msg']}", + "Lottery", "cyan") + + self.delete_0st_TVlist() + except Exception: + Printer().printer(f'获取到异常抽奖结果: {json_response}', "Warning", "red") if self.monitor: check_list = list(self.monitor) @@ -109,7 +110,7 @@ async def clean_TV(self): Printer().printer(f"出现意外的监控情况,启动分区检查 {check_str}", "Info", "green") await utils.reconnect() except Exception: - traceback.print_exc() + Printer().printer(traceback.format_exc(), "Error", "red") finally: del self.monitor[roomid] diff --git a/utils.py b/utils.py index a038682..2bea52e 100644 --- a/utils.py +++ b/utils.py @@ -45,7 +45,7 @@ async def fetch_medal(printer=True): adjust_for_chinese('排名'), '勋章状态')) dic_worn = {'1': '正在佩戴', '0': '待机状态'} response = await bilibili().request_fetchmedal() - json_response = await response.json() + json_response = await response.json(content_type=None) roomid = 0 today_feed = 0 day_limit = 0