async def link_sign(): json_rsp = await bilibili.get_grouplist() printer.warn(json_rsp) list_check = json_rsp['data']['list'] for i in list_check: asyncio.ensure_future(Sign1Group(i['group_id'], i['owner_uid'])) BiliTimer.call_after(link_sign, 21600)
async def ReceiveMessageLoop(self): while True: bytes_datas = await self.ReadSocketData() if bytes_datas is None: break len_read = 0 len_bytes_datas = len(bytes_datas) while len_read != len_bytes_datas: state = None split_header = self.structer.unpack(bytes_datas[len_read:16 + len_read]) len_data, len_header, ver, opt, seq = split_header remain_data = bytes_datas[len_read + 16:len_read + len_data] # 人气值/心跳 3s间隔 if opt == 3: # self._UserCount, = struct.unpack('!I', remain_data) printer.debug(f'弹幕心跳检测{self.area_id}') # cmd elif opt == 5: messages = remain_data.decode('utf-8') dic = json.loads(messages) state = self.loop_func(dic) # 握手确认 elif opt == 8: printer.info([f'{self.area_id}号弹幕监控进入房间({self.roomid})'], True) else: printer.warn(bytes_datas[len_read:len_read + len_data]) if state is not None and not state: return len_read += len_data
async def _read_one(self) -> bool: header = await self._conn.read_bytes(4) # 本函数对bytes进行相关操作,不特别声明,均为bytes if header is None: return False len_body, = self.header_struct.unpack_from(header) # 心跳回复 if not len_body: return True body = await self._conn.read_json(len_body) if body is None: return False json_data = body data_type = json_data['type'] if data_type == 'raffle': return self.handle_danmu(json_data['data']) # 握手确认 elif data_type == 'entered': print(f'{self._area_id}号数据连接确认建立连接({self._key})') elif data_type == 'error': warn(f'{self._area_id}号数据连接发生致命错误{json_data}') await asyncio.sleep(1.0) return False return True
async def check_handle(self): while True: if self._waiting_pause is not None: print(f'暂停启动实物抽奖查找参与循环,等待RESUME指令') await self._waiting_pause curr_time = utils.curr_time() results = substance_raffle_sql.select_rafflestatus( -1, (curr_time - 45, curr_time + 90))[:5] print('正在查找需要参与的实物抽奖:', results) for substance_raffle_status in results: print(substance_raffle_status) aid = substance_raffle_status.aid number = substance_raffle_status.number is_exist = await notifier.exec_func( SubstanceRaffleUtilsTask.check, aid) if not is_exist: substance_raffle_sql.del_from_substanceraffle_status_table( aid, number) printer.warn(f'{substance_raffle_status}消失了。。。。。') continue print(f'{aid}({number})的实物抽奖正在参与') await notifier.exec_task(SubstanceRaffleJoinTask, substance_raffle_status) substance_raffle_sql.set_rafflestatus_handle_status( 1, aid, number) print(f'{aid}({number})的实物抽奖参与完毕') if not results: await asyncio.sleep(60)
def list_owned_items(data): """Display a list of owned items.""" owned_items = [item["name"] for item in data["items"].values() if "owned" in item["attributes"]] if len(owned_items) == 0: printer.warn(data["prefix"], "You don't own any items, better go buy some in the shop~!") else: printer.yard(data["prefix"], "You currently own a {0}".format(", and a ".join(owned_items)))
async def _req(self, parse_rsp, method, url, ok_status_codes=None, **kwargs): if ok_status_codes is None: ok_status_codes = self.DEFAULT_OK_STATUS_CODES async with sem: i = 0 while True: i += 1 if i >= 10: printer.warn(f'反复请求多次未成功, {url}, {kwargs}') await asyncio.sleep(0.75) try: async with self.session.request(method, url, **kwargs) as rsp: if rsp.status in ok_status_codes: body = await parse_rsp(rsp) if body: # 有时候是 None 或空,直接屏蔽。read 或 text 类似,禁止返回空的东西 return body elif rsp.status in (412, 403): printer.warn(f'403频繁, {url}, {kwargs}') raise ForbiddenError(msg=url) except asyncio.CancelledError: raise except ForbiddenError: raise except: # print('当前网络不好,正在重试,请反馈开发者!!!!') print(sys.exc_info()[0], sys.exc_info()[1], url)
async def Daily_bag(): json_response = await bilibili.get_dailybag() # no done code printer.warn(json_response) for i in json_response['data']['bag_list']: printer.info(["# 获得-" + i['bag_name'] + "-成功"]) BiliTimer.call_after(Daily_bag, 21600)
async def check_handle(self): while True: curr_time = utils.curr_time() results = substance_raffle_sql.select_rafflestatus( -1, (curr_time - 45, curr_time + 90))[:5] printer.info(['正在查找需要参与的实物抽奖:', results], True) for substance_raffle_status in results: print(substance_raffle_status) aid = substance_raffle_status.aid number = substance_raffle_status.number is_exist = await notifier.exec_func( -1, SubstanceRaffleHandlerTask.check, aid) if not is_exist: substance_raffle_sql.del_from_substanceraffle_status_table( aid, number) printer.warn(f'{substance_raffle_status}消失了。。。。。') continue printer.info([f'{aid}({number})的实物抽奖正在参与'], True) await notifier.exec_task_awaitable(-2, SubstanceRaffleHandlerTask, 1, substance_raffle_status) substance_raffle_sql.set_rafflestatus_handle_status( 1, aid, number) printer.info([f'{aid}({number})的实物抽奖参与完毕'], True) if not results: await asyncio.sleep(60)
async def handle_1_TV_raffle_black(num, real_roomid, raffleid, raffle_type): # print('ffffffffffggggdgdfddf') for i in range(50): json_response2 = await bilibili.get_gift_of_TV_app( real_roomid, raffleid, raffle_type) code = json_response2['code'] if not code: break elif code == -403: return True elif code == -405: print('没抢到。。。。。') printer.warn(raffleid) return False elif code != -401 and code != -403: # print('00', json_response2) pass # await asyncio.sleep() code = json_response2['code'] if code: await asyncio.sleep(5) return data = json_response2['data'] Statistics.append_to_TVlist(raffleid, real_roomid) Statistics.add_to_result(data['gift_name'], int(data['gift_num'])) printer.info([f'参与了房间{real_roomid:^9}的道具抽奖'], True) # printer.info([f'# 道具抽奖状态: {json_response2["msg"]}']) printer.info([ f'# 房间{real_roomid:^9}网页端活动抽奖结果: {data["gift_name"]}X{data["gift_num"]}' ]) return True
async def read_datas(self): while True: datas = await self._read_bytes() # 本函数对bytes进行相关操作,不特别声明,均为bytes if datas is None: return data_l = 0 len_datas = len(datas) while data_l != len_datas: # 每片data都分为header和body,data和data可能粘连 # data_l == header_l && next_data_l = next_header_l # ||header_l...header_r|body_l...body_r||next_data_l... tuple_header = self.structer.unpack_from(datas[data_l:]) len_data, len_header, ver, opt, seq = tuple_header body_l = data_l + len_header next_data_l = data_l + len_data body = datas[body_l:next_data_l] # 人气值(或者在线人数或者类似)以及心跳 if opt == 3: # UserCount, = struct.unpack('!I', remain_data) # printer.debug(f'弹幕心跳检测{self._area_id}') pass # cmd elif opt == 5: if not self.handle_danmu(body): return # 握手确认 elif opt == 8: printer.info( [f'{self._area_id}号弹幕监控进入房间({self._room_id})'], True) else: printer.warn(datas[data_l:next_data_l]) data_l = next_data_l
async def handle_1_TV_raffle(num, real_roomid, raffleid, raffle_type): while True: json_response2 = await bilibili.get_gift_of_TV_app( real_roomid, raffleid, raffle_type) code = json_response2['code'] if not code: break elif code == -403: return True elif code == -405: print('没抢到。。。。。') printer.warn(raffleid) return False elif code == 400: print(json_response2) tasklist = [] for i in range(60): task = asyncio.ensure_future( handle_1_TV_raffle_black(num, real_roomid, raffleid, raffle_type)) tasklist.append(task) await asyncio.wait(tasklist, return_when=asyncio.FIRST_COMPLETED) return elif code != -401 and code != -403: pass data = json_response2['data'] Statistics.append_to_TVlist(raffleid, real_roomid) Statistics.add_to_result(data['gift_name'], int(data['gift_num'])) printer.info([f'参与了房间{real_roomid:^9}的道具抽奖'], True) # printer.info([f'# 道具抽奖状态: {json_response2["msg"]}']) printer.info([ f'# 房间{real_roomid:^9}网页端活动抽奖结果: {data["gift_name"]}X{data["gift_num"]}' ]) return True
async def request_text(self, method, url, headers=None, data=None, params=None)->str: async with sem: i = 0 while True: i += 1 if i >= 10: printer.warn(url) try: async with self.var_session.request(method, url, headers=headers, data=data, params=params) as rsp: if rsp.status == 200: text_body = await self.__get_text_body(rsp) if text_body: return text_body elif rsp.status == 403: printer.warn(f'403频繁, {url}') await asyncio.sleep(240) except: # print('当前网络不好,正在重试,请反馈开发者!!!!') print(sys.exc_info()[0], sys.exc_info()[1], url) continue
def handle_danmu(self, body): dic = json.loads(body.decode('utf-8')) cmd = dic['cmd'] # print(cmd) if cmd == 'DANMU_MSG': info = dic['info'] ori = info[1] uid = info[2][0] print(ori) try: msg = self.__reverse(ori) result = self.__combine_piece(uid, msg) print('监控read dic', self.__read) if result is None: return True print(result) type, raffle_id, room_id = result if type == '+': printer.info([ f'{self._area_id}号弹幕监控检测到{room_id:^9}的大航海(id: {raffle_id})' ], True) RaffleHandler().push2queue((room_id, raffle_id), 'handle_guard_raffle') bili_stats.add2pushed_raffles('Yj协同大航海', 2) except Exception: printer.warn(f'Yj监控房间内可能有恶意干扰{uid}: {ori}') return True
def handle_danmu(self, body): dic = json.loads(body.decode('utf-8')) cmd = dic['cmd'] # print(cmd) if cmd == 'DANMU_MSG': info = dic['info'] ori = info[1] uid = info[2][0] # print('测试', self.__read, ori) try: msg = self.__reverse(ori) if msg is not None: msg_id, type, id = msg if type == '~' and not msg_id % 2: raffle_id = id printer.info([ f'{self._area_id}号弹幕监控检测到{"0":^9}的节奏风暴(id: {raffle_id})' ], True) # raffle_handler.exec_at_once(StormRaffleHandlerTask, 0, raffle_id) bili_statistics.add2pushed_raffles('Yj协同节奏风暴', 2) result = self.__combine_piece(uid, msg) if result is None: return True type, raffle_id, real_roomid = result if type == '+': printer.info([ f'{self._area_id}号弹幕监控检测到{real_roomid:^9}的大航海(id: {raffle_id})' ], True) raffle_handler.push2queue(GuardRaffleHandlerTask, real_roomid, raffle_id) bili_statistics.add2pushed_raffles('Yj协同大航海', 2) except Exception: printer.warn(f'Yj监控房间内可能有恶意干扰{uid}: {ori}') return True
async def _one_read(self) -> bool: header = await self._conn.read_bytes(Header.raw_header_size) if header is None: return False len_body, = Header.unpack(header) # 心跳回复 if not len_body: # print('heartbeat') return True json_body = await self._conn.read_json(len_body) if json_body is None: return False data_type = json_body['type'] if data_type == 'raffle': if not self.handle_danmu(json_body['data']): return False # 握手确认 elif data_type == 'entered': print(f'{self._area_id} 号数据连接确认建立连接({self._key})') elif data_type == 'error': warn(f'{self._area_id} 号数据连接发生致命错误{json_body}') self._closed = True # 内部关闭,不再重连 return False return True
async def request_json(self, method, url, ctrl: Ctrl = ZERO_ONLY_CTRL, **kwargs) -> dict: async with sem: i = 0 while True: i += 1 if i >= 10: printer.warn(url) try: async with self.var_session.request(method, url, **kwargs) as rsp: if rsp.status == 200: json_body = await self.__get_json_body(rsp) if json_body: # 有时候是None或空,直接屏蔽。下面的read/text类似,禁止返回空的东西 json_rsp_type = ctrl.verify(json_body) if json_rsp_type == JsonRspType.OK: return json_body elif json_rsp_type == JsonRspType.IGNORE: await asyncio.sleep(1.0) elif rsp.status in (412, 403): printer.warn(f'403频繁, {url}') await asyncio.sleep(240) except asyncio.CancelledError: raise except: # print('当前网络不好,正在重试,请反馈开发者!!!!') print(sys.exc_info()[0], sys.exc_info()[1], url) await asyncio.sleep(0.02)
async def request_binary(self, method, url, headers=None, data=None, params=None, is_none_allowed=False): async with sem: i = 0 while True: i += 1 if i >= 10: printer.warn(url) try: async with self.var_session.request(method, url, headers=headers, data=data, params=params) as rsp: if rsp.status == 200: binary_body = await self.__get_binary_body(rsp) if binary_body is not None or is_none_allowed: return binary_body elif rsp.status == 403: printer.warn(f'403频繁, {url}') await asyncio.sleep(240) elif rsp.status == 404: return None except: # print('当前网络不好,正在重试,请反馈开发者!!!!') print(sys.exc_info()[0], sys.exc_info()[1], url) continue
async def handle_1_activity_raffle_black(num, text1, raffleid): # print('参与') # await asyncio.sleep(random.uniform(0.5, min(30, num * 1.3))) for i in range(50): json_response1 = await bilibili.get_gift_of_events_app(text1, raffleid) code = json_response1['code'] if not code: break elif code == -403: return True elif code == -405: print('没抢到。。。。。') printer.warn(raffleid) return False elif code != -401 and code != -403: # print('00', json_response2) pass # json_pc_response = await bilibili.get_gift_of_events_web(text1, text2, raffleid) # print(json_response1) printer.info([f'参与了房间{text1:^9}的活动抽奖'], True) if not json_response1['code']: printer.info([f'# 移动端活动抽奖结果: {json_response1["data"]["gift_desc"]}']) Statistics.add_to_result( *(json_response1['data']['gift_desc'].split('X'))) else: # print(json_response1) printer.info([f'# 移动端活动抽奖结果: {json_response1}']) return True
def handle_danmu(self, body): dic = json.loads(body.decode('utf-8')) cmd = dic['cmd'] # print(cmd) if cmd == 'DANMU_MSG': info = dic['info'] ori = info[1] uid = info[2][0] print(ori) try: msg = self.__reverse(ori) ''' if msg is not None: msg_id, type, id = msg if type == '~' and not msg_id % 2: storm_id = id print('节奏风暴', storm_id) ''' result = self.__combine_piece(uid, msg) print('监控read dic', self.__read) if result is None: return True print(result) type, raffle_id, room_id = result if type == '+': printer.info([f'{self._area_id}号弹幕监控检测到{room_id:^9}的大航海(id: {raffle_id})'], True) rafflehandler.Rafflehandler.Put2Queue((room_id, raffle_id), rafflehandler.handle_1_room_guard) Statistics.add2pushed_raffle('Yj协同大航海', 2) except Exception: printer.warn(f'Yj监控房间内可能有恶意干扰{uid}: {ori}') return True
async def __request(self, parse_rsp, method, url, **kwargs): async with sem: i = 0 while True: i += 1 if i >= 10: printer.warn(f'反复请求多次未成功, {url}, {kwargs}') try: async with self.var_session.request(method, url, **kwargs) as rsp: if rsp.status == 200: body = await parse_rsp(rsp) if body: # 有时候是None或空,直接屏蔽。下面的read/text类似,禁止返回空的东西 return body elif rsp.status in (412, 403): printer.warn(f'403频繁, {url}, {kwargs}') raise ForbiddenError(msg=url) except asyncio.CancelledError: raise except ForbiddenError: raise except: # print('当前网络不好,正在重试,请反馈开发者!!!!') print(sys.exc_info()[0], sys.exc_info()[1], url) await asyncio.sleep(0.02)
async def send_gift(): if ConfigLoader().dic_user['task_control']['clean-expiring-gift']: argvs = await utils.fetch_bag_list(show=False) printer.warn(argvs) roomID = ConfigLoader( ).dic_user['task_control']['clean-expiring-gift2room'] time_set = ConfigLoader().dic_user['task_control']['set-expiring-time'] list_gift = [] for i in argvs: left_time = i[3] if left_time is not None and 0 < int( left_time) < time_set: # 剩余时间少于半天时自动送礼 list_gift.append(i[:3]) if list_gift: print('发现即将过期的礼物') if ConfigLoader( ).dic_user['task_control']['clean_expiring_gift2all_medal']: print('正在投递其他勋章') list_medal = await utils.fetch_medal(show=False) list_gift = await full_intimate(list_gift, list_medal) print('正在清理过期礼物到指定房间') for i in list_gift: giftID = i[0] giftNum = i[1] bagID = i[2] await utils.send_gift_web(roomID, giftNum, bagID, giftID) else: print('未发现即将过期的礼物') BiliTimer.call_after(send_gift, 21600)
async def _read_datas(self): while True: datas = await self._read_bytes() # 本函数对bytes进行相关操作,不特别声明,均为bytes if datas is None: return data_l = 0 len_datas = len(datas) while data_l != len_datas: # 每片data都分为header和body,data和data可能粘连 # data_l == header_l && next_data_l == next_header_l # ||header_l...header_r|body_l...body_r||next_data_l... tuple_header = self.structer.unpack_from(datas[data_l:]) len_data, len_header, _, opt, _ = tuple_header body_l = data_l + len_header next_data_l = data_l + len_data body = datas[body_l:next_data_l] # 人气值(或者在线人数或者类似)以及心跳 if opt == 3: # num_watching, = struct.unpack('!I', body) # print(f'弹幕心跳检测{self._area_id}') pass # cmd elif opt == 5: if not self.handle_danmu(json.loads(body.decode('utf-8'))): return # 握手确认 elif opt == 8: printer.info( [f'{self._area_id}号弹幕监控进入房间({self._room_id})'], True) else: printer.warn(f'弹幕数据错误:{datas}') return data_l = next_data_l
async def handle_msg(self): while True: bytes_datas = await self.__read_msg() if bytes_datas is None: return len_read = 0 len_bytes_datas = len(bytes_datas) while len_read != len_bytes_datas: split_header = self.structer.unpack(bytes_datas[len_read:16 + len_read]) len_data, len_header, ver, opt, seq = split_header remain_data = bytes_datas[len_read + 16:len_read + len_data] # 人气值/心跳 3s间隔 if opt == 3: # self._UserCount, = struct.unpack('!I', remain_data) printer.debug(f'弹幕心跳检测{self.area_id}') # cmd elif opt == 5: if not self.handle_danmu(remain_data): return # 握手确认 elif opt == 8: printer.info([f'{self.area_id}号弹幕监控进入房间({self.roomid})'], True) else: printer.warn(bytes_datas[len_read:len_read + len_data]) len_read += len_data
async def handle_1_TV_raffle(num, raffle_type, real_roomid, raffleid): while True: printer.info([f'参与房间{real_roomid:^9}的 {raffle_type} 抽奖:{raffleid}'], True) json_response2 = await OnlineNet().req('get_gift_of_TV', raffle_type, real_roomid, raffleid) code = json_response2['code'] if not code: break elif code == -403: return True elif code == -405: print('没抢到。。。。。') printer.warn(f'{raffleid} {raffle_type} {num}') return False elif code == -400: print(json_response2) return elif code != -401 and code != -403: print(json_response2) return printer.info( [f'房间{real_roomid:^9}的抽奖:{raffleid} = {json_response2["msg"]}'], True) return True
def try_to_place(data, item): """Attempt item placement in yard.""" if sum([toy["size"] for toy in data["yard"]]) + item["size"] < data["space"]: data["yard"].append(item) item["in_yard"] = True printer.success(data["prefix"], "Nice! Your yard now consists of a {0}".format(", and a ".join([toy["name"] for toy in data["yard"]]))) else: printer.warn(data["prefix"], "Oops that won't fit in your yard! Would you like to remove an item?") offer_replace(data, item)
async def Daily_Task(): # -400 done/not yet json_response2 = await bilibili.get_dailytask() printer.warn(json_response2) printer.info([f'# 双端观看直播: {json_response2["msg"]}']) if json_response2['code'] == -400 and '已' in json_response2['msg']: sleeptime = (utils.seconds_until_tomorrow() + 300) else: sleeptime = 350 BiliTimer.call_after(Daily_Task, sleeptime)
async def DoSign(): # -500 done temp = await bilibili.get_dosign() printer.warn(temp) printer.info([f'# 签到状态: {temp["msg"]}']) if temp['code'] == -500 and '已' in temp['msg']: sleeptime = (utils.seconds_until_tomorrow() + 300) else: sleeptime = 350 BiliTimer.call_after(DoSign, sleeptime)
def offer_replace(data, item): """Replace an existing item in yard.""" yard_items = [toy["name"] for toy in data["yard"]] printer.yard(data["prefix"], "Currently in your yard you have: a {0}".format(", and a".join(yard_items))) inp = input("{.YARD}{}{.ENDC} Would you like to replace any of the items in your yard? Which one? ".format(printer.PColors, data["prefix"], printer.PColors)) if inp in yard_items: remove_from_yard(data, inp) try_to_place(data, item) else: printer.warn(data["prefix"], "Sorry I don't see that item in your yard")
def buy_item(data): """Buy an item.""" buyable_items = [item for item in data["items"].keys() if data["items"][item]["attributes"] == []] inp = input("{.SHOP}{}{.ENDC} What item would you like to buy? ".format( printer.PColors, data["prefix"], printer.PColors)) if inp in buyable_items: try_to_buy(data, inp) else: printer.warn(data["prefix"], "Uhhh sorry, we don't carry that item.")
async def Daily_bag(self): json_response = await self.online_request(self.webhub.get_dailybag) # no done code try: for i in json_response['data']['bag_list']: self.printer_with_id(["# 获得-" + i['bag_name'] + "-成功"]) except: print('hhhhhhjjjjdjdjdjddjdjdjjdjdjdjdjdjdjdjdjddjjddjjdjdjdjdj', json_response) printer.warn(f'{json_response}') return 21600
async def link_sign(): json_rsp = await bilibili.get_grouplist() printer.warn(json_rsp) list_check = json_rsp['data']['list'] id_list = ((i['group_id'], i['owner_uid']) for i in list_check) if list_check: tasklist = [] for (i1, i2) in id_list: task = asyncio.ensure_future(Sign1Group(i1, i2)) tasklist.append(task) results = await asyncio.gather(*tasklist) BiliTimer.call_after(link_sign, 21600)
def ex_item(data): """Examine item.""" items = data["items"].keys() printer.shop( data["prefix"], "Here are the items you can see: " + ", ".join(items)) inp = input("{.SHOP}{}{.ENDC} which would you like to examine? ".format( printer.PColors, data["prefix"], printer.PColors)) if inp in items: print("{.SHOP}{}{.ENDC}".format( printer.PColors, data["items"][inp]["description"], printer.PColors)) else: printer.warn(data["prefix"], "Uhhh sorry, I don't see that item.")
async def enter_room(roomid): json_response = await bilibili.request_check_room(roomid) if not json_response['code']: data = json_response['data'] param1 = data['is_hidden'] param2 = data['is_locked'] param3 = data['encrypted'] if any((param1, param2, param3)): printer.info([f'抽奖脚本检测到房间{roomid:^9}为异常房间'], True) printer.warn(f'抽奖脚本检测到房间{roomid:^9}为异常房间') return False else: await bilibili.post_watching_history(roomid) return True
async def send(self, msg): print('_________________________________________') msg = self.special_handle(msg) list_danmu = self.add_special_str0(msg) + self.add_special_str1(msg) # print('本轮次测试弹幕群', list_danmu) for i in list_danmu: if await self.check_send(i): print('_________________________________________') return True await asyncio.sleep(1.5) printer.warn(f'弹幕{i}尝试') print('发送失败,请反馈', msg) printer.warn(f'弹幕{msg}尝试失败,请反馈') # sys.exit(-1) return False
def list_yard_items(data): """Display list of items placed in yard.""" if len(data["yard"]) > 0: things = [(item["name"], item["occupant"]) for item in data["yard"]] for thing in things: cat = "no one" if thing[1]: try: cat = thing[1][0]["name"] except: pass printer.yard(data["prefix"], "Your yard currently has a {0} in it, occupied by {1}".format(thing[0], cat)) # TODO: add cat descriptions else: printer.warn(data["prefix"], "You currently have nothing in your yard, how sad") check_food(data)
def place(data): """Place item in yard.""" items_list = [item for item in data["items"].values() if "owned" in item["attributes"] and not item["in_yard"]] # TODO: this is ultra gross placable_items = {} for item in items_list: if item["size"] < 6: placable_items[item["name"]] = item printer.yard(data["prefix"], "Here are the items that you can put in your yard: {0}".format(", ".join(placable_items.keys()))) inp = input("{.YARD}{}{.ENDC} Which item would you like to place? ".format( printer.PColors, data["prefix"], printer.PColors)) if inp in placable_items.keys(): try_to_place(data, placable_items[inp]) else: printer.warn(data["prefix"], "I'm sorry I didn't recognize that item")
async def read_datas(self): while True: datas = await self._read_bytes() # 本函数对bytes进行相关操作,不特别声明,均为bytes if datas is None: return data_l = 0 len_datas = len(datas) while data_l != len_datas: # 每片data都分为header和body,data和data可能粘连 # data_l == header_l && next_data_l = next_header_l # ||header_l...header_r|body_l...body_r||next_data_l... tuple_header = self.structer.unpack_from(datas[data_l:]) len_data, len_header, ver, opt, seq = tuple_header body_l = data_l + len_header next_data_l = data_l + len_data if ver == 2: # handle ver 2 zlib gibberish, insert decompressed data to datas decompressed = zlib.decompress(datas[body_l:next_data_l]) datas = decompressed + datas[next_data_l:] data_l = 0 len_datas = len(datas) continue else: # ver 0 and ver 1 doesn't need decompression body_l = data_l + len_header next_data_l = data_l + len_data body = datas[body_l:next_data_l] # 人气值(或者在线人数或者类似)以及心跳 if opt == 3: # UserCount, = struct.unpack('!I', remain_data) printer.debug(f'弹幕心跳检测{self._area_id}') # cmd elif opt == 5: if not self.handle_danmu(body): return # 握手确认 elif opt == 8: printer.info( [f'{self._area_id}号弹幕监控进入房间({self._room_id})'], True) else: printer.warn(datas[data_l:next_data_l]) data_l = next_data_l
def check_food(data): """Check food in yard.""" if data["food_remaining"] == 0: printer.warn(data["prefix"], "Your yard currently doesn't have any food in it! No cats will come if there's no food!") else: printer.success(data["prefix"], "Your yard currently has a {0} in it with {1} time remaining".format(data["food"], data["food_remaining"]))