def getPrinter(self, printerId, accountName): """Fetch one printer, including capabilities. Args: printerId: something like e64b1063-80e7-a87e-496c-3caa8cb7d736 accountName: email address (account) printer is associated with Returns: A Printer object, or None if printer not found.""" for requestor in self.requestors: if accountName != requestor.getAccount(): continue response = requestor.printer(printerId) if response is None or not response['success'] \ or 'printers' not in response or not response['printers']: break return Printer(response['printers'][0], requestor) return None
def __init__(self): self.p = Printer() self.btnwidth = 35 self.be = BackEnd() self.printers = self.p.getActivePrinters() self.checkboxes = {} self.window = Tk() self.window.wm_title("Batch Printer Install") self.window.protocol("WM_DELETE_WINDOW", self.on_closing) row = 0 for printer in self.printers: self.addPrinterOption(printer.name, printer.path, [row, 0]) row += 1 row += 1 btnAddPrinters = Button(self.window, text="Add Printers", width=self.btnwidth, command=self.add_printers_command) btnAddPrinters.grid(row=row, column=0, sticky='we') row += 1 self.lblStatus = Label() self.lblStatus.grid(row=row, column=0, sticky='we')
def simulation(num_seconds, pages_per_minute, num_students): lab_printer = Printer(pages_per_minute) print_queue = Queue() waiting_times = [] for current_second in range(num_seconds): if new_print_task(num_students): task = Task(current_second) print_queue.enqueue(task) if (not lab_printer.busy()) and (not print_queue.is_empty()): next_task = print_queue.de_queue() waiting_times.append(next_task.wait_time(current_second)) lab_printer.start_next(next_task) lab_printer.tick() average_wait = sum(waiting_times) / len(waiting_times) print( f"Average Wait {average_wait:6.2f} secs {print_queue.size():3d} tasks remaining." )
async def handle_1_room_TV(real_roomid): await asyncio.sleep(random.uniform(0.5, 1.5)) result = await utils.check_room_true(real_roomid) if True in result: Printer().printlist_append([ 'join_lottery', '钓鱼提醒', 'user', f'WARNING:检测到房间{real_roomid:^9}的钓鱼操作' ], True) else: # print(True) await bilibili.post_watching_history(real_roomid) json_response = await bilibili.get_giftlist_of_TV(real_roomid) # print(json_response['data']['list']) checklen = json_response['data']['list'] list_available_raffleid = [] for j in checklen: # await asyncio.sleep(random.uniform(0.5, 1)) # resttime = j['dtime'] raffleid = j['raffleId'] status = j['status'] if status == 1: # print('未参加') list_available_raffleid.append(raffleid) elif status == 2: # print('过滤') pass else: print(checklen) tasklist = [] num_available = len(list_available_raffleid) for raffleid in list_available_raffleid: task = asyncio.ensure_future( handle_1_TV_raffle(num_available, real_roomid, raffleid)) tasklist.append(task) if tasklist: raffle_results = await asyncio.gather(*tasklist) if False in raffle_results: print('有繁忙提示,稍后重新尝试') Rafflehandler.Put2Queue(handle_1_room_TV, (real_roomid, ))
async def fetch_medal(printer=True): if printer: Printer().printer('查询勋章信息', "Info", "green") print('{} {} {:^12} {:^10} {} {:^6} '.format( adjust_for_chinese('勋章'), adjust_for_chinese('主播昵称'), '亲密度', '今日的亲密度', adjust_for_chinese('排名'), '勋章状态')) dic_worn = {'1': '正在佩戴', '0': '待机状态'} for _ in range(3): response = await bilibili().request_fetchmedal() json_response = await response.json(content_type=None) if json_response['code']: continue # 有时候dict获取不完整,包括最后一项"roomid"的后半部分缺失 elif all([ "roomid" not in medal for medal in json_response['data']['fansMedalList'] ]): continue else: break roomid = 0 today_feed = 0 day_limit = 0 if json_response['code'] == 0: for i in json_response['data']['fansMedalList']: if i['status'] == 1: roomid = i.get('roomid', 0) # 主站获取的勋章没有直播间 today_feed = i['today_feed'] day_limit = i['day_limit'] if printer: print('{} {} {:^14} {:^14} {} {:^6} '.format( adjust_for_chinese(i['medal_name'] + '|' + str(i['level'])), adjust_for_chinese(i['anchorInfo']['uname']), str(i['intimacy']) + '/' + str(i['next_intimacy']), str(i['todayFeed']) + '/' + str(i['dayLimit']), adjust_for_chinese(str(i['rank'])), dic_worn[str(i['status'])])) return roomid, today_feed, day_limit
async def auto_send_gift(self): if self.dic_user['auto-gift']['on/off'] == "1": a = await utils.fetch_medal(printer=False) res = await bilibili().gift_list() json_res = await res.json() temp_dic = {} for j in range(0, len(json_res['data'])): price = json_res['data'][j]['price'] id = json_res['data'][j]['id'] temp_dic[id] = price x, temp = await utils.fetch_bag_list(printer=False) roomid = a[0] today_feed = a[1] day_limit = a[2] left_num = int(day_limit) - int(today_feed) calculate = 0 for i in range(0, len(temp)): gift_id = int(temp[i][0]) gift_num = int(temp[i][1]) bag_id = int(temp[i][2]) if (gift_num * (temp_dic[gift_id] / 100) < left_num) and (gift_id != 4 and gift_id != 3): calculate = calculate + temp_dic[gift_id] / 100 * gift_num # tmp = calculate / (temp_dic[gift_id] / 100) tmp2 = temp_dic[gift_id] / 100 * gift_num await utils.send_gift_web(roomid, gift_id, gift_num, bag_id) left_num = left_num - tmp2 elif left_num - temp_dic[gift_id] / 100 >= 0 and ( gift_id != 4 and gift_id != 3): tmp = (left_num) / (temp_dic[gift_id] / 100) tmp1 = (temp_dic[gift_id] / 100) * int(tmp) calculate = calculate + tmp1 await utils.send_gift_web(roomid, gift_id, tmp, bag_id) left_num = left_num - tmp1 Printer().printlist_append([ 'join_lottery', '', 'user', "# 自动送礼共送出亲密度为%s的礼物" % int(calculate) ])
async def handle_1_room_TV(real_roomid): await asyncio.sleep(random.uniform(0, 1)) result = await utils.check_room_true(real_roomid) if True in result: Printer().printer(f"检测到房间 {real_roomid} 的钓鱼操作", "Warning", "red") else: await bilibili().post_watching_history(real_roomid) response = await bilibili().get_giftlist_of_TV(real_roomid) json_response = await response.json(content_type=None) gifts = json_response['data']['gift'] for gift in gifts: if gift['raffleId'] not in Rafflehandler().list_TV_processed: gift_data = { 'id': gift['raffleId'], 'type': gift['type'], 'time_wait': gift['time_wait'], 'roomid': real_roomid, } Rafflehandler().list_TV_processed.append(gift['raffleId']) await Rafflehandler().list_TV_waiting.put(gift_data)
async def ReadSocketData(self): try: header = await asyncio.wait_for(self._reader.read(4), timeout=35.0) except Exception: Printer().printer("与服务器连接断开", "Error", "red") self.connected = False return False if len(header) == 0: return False try: len_body, = self.header_struct.unpack_from(header) except: Printer().printer( f"unpack_from出现错误,header:{header} len(header):{len(header)}", "Error", "red") self.connected = False return False if not len_body: return False try: body = await self._reader.read(len_body - 4) Printer().printer(f"接收到服务器的header数据{header} body数据{body}", "DEBUG", "yellow") except Exception: Printer().printer("与服务器连接断开", "Error", "red") self.connected = False return False if body is None: return False try: body = body.decode('utf-8') body = body.replace("True", "true").replace("False", "false").replace( "None", "null") except: Printer().printer(f"body.decode出现错误,body:{body}", "Error", "red") self.connected = False return False try: json_data = json.loads(body) await self.parseDanMu(json_data) except Exception: Printer().printer(f"json.loads出现错误,body:{body}", "Error", "red") self.connected = False return False return True
async def auto_send_gift(self): if self.dic_user['auto-gift']['on/off'] == "1": a = await utils.fetch_medal(printer=False) # res = await bilibili().gift_list() # json_res = await res.json() # temp_dic = {} # for j in range(0, len(json_res['data'])): # price = json_res['data'][j]['price'] # id = json_res['data'][j]['id'] # temp_dic[id] = price temp_dic = {1: 100, 6: 1000} x, temp = await utils.fetch_bag_list(printer=False) roomid = a[0] today_feed = a[1] day_limit = a[2] left_num = int(day_limit) - int(today_feed) calculate = 0 for i in range(0, len(temp)): gift_id = int(temp[i][0]) gift_num = int(temp[i][1]) bag_id = int(temp[i][2]) expire = int(temp[i][3]) if gift_id in [1, 6] and expire != 0: if (gift_num * (temp_dic[gift_id] / 100) < left_num): calculate = calculate + temp_dic[ gift_id] / 100 * gift_num tmp2 = temp_dic[gift_id] / 100 * gift_num await utils.send_gift_web(roomid, gift_id, gift_num, bag_id) left_num = left_num - tmp2 elif left_num - temp_dic[gift_id] / 100 >= 0: tmp = (left_num) / (temp_dic[gift_id] / 100) tmp1 = (temp_dic[gift_id] / 100) * int(tmp) calculate = calculate + tmp1 await utils.send_gift_web(roomid, gift_id, tmp, bag_id) left_num = left_num - tmp1 Printer().printer(f"自动送礼共送出亲密度为{int(calculate)}的礼物", "Info", "green")
def start(): from analyzer import Analyzer p = ArgumentParser(description="python3 ./main.py -f \"laginak/*.doc.txt\" ") optional = p._action_groups.pop() # Edited this line required = p.add_argument_group('Required arguments') required.add_argument("-f", "--files", nargs='+', help="Files to analyze (in .txt, .odt, .doc or .docx format)") optional.add_argument('-a', '--all', action='store_true', help="Generate a CSV file with all the results") optional.add_argument('-s', '--similarity', action='store_true', help="Calculate similarity (max. 5 files)") p._action_groups.append(optional) opts = p.parse_args() FileLoader.load_files(opts.files) FileLoader.load_irregular_verbs_list() FileLoader.load_dale_chall_list() FileLoader.load_connectives_list() FileLoader.load_oxford_word_list() cube = Cube(verbose=True) # Cargar modelo Cube cube.load("en", "latest") df_row = None ### Files will be created in this folder path = Printer.create_directory(FileLoader.files[0]) file_num = 0 total = len(FileLoader.files) for input in FileLoader.files: texto = Analyzer.process_text(input=input) # Analizar a = Analyzer(texto, input, cube) i = a.analyze(opts.similarity) df = a.create_dataframe() prediction = a.predict_dificulty(df) file_num += 1 p = Printer(input, i) p.print_info(opts.similarity, prediction, file_num, total) if opts.all: df_row = p.write_in_full_csv(df_row, opts.similarity) p.generate_csv(path, prediction, opts.similarity) if opts.all: df_row.to_csv(os.path.join(path, "full_results_aztertest.csv"), encoding='utf-8', index=False)
async def auto_send_gift(): if ConfigLoader().dic_user['task_control']['send2wearing-medal']: a = await utils.WearingMedalInfo() if a is None: print('暂未佩戴任何勋章') await BiliTimer.append2list_jobs(auto_send_gift, 21600) return json_res = await bilibili.gift_list() temp_dic = {j['id']: (j['price'] / 100) for j in json_res['data']} temp = await utils.fetch_bag_list(printer=False) roomid = a[0] today_feed = a[1] day_limit = a[2] left_score = int(day_limit) - int(today_feed) calculate = 0 # print(temp) for i in temp: gift_id = int(i[0]) gift_num = int(i[1]) bag_id = int(i[2]) left_time = i[3] if (gift_id not in [4, 3, 9, 10]) and left_time is not None: # print(gift_id, bag_id) if (gift_num * temp_dic[gift_id] <= left_score): pass elif left_score - temp_dic[gift_id] >= 0: gift_num = int((left_score) / (temp_dic[gift_id])) else: continue score = temp_dic[gift_id] * gift_num await utils.send_gift_web(roomid, gift_num, bag_id, gift_id) calculate = calculate + score left_score = left_score - score Printer().printlist_append([ 'join_lottery', '', 'user', "# 自动送礼共送出亲密度为%s的礼物" % int(calculate) ]) await BiliTimer.append2list_jobs(auto_send_gift, 21600)
def test_renamePrinter(): assert len(helperinstance.getPrinters()) == 0 requestor = CloudPrintRequestor() requestor.setAccount("test") printerinstance = Printer( { 'name': 'Testing Printer', 'id': '__test_printer', 'capabilities': [{ 'name': 'ns1:Colors', 'type': 'Feature' }] }, requestor, helperinstance) helperinstance.addPrinter(printerinstance, "test") helperinstance.renamePrinter('gcp://test/__test_printer', 'Testing Printer 2', 'test location') printerdetails = helperinstance.getPrinter('gcp://test/__test_printer') assert printerdetails['device-uri'] == 'gcp://test/__test_printer' assert printerdetails['printer-info'] == 'Testing Printer 2' assert printerdetails['printer-location'] == 'test location' assert len(helperinstance.getPrinters()) == 1
def getPrinters(): output = os.popen(checkIfIdle).read() lines = output.split("\n") lines.pop(-1) for l in lines: parts = l.split(' ') # print(parts[0]) if parts[0] != 'printer': lines.remove(l) # print(lines) for l in lines: parts = l.split(' ') # index 1 = printer name, index 3 = status printerName = parts[1] printerStatus = parts[parts.index('since') - 1] print("{}: {}".format(printerName, printerStatus)) printers.append(Printer(printerName, printerStatus)) #print(printers) return printers
async def guard_lottery(self): for k in range(1): try: response = await bilibili().guard_list() json_response = response.json() break except Exception: continue else: Printer().printer("连接舰长服务器失败,尝试从CDN拉取数据", "Error", "red") response = await bilibili().guard_list_v2() encrypt_content = response.json( )['data']['room_info']['description'].replace('b6', '').replace( '</p>', '').replace('<p>', '') json_response = json.loads( brotli.decompress(encrypt.decrypt(encrypt_content)).decode()) for i in range(0, len(json_response)): GuardId = json_response[i]['Id'] if GuardId not in GuardLottery.had_gotted_guard and GuardId != 0: GuardLottery.had_gotted_guard.append(GuardId) OriginRoomId = json_response[i]['RoomId'] await self.guard_join(OriginRoomId, GuardId) await asyncio.sleep(0.2)
def main() -> None: parser = ArgumentParser( description="Prints tweet backlog to a line printer.") parser.add_argument("archive", type=FileType(), help="Tweet backlog as generated by tweetquenz.py") parser.add_argument( "--printer", default="/dev/lp0", help="Path to the printer device to use (default: /dev/lp0)", type=FileType("wb", bufsize=0), ) parser.add_argument( "--encoding", default="cp437", help="Character set to use for the printer output (default: cp437)", ) args = parser.parse_args() printer = Printer(args.printer, encoding=args.encoding) for line in args.archive: tweet = Tweet(**json.loads(line)) print_tweet(tweet, printer, indent=randrange(12))
def test_generateCUPSQueueName(): testdata = { 'test': 'test-test', 'test1': 'test1-test', 'test-1': 'test-1-test', 'testing test': 'testingtest-test', 'testing£test': 'testingtest-test', } requestor = CloudPrintRequestor() requestor.setAccount("test") for teststring in testdata: printerinstance = Printer( { 'name': teststring, 'id': '__test_printer', 'capabilities': [{ 'name': 'ns1:Colors', 'type': 'Feature' }] }, requestor, helperinstance) assert helperinstance.generateCUPSQueueName( printerinstance) == testdata[teststring]
def main(): parser = argparse.ArgumentParser() parser.add_argument('-v', '--verbosity', type=int, default=0, help='Verbosity level -- possible values: (0,1,2)') graph = parseGraph(cfg.path) assert (cfg.source != cfg.destination) graph.start = cfg.source graph.end = cfg.destination assert (cfg.population_size > 0) assert (cfg.evaporation_factor > 0.0 and cfg.evaporation_factor <= 1.0) assert (cfg.pheromone_influence >= 0.0) assert (cfg.heuristic_influence >= 0.0) args = parser.parse_args() assert (args.verbosity in (0,1,2)) printer = Printer(graph) solver = Solver(graph, printer, args.verbosity, cfg.initial_pheromone_amount, cfg.state_displaying_period) solver.perform_algorithm(cfg.iterations, cfg.population_size, cfg.evaporation_factor, cfg.pheromone_influence, cfg.heuristic_influence)
async def check_area(self, area, roomid=None, mandatory_check=False, mandatory_recreate=False): if len(str(area)) == 1: area = [ tem_area for tem_area in connect.areas if str(area) in tem_area ][0] if roomid is None: roomid = connect.roomids[connect.areas.index(area)] if not mandatory_check and time.time() - self.check_time[area[:1]] < 60: Printer().printer(f"[{area}分区] 近已检查,跳过", "Info", "green") [ckd_roomid, ckd_area] = [roomid, area] else: # Printer().printer(f"[{area}分区] {roomid} 检查开始", "Info", "green") self.check_time[area[:1]] = time.time() [ckd_roomid, ckd_area] = await MultiRoom.check_state(roomid=roomid, area=area) self.check_time[area[:1]] = time.time() if mandatory_recreate or ckd_roomid != roomid: await self.recreate(new_roomid=ckd_roomid, area=ckd_area)
def main(): parser = argparse.ArgumentParser(parents=[argparse_parent_base.parser], description=banner(), add_help=True) args = parser.parse_args() scanner = Scanner() printer = Printer() if args.timeout: scanner.timeout = args.timeout if args.number_of_process: scanner.number_of_process = args.number_of_process if args.ports: ports = map(int, args.ports) scanner.ports = filter(valid_port, ports) if args.host_file: scanner.ips = read_host_from_file(args.host_file) scanner.ips += args.host scanner.start() if args.output_file: printer.filepath = args.output_file printer.list_to_file(scanner.status_ports) else: printer.list_to_console(scanner.status_ports)
async def clean_activity(self): # print(self.activity_raffleid_list) if self.activity_raffleid_list: for i in range(0, len(self.activity_roomid_list)): response = await bilibili().get_activity_result( self.activity_roomid_list[0], self.activity_raffleid_list[0]) json_response = await response.json() # print(json_response) try: if json_response['code'] == 0: data = json_response['data'] Printer().printlist_append([ 'join_lottery', '', 'user', "房间{:^9}网页端活动抽奖结果: {}X{}".format( self.activity_roomid_list[0], data['gift_name'], data['gift_num']) ], True) self.add_to_result(data['gift_name'], int(data['gift_num'])) self.delete_0st_activitylist() # {'code': -400, 'msg': '尚未开奖,请耐心等待!', 'message': '尚未开奖,请耐心等待!', 'data': []} elif json_response['code'] == -400: # sleepseconds = self.activitysleeptime + self.activity_time_list[0] - int(CurrentTime())+ 2 # sleepseconds = self.activity_time_list[0] - int(CurrentTime()) # return sleepsecondsq return else: print('未知情况') print(json_response) except: print(json_response) else: return
async def bili_section_get(self, url, headers=None, data=None, params=None): while True: try: response = await self.bili_section.get(url, headers=headers, data=data, params=params) if response.status == 403: Printer().printer('403频繁,5s后重试', "Error", "red") await asyncio.sleep(5) continue tag = await self.replay_request(response) if tag: continue return response except: # print('当前网络不好,正在重试,请反馈开发者!!!!') # print(sys.exc_info()[0], sys.exc_info()[1]) await asyncio.sleep(1) continue
def run(): api = Netease() with open('music_list.txt', 'rb') as f1: charset = chardet.detect(f1.read()) _music_list = [] with codecs.open('music_list.txt', 'r', encoding=charset['encoding']) as f1: for line in f1.readlines(): if line.strip(): _music_list.append(line.strip()) # 去重排序 # music_list = list(set(_music_list)) # 随机顺序排序 music_list = {}.fromkeys(_music_list).keys() # 字典顺序排序 Printer().info('歌曲下载列表加载完成...') tasks = [] for song_name in music_list: tasks.append(asyncio.ensure_future(api.download_song_by_search(song_name))) with closing(asyncio.get_event_loop()) as loop: loop.run_until_complete(asyncio.wait(tasks))
async def handle_1_room_TV(real_roomid): await asyncio.sleep(random.uniform(1, 2)) result = await utils.check_room_true(real_roomid) if True in result: Printer().printer(f"检测到房间 {real_roomid} 的钓鱼操作", "Warning", "red") else: await bilibili().post_watching_history(real_roomid) response = await bilibili().get_giftlist_of_TV(real_roomid) json_response = await response.json() checklen = json_response['data']['list'] num = len(checklen) list_available_raffleid = [] for j in range(0, num): raffleid = json_response['data']['list'][j]['raffleId'] type = json_response['data']['list'][j]['type'] if Statistics().check_TVlist(raffleid): list_available_raffleid.append([type, raffleid]) tasklist = [] num_available = len(list_available_raffleid) for k in list_available_raffleid: task = asyncio.ensure_future(handle_1_TV_raffle(k[0], num_available, real_roomid, k[1])) tasklist.append(task) if tasklist: await asyncio.wait(tasklist, return_when=asyncio.ALL_COMPLETED)
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': return elif json_response['data']['gift_id'] != '-1': 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) else: return
async def guard_lottery(self): for k in range(3): try: response = await bilibili().guard_list() json_response = response.json() break except Exception: continue else: Printer().printer("连接舰长服务器失败", "Error", "red") return for i in range(0, len(json_response)): if json_response[i]['Status']: GuardId = json_response[i]['GuardId'] if GuardId not in had_gotted_guard and GuardId != 0: had_gotted_guard.append(GuardId) OriginRoomId = json_response[i]['OriginRoomId'] if not OriginRoomId == OnlineHeart.last_guard_room: result = await utils.check_room_true(OriginRoomId) if True in result: Printer().printer(f"检测到房间 {OriginRoomId} 的钓鱼操作", "Warning", "red") continue await bilibili().post_watching_history(OriginRoomId) OnlineHeart.last_guard_room = OriginRoomId response2 = await bilibili().get_gift_of_captain(OriginRoomId, GuardId) json_response2 = await response2.json(content_type=None) if json_response2['code'] == 0: Printer().printer(f"获取到房间 {OriginRoomId} 编号 {GuardId} 的上船亲密度: {json_response2['data']['message']}", "Lottery", "cyan") elif json_response2['code'] == 400 and json_response2['msg'] == "你已经领取过啦": Printer().printer( f"房间 {OriginRoomId} 编号 {GuardId} 的上船亲密度已领过", "Info", "green") elif json_response2['code'] == 400 and json_response2['msg'] == "访问被拒绝": Printer().printer(f"获取房间 {OriginRoomId} 编号 {GuardId} 的上船亲密度: {json_response2['message']}", "Lottery", "cyan") print(json_response2) else: Printer().printer( f"房间 {OriginRoomId} 编号 {GuardId} 的上船亲密度领取出错: {json_response2}", "Error", "red") else: pass
async def ReadSocketData(self, len_wanted): bytes_data = b'' if len_wanted == 0: return bytes_data len_remain = len_wanted while len_remain != 0: try: tmp = await asyncio.wait_for(self._reader.read(len_remain), timeout=35.0) except asyncio.TimeoutError: # 由于心跳包30s一次,但是发现35s内没有收到任何包,说明已经悄悄失联了,主动断开 Printer().printer(f'心跳失联,主动断开 @[{self.area}分区]{self._roomId}',"Error","red") self.close_connection() await asyncio.sleep(1) return None except ConnectionResetError: Printer().printer(f'RESET,网络不稳定或者远端不正常断开 @[{self.area}分区]{self._roomId}',"Error","red") self.close_connection() await asyncio.sleep(5) return None except ConnectionAbortedError: Printer().printer(f'你的主机中的软件中止了一个已建立的连接 @[{self.area}分区]{self._roomId}',"Error","red") self.close_connection() await asyncio.sleep(5) return None except asyncio.CancelledError: return None except: Printer().printer(f"{sys.exc_info()[0]}, {sys.exc_info()[1]} @[{self.area}分区]{self._roomId}","Error","red") Printer().printer(f'请联系开发者',"Warning","red") self.close_connection() return None if not tmp: Printer().printer(f"主动关闭或者远端主动发来FIN @[{self.area}分区]{self._roomId}","Error","red") self.close_connection() await asyncio.sleep(1) return None else: bytes_data = bytes_data + tmp len_remain = len_remain - len(tmp) return bytes_data
async def parseDanMu(self, messages): try: dic = json.loads(messages) except: return cmd = dic['cmd'] if cmd == 'LIVE': # Printer().printer(f"[{self.area}分区] 房间 {self._roomId} 疑似切换分区!启动分区检查", "Info", "green") # await utils.check_area_list([self.area], mandatory_check=True) pass elif cmd == 'PREPARING': Printer().printer(f"[{self.area}分区] 房间 {self._roomId} 下播!将切换监听房间", "Info", "green") self.close_connection() await utils.reconnect(self.area) elif cmd == 'DANMU_MSG': # Printer().printer(f"{dic}", "Message", "cyan", printable=False) pass elif cmd == 'SYS_GIFT': # Printer().printer(f"出现了远古的SYS_GIFT,请尽快联系开发者{dic}", "Warning", "red") pass elif cmd == 'NOTICE_MSG': # msg_type: 1 小时榜首绘马大奖等通报 # 2 抽奖 (TV, 大楼, etc.) # 3 舰队 # 4 总督进入直播间 # 5 当前房间高能大奖 # 6 风暴 # 8 任意门 # 9 活动中主播达成星级通报 try: if dic.get('msg_type') in [2, 8]: real_roomid = dic.get('real_roomid') Printer().printer( f"检测到房间 {real_roomid} 的广播抽奖 @[{self.area}分区]{self._roomId}", "Lottery", "cyan") Rafflehandler().append2list_TV(real_roomid) Statistics().append2pushed_TVlist(real_roomid, self.area[0]) else: Printer().printer( f"{dic['msg_common']} @[{self.area}分区]{self._roomId}", "Info", "green") except Exception: Printer().printer(f"NOTICE_MSG出错,请联系开发者 {dic}", "Warning", "red") elif cmd == 'SYS_MSG': if set(dic) in [ set(self.dic_bulletin), {'cmd', 'msg', 'msg_text'}, {'cmd', 'msg', 'url'} ]: Printer().printer( f"{dic['msg']} @[{self.area}分区]{self._roomId}", "Info", "green") else: try: real_roomid = dic['real_roomid'] Printer().printer( f"检测到房间 {real_roomid} 的广播抽奖 @[{self.area}分区]{self._roomId}", "Lottery", "cyan") Rafflehandler().append2list_TV(real_roomid) Statistics().append2pushed_TVlist(real_roomid, self.area[0]) except: Printer().printer(f"SYS_MSG出错,请联系开发者 {dic}", "Warning", "red") # 观众相关 [欢迎入场,送礼,发弹幕] elif cmd in ["WELCOME", "SEND_GIFT", "DANMU_MSG"]: pass # 各种通知 [通知(当前房间开奖 活动小时榜 各种SYS_MSG都会同时有NOTICE_MSG),系统通知(友爱社 心愿达成 绘马 主播招募 直播间强推)] elif cmd in ["NOTICE_MSG", "SYS_MSG"]: pass # 各种高能 [节奏风暴(开始 结束),高能广播(无抽奖 活动高能 全频风暴),抽奖通知(现在广播全在这里了),总督广播] elif cmd in [ "SPECIAL_GIFT", "SYS_GIFT", "SYS_MSG", "GUARD_MSG", "GUIARD_MSG" ]: pass # 礼物效果 [连击开始,连击结束,使用积分加成卡] elif cmd in ["COMBO_SEND", "COMBO_END", "SCORE_CARD"]: pass # PK相关 elif cmd in [ "PK_INVITE_INIT", "PK_INVITE_FAIL", "PK_INVITE_CANCEL", "PK_INVITE_SWITCH_OPEN", "PK_INVITE_SWITCH_CLOSE", "PK_PRE", "PK_START", "PK_PROCESS", "PK_SETTLE", "PK_END", "PK_MIC_END", "PK_MATCH", "PK_CLICK_AGAIN", "PK_AGAIN" ]: pass # 当前房间抽奖相关 elif cmd in [ "RAFFLE_START", "RAFFLE_END", "TV_START", "TV_END", "GUARD_LOTTERY_START", "LOTTERY_START" ]: pass # 房间管理相关 [屏蔽关键词,用户被加入黑名单,禁言开启,禁言关闭,新设房管,房管变更] elif cmd in [ "ROOM_SHIELD", "ROOM_BLOCK_MSG", "ROOM_SILENT_ON", "ROOM_SILENT_OFF", "room_admin_entrance", "ROOM_ADMINS" ]: pass # 舰队相关 [本房间购买舰长,船票购买,本房间舰队消息(登船),船员进房间,进房间特效] elif cmd in [ "USER_TOAST_MSG", "GUARD_BUY", "GUARD_MSG", "WELCOME_GUARD", "ENTRY_EFFECT" ]: pass # 直播状态相关 [开播,下播,警告,被切直播,房间被封] elif cmd in ["LIVE", "PREPARING", "WARNING", "CUT_OFF", "ROOM_LOCK"]: pass # 活动榜单相关 [进入小时榜,未知,获小时榜第一道具奖励] elif cmd in ["ROOM_RANK", "new_anchor_reward", "HOUR_RANK_AWARDS"]: pass # 活动相关 [活动获得的直播间入场特效,活动事件(如充能值信息),以前的高能事件,送礼抽奖活动开奖,LOL竞猜活动,LOL助力活动,?(不知道是啥,每个直播间都有,无论开播,每分钟发一次),?,?,冲鸭!机甲大作战相关,周星活动相关] elif cmd in [ "WELCOME_ACTIVITY", "ACTIVITY_EVENT", "EVENT_CMD", "BOX_LOTTERY_WIN", "LOL_ACTIVITY", "ACTIVITY_MATCH_GIFT", "ACTIVITY_BANNER_RED_NOTICE_CLOSE", "ACTIVITY_BANNER_CLOSE", "DAILY_QUEST_NEWDAY", "BOSS_ENERGY", "NOTICE_MSG_H5", "BOSS_INJURY", "BOSS_BATTLE", "ANIMATION", "BOSS_INFO", "WEEK_STAR_CLOCK", "ROOM_BOX_MASTER", "ROOM_BOX_USER" ]: pass # 直播间信息相关 [直播间更换壁纸,直播间界面皮肤变化,许愿瓶进度变化,关注数变化,直播间更名,实物抽奖宝箱提醒,实物抽奖宝箱开奖,弹幕抽奖结束] elif cmd in [ "CHANGE_ROOM_INFO", "ROOM_SKIN_MSG", "WISH_BOTTLE", "ROOM_REAL_TIME_MESSAGE_UPDATE", "ROOM_CHANGE", "BOX_ACTIVITY_START", "WIN_ACTIVITY", "DANMU_LOTTERY_END" ]: pass # 大乱斗活动 elif cmd in [ "PK_BATTLE_ENTRANCE", "PK_BATTLE_PRE", "PK_BATTLE_MATCH_TIMEOUT", "PK_BATTLE_START", "PK_BATTLE_VOTES_ADD", "PK_BATTLE_PROCESS", "PK_BATTLE_PRO_TYPE", "PK_BATTLE_GIFT", "PK_BATTLE_END", "PK_BATTLE_RANK_CHANGE", "PK_BATTLE_SETTLE_USER", "PK_BATTLE_SETTLE", "PK_LOTTERY_START", "ACTIVITY_BANNER_UPDATE" ]: pass else: # Printer().printer(f"出现一个未知msg @[{self.area}分区]{self._roomId} {dic}", "Warning", "red") pass
#!/usr/bin/env python3 from analyser import Analyser from printer import Printer from question import Question import queries dsn = 'dbname=news' analyser = Analyser(dsn, Printer(), 'Logs Analysis') analyser.add_question( Question('What are the most popular three articles of all time?', queries.MOST_TREE_POPULAR_ARTICLES, lambda result: '{}: {} views'.format(result[0], result[1]))) analyser.add_question( Question('Who are the most popular article authors of all time?', queries.MOST_POPULAR_ARTICLE_AUTHORS, lambda result: '{}: {} views'.format(result[0], result[1]))) analyser.add_question( Question('On which days did more than 1% of requests lead to errors?', queries.ERROR_DAYS, lambda result: '{}: {}% errors'.format(result[0], result[1]))) analyser.analyse()
import helpers import threading import random import os, sys, getopt, time import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import pickle import speech_recognition as sr WIT_AI_KEY = "BMSJFOODR7HW2VFEWLIUEYHNOVWNOC74" # Wit.ai keys are 32-character uppercase alphanumeric strings r = sr.Recognizer() m = sr.Microphone() printer = Printer() gui = Gui() instructions = [] def main(argv): """ INIT THE SPEECH RECOGNITION """ print("A moment of silence, please...") with m as source: r.adjust_for_ambient_noise(source) r.energy_threshold = 100 print("Set minimum energy threshold to {}".format(r.energy_threshold)) """ INIT THE JOB """ if (os.path.isfile('jobs/TGP.conf')): with open('jobs/TGP.conf', 'rb') as f: p = pickle.load(f)
async def Daily_Task(self): response2 = await bilibili().get_dailytask() json_response2 = await response2.json() Printer().printlist_append( ['join_lottery', '', 'user', "# 双端观看直播:", json_response2["msg"]])