def _download(photos_urls): photo_save_path, photo_download_url = photos_urls result = requests.get(photo_download_url, stream=True) if result.status_code == 200: hues.log(f"Сохраняю {photo_save_path}...") with open(photo_save_path, "wb") as f: f.write(result.content)
def get_photos_urls(vk, user_id, directory): hues.info("Начинаю поиск фотографий...") photos_urls = {} start_from = 0 while True: results = vk.messages.getHistoryAttachments( peer_id=user_id, media_type="photo", count=200, start_from=start_from ) if results["items"]: for attachment in results["items"]: photo = attachment["attachment"]["photo"] photo_name = ( f"{photo['id']}_{photo['owner_id']} " f"{dt.fromtimestamp(photo['date'], TZ).strftime('%d-%m-%y %H:%M')}.jpg" ) # example: 373772945_105918493 07-07-15 02:29 photo_save_path = f"{directory}/{photo_name}" photo_download_url = photo["sizes"][-1]["url"] photos_urls.update({photo_save_path: photo_download_url}) start_from = results["next_from"] hues.log( f"Получено {len(photos_urls)} фото, следующее смещение: {start_from}" ) else: hues.info(f"Найдено {len(photos_urls)} фото.") break time.sleep(INTERVAL) return photos_urls
def mclient(): # Step1: 输入host和port信息 host ='127.0.0.1' #raw_input('please input host name: ') port ='51500' #raw_input('please input textport: ') # Step2: 创建socket对象 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: port = int(port) except ValueError: port = socket.getservbyname(port, 'udp') # Step3: 打开socket连接 s.connect((host, port)) # 不管是tcp还是udp的都有connnect方法 hues.log("Looking for replies; press Ctrl-C or Ctrl-Break to stop") while 1: # Step4: 发送数据 hues.log("Enter data to transmit: ") data = sys.stdin.readline().strip() s.sendall(data) #s.sendto(data) # Step5: 接收服务器发过来的数据(一直在等待服务器发送过来的数据) buf = s.recv(2048) if not len(buf): break #sys.stdout.write(buf) hues.success(buf) time.sleep(5) s.close()
async def _(msg, ctx): """Handle only telegram messages with attachments.""" hues.log( f"CID:{msg.receiver_id} UID:{msg.sender_id} ATTACHMENTS:{msg.attachments}" ) if (ctx.backend.get_identity() == "telegram" and msg.receiver_id == ctx.config["tg_chat_id"]): # get vk backend vk_backend = ctx.app.get_backends()[1] # get vk chat_id chat_id = ctx.config["vk_chat_id"] msg_raw = msg.raw["message"] if msg_raw.get("photo"): if msg_raw.get("caption"): caption = msg_raw["caption"] attach_text = ( f'[photo - "{caption}" ' f"{msg_raw['photo'][-1]['width']}x{msg_raw['photo'][-1]['height']}]" ) else: attach_text = ( f"[photo - " f"{msg_raw['photo'][-1]['width']}x{msg_raw['photo'][-1]['height']}]" ) elif msg_raw.get("document"): attach_text = f"[doc - \"{msg_raw['document']['file_name']}\"]" elif msg_raw.get("sticker"): attach_text = f"[sticker - \"{msg_raw['sticker']['emoji']}\"]" elif msg_raw.get("location"): lat = msg_raw["location"]["latitude"] long = msg_raw["location"]["longitude"] return await vk_backend.request( "messages.send", chat_id=chat_id, lat=lat, long=long, random_id=random.randint(1, 99999), ) elif msg_raw.get("voice"): attach_text = f"[voice - {msg_raw['voice']['duration']} сек]" elif msg_raw.get("video_note"): attach_text = f"[video_note - {msg_raw['video_note']['duration']} сек]" elif msg_raw.get("poll"): attach_text = f"[poll - \"{msg_raw['poll']['question']}\"]" else: attach_text = "[unsupported attachment type]" header = create_message_header(msg.date, msg.raw) msg_text = f"{header}\n{attach_text}" return await vk_backend.request( "messages.send", chat_id=chat_id, message=msg_text, random_id=random.randint(1, 99999), )
def tcpserver(): s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 创建一个基于ipv4 的TCP协议的socket s.bind(('127.0.0.1',9999)) s.listen(5) # 开始监听 hues.log("Waiting for connection......") # 无限循环等待连接 while True: sock,addr=s.accept() # 返回一个单独的新的客户端套接字用来处理 t=threading.Thread(target=tcplink,args=(sock, addr)) t.start()
async def _(msg, ctx): """Handle only telegram messages without attachments.""" hues.log(f"CID:{msg.receiver_id} UID:{msg.sender_id} TEXT:{msg.text}") if (ctx.backend.get_identity() == "telegram" and msg.receiver_id == ctx.config["tg_chat_id"]): # get vk backend vk_backend = ctx.app.get_backends()[1] # get vk chat_id chat_id = ctx.config["vk_chat_id"] header = create_message_header(msg.date, msg.raw) msg_text = f"{header}\n{msg.text}" return await vk_backend.request( "messages.send", chat_id=chat_id, message=msg_text, random_id=random.randint(1, 99999), )
def print_reports(reports, verbose=False): '''Utility function for rendering SynParser report.''' errored = False for report in reports: if report.level == LEVELS['ok']: if verbose: hues.log(report.line_nb, report.msg, time=False) continue elif report.level == LEVELS['warn']: hues.log(report.line_nb, report.msg, time=False, warn=True) elif report.level == LEVELS['error']: hues.log(report.line_nb, report.msg, time=False, error=True) errored = True if not errored: hues.log('Valid Synonyms', time=False, success=True) return errored
def echo(msg, priority=4): hues.log(msg)
def routine(manual=True) -> None: Methods.console_clear() vk = VkAPI() _settings = None if os.path.exists('./settings.json'): with open('./settings.json') as f: try: _settings = json.loads(f.read()) except Exception: hues.error('Bad settings') os.remove('./settings.json') os._exit(-1) hues.success('Settings loaded.') from source.static.StaticData import StaticData if not Settings.settings_get(): Settings.settings_save(StaticData.defaultSettings) _settings = Settings.settings_get() if manual: if not _settings.get('safe_zone'): hues.warn('No users in safe zone.\nContinue? (y/n)') _choice = input('> ').lower() while _choice != 'y' and _choice != 'n': hues.warn('No users in safe zone.\nContinue? (y/n)') _choice = input('> ').lower() if _choice == 'n': Methods.console_clear() return _ban_list = [] from copy import copy from source.static.StaticMethods import StaticMethods _friends = vk.friends_get() _friends['items'] += vk.get_out_requests()['items'] if _settings.get('safe_zone'): for _friend in _friends['items']: if str(_friend) not in _settings['safe_zone']: _ban_list.append(_friend) _ban_list = list([str(x) for x in _ban_list]) else: _ban_list = list([str(x) for x in _friends['items']]) if _settings['newsfeedBan']: if manual: hues.warn( f'{len(_ban_list)} your friends (and out requests) will be affected.\nContinue? (y/n)' ) _choice = input('> ').lower() while _choice != 'y' and _choice != 'n': _choice = input('> ').lower() if _choice == 'n': Methods.console_clear() return __init_count = len(_ban_list) _temp = copy(_ban_list) while len(_temp) > 0: if manual: hues.log( f'[Newsfeed] Progress: {StaticMethods.get_percentage(abs(__init_count - len(_temp)), __init_count)}' ) vk.add_newsfeed_ban(_temp[:100]) del (_temp[:100]) sleep(0.4) if _settings['messagesBan']: pass if _settings['storiesBan']: _temp = copy(_ban_list) __init_count = len(_temp) while len(_temp) > 0: if manual: hues.log( f'[Stories] Progress: {StaticMethods.get_percentage(abs(__init_count - len(_temp)), __init_count)}' ) vk.stories_ban(_temp[:100]) del (_temp[:100]) sleep(0.4) if manual: Methods.console_clear() hues.success('Work done!')
def get_info(self): cities = [] schools = [] univers = [] counter = 0 users = self.get_friends() hues.success() for user in users: user_info = self.session.method('users.get', { 'user_ids': user, 'fields': 'city,schools,education' }) time.sleep(0.4) counter += 1 hues.log('Users handled {} ({}/{})'.format( StaticMethods.get_percentage(counter, len(users)), str(counter), str(len(users)))) try: cities.append(user_info[0].get('city').get('title')).replace( ',', '') except: pass try: schools.append( user_info[0].get('schools')[-1].get('name')).replace( ',', '') except: pass try: univer = user_info[0].get('university_name').replace(',', '') if univer: univers.append(univer) except: pass data = [Counter(cities), Counter(schools), Counter(univers)] top_cities = [None] * 3 for i in range(len(data)): if len(data[0]) > 2: top_cities[0] = str( sorted(dict(data[i]).items(), key=operator.itemgetter(1))[-1]).replace( '(', '').replace(')', '').split(',') top_cities[1] = str( sorted(dict(data[i]).items(), key=operator.itemgetter(1))[-2]).replace( '(', '').replace(')', '').split(',') top_cities[2] = str( sorted(dict(data[i]).items(), key=operator.itemgetter(1))[-3]).replace( '(', '').replace(')', '').split(',') elif len(data[0]) > 1: top_cities[0] = str( sorted(dict(data[i]).items(), key=operator.itemgetter(1))[-1]).replace( '(', '').replace(')', '').split(',') top_cities[1] = str( sorted(dict(data[i]).items(), key=operator.itemgetter(1))[-2]).replace( '(', '').replace(')', '').split(',') elif len(data[0]) == 1: top_cities[0] = str( sorted(dict(data[i]).items(), key=operator.itemgetter(1))[-1]).replace( '(', '').replace(')', '').split(',') else: top_cities = 'Not found' print('\n\n\n') try: if i == 0: out = 'City:\n{}\n{}\n{}'.format( '{}: {} ({}/{})'.format( top_cities[0][0].replace('\'', ''), StaticMethods.get_percentage( top_cities[0][1], str(len(cities)), 3), top_cities[0][1].strip(), str(len(cities)), 3), '{}: {} ({}/{})'.format( top_cities[1][0].replace('\'', ''), StaticMethods.get_percentage( top_cities[1][1], str(len(cities)), 3), top_cities[1][1].strip(), str(len(cities))), '{}: {} ({}/{})'.format( top_cities[2][0].replace('\'', ''), StaticMethods.get_percentage( top_cities[2][1], str(len(cities)), 3), top_cities[2][1].strip(), str(len(cities)))) print(out) self.save(out) elif i == 1: out = '\n\nSchool:\n{}\n{}\n{}'.format( '{}: {} ({}/{})'.format( top_cities[0][0].replace('\'', ''), StaticMethods.get_percentage( top_cities[0][1], str(len(cities)), 3), top_cities[0][1].strip(), str(len(cities))), '{}: {} ({}/{})'.format( top_cities[1][0].replace('\'', ''), StaticMethods.get_percentage( top_cities[1][1], str(len(cities)), 3), top_cities[1][1].strip(), str(len(cities))), '{}: {} ({}/{})'.format( top_cities[2][0].replace('\'', ''), StaticMethods.get_percentage( top_cities[2][1], str(len(cities)), 3), top_cities[2][1].strip(), str(len(cities)))) print(out) self.save(out) elif i == 2: out = '\n\nUniversity:\n{}\n{}\n{}'.format( '{}: {} ({}/{})'.format( top_cities[0][0].replace('\'', ''), StaticMethods.get_percentage( top_cities[0][1], str(len(cities)), 3), top_cities[0][1].strip(), str(len(cities))), '{}: {} ({}/{})'.format( top_cities[1][0].replace('\'', ''), StaticMethods.get_percentage( top_cities[1][1], str(len(cities)), 3), top_cities[1][1].strip(), str(len(cities))), '{}: {} ({}/{})'.format( top_cities[2][0].replace('\'', ''), StaticMethods.get_percentage( top_cities[2][1], str(len(cities)), 3), top_cities[2][1].strip(), str(len(cities)))) print(out) self.save(out) print('\n') except: pass
# class RandomListNode(object): # def __init__(self, x): # self.label = x # self.next = None # self.random = None class Solution(object): def copyRandomList(self, head): """ :type head: RandomListNode :rtype: RandomListNode """ ''' import hues hues.log('Mission', 42) hues.info('Finding', 42) hues.error(41, 'is not', 42) hues.warn('We are distracted...') hues.info('Found', 24) hues.success('Close enough') class LinkListRandom: def __init__(self, x): self.label = x self.next = None self.random = None #插入一个节点 def insert(self, head, val):
def consoleMessage(logtype, message): if logtype is VirBotLogType.ERROR: hues.log(hues.huestr("[ERROR] " + message).magenta.bold.colorized) elif logtype is VirBotLogType.GENERIC: hues.log(hues.huestr(message).black.colorized) elif logtype is VirBotLogType.GENERICBOLD: hues.log(hues.huestr(message).black.bold.colorized) elif logtype is VirBotLogType.CHANNEL: hues.log(hues.huestr(message).blue.bold.colorized) elif logtype is VirBotLogType.NOTICE: hues.log(hues.huestr("[NOTICE] " + message).blue.bold.colorized) elif logtype is VirBotLogType.RECEIVED: hues.log(hues.huestr("[RECEIVED] " + message).green.colorized) elif logtype is VirBotLogType.SENT: hues.log(hues.huestr("[SENT] " + message).magenta.bold.colorized) elif logtype is VirBotLogType.SERVER: hues.log(hues.huestr("[SERVER] " + message).cyan.bold.colorized)
def log(message): LogWork.base_init() logging.info(message) hues.log(message)