async def method(self, key: str, data: dict = {}): """Выполняет метод API VK с опциональными параметрами""" # Если у нас TOKEN, то для всех остальных методов, # кроме разрешённых, вызовем публичное API if key not in self.group_methods and self.token and 'message' not in key: api_method = self.public_api else: api_method = self.api try: return await api_method(key, **data) except (asyncio.TimeoutError, json.decoder.JSONDecodeError): # Пытаемся отправить запрос к API ещё раз return await api_method(key, **data) except aiovk.exceptions.VkAuthError: message = 'TOKEN' if self.token else 'LOGIN и PASSWORD' fatal(f"Произошла ошибка при авторизации API, " "проверьте значение полей {message} в settings.py!") except aiovk.exceptions.VkAPIError as ex: if ex.error_code == 9: # Flood error - слишком много одинаковых сообщений if 'message' not in data: return {} data['message'] += f'\n Анти-флуд (API): {self.anti_flood()}' try: # Пытаемся отправить сообщение ещё раз await self.method('messages.send', data) except aiovk.exceptions.VkAPIError: # В реальности такое будет очень редко # или вообще не случится hues.error('Обход анти-флуда API не удался =(') else: hues.error( f"Произошла ошибка при вызове метода API {key} с значениями {data}:\n{ex}" ) return {}
def get_session(self): try: self.vk = vk_api.VkApi(token=self.token) except: hues.error( 'Bad community\'s access token\\s. Or VkApi internal error.') exit()
async def process_command(self, msg_obj: Message, cmd: Command): """Обрабатка команды""" if not cmd.check_command(self): return False if cmd.has_prefix and settings.LOG_COMMANDS: cmd.log() try: return await self.system.call_command(cmd, msg_obj, cmd.args) except Exception as e: # Если в плагине произошла какая-то ошибка code = msg_obj.vk.anti_flood() await msg_obj.answer(f"{code}.\n" f"Произошла ошибка при выполнении команды <{cmd.command}> " "пожалуйста, сообщите об этом разработчику!") hues.error( f"{code}.\n" f"Произошла ошибка при вызове команды '{cmd.command}' с аргументами {cmd.args}.\n" f"Текст сообщения: '{cmd.text}'.\n" f"Ошибка:\n{traceback.format_exc()}") return True
async def process_command(self, msg_obj: Message): """Обрабатывает команду (объект Message)""" cmd = Command(msg_obj._data, self.convert) if not cmd.has_prefix: return False # Если команда есть в списке команд if cmd.command in self.commands: cmd_text = cmd.command # Или нужно попробовать конвертировать и изменённая команда в командах elif self.convert and cmd.try_convert() in self.commands: cmd.convert() cmd_text = cmd.command else: return False # Логгируем команду, если нужно if settings.LOG_COMMANDS: cmd.log() try: await self.system.call_command(cmd_text, msg_obj, cmd.args) return True # Если в плагине произошла какая-то ошибка except Exception: await msg_obj.answer( f"{msg_obj.vk.anti_flood()}. " f"Произошла ошибка при выполнении команды <{cmd_text}> " "пожалуйста, сообщите об этом разработчику!") hues.error( f"Произошла ошибка при вызове команды '{cmd_text}' с аргументами {cmd.args}. " f"Текст сообщения: '{msg_obj._data}'." f"Ошибка:\n{traceback.format_exc()}")
async def method(self, key: str, data=None, send_from=None, nowait=False): """Выполняет метод API VK с дополнительными параметрами""" if send_from is None: if self.group and is_available_from_group(key): send_from = SendFrom.GROUP elif is_available_from_public(key): send_from = SendFrom.USER else: send_from = SendFrom.USER task = RequestFuture(key, data, send_from) client = None if self.users and send_from == SendFrom.USER: client = self.users[self.current_user % len(self.users)] self.current_user += 1 elif self.tokens and send_from == SendFrom.GROUP: client = self.tokens[self.current_token % len(self.tokens)] self.current_token += 1 if not client: hues.error(f"Некому выполнять: {task.key}") return None client.queue.put_nowait(task) if nowait: return None return await asyncio.wait_for(task, None)
def __request(self, request: str, comparator) -> str: while True: result = input(request).strip().lower() if not comparator(result): hues.error('Invalid value passed.') else: return result
async def update_counters(stopper, vk): stopper.sleep = int(plugin.temp_data['s']['time']) if datetime.datetime.now() - plugin.temp_data['24h'] >= datetime.timedelta(days=1): plugin.temp_data['messages_24h'] = 0 plugin.temp_data['processed_messages_24h'] = 0 plugin.temp_data['24h'] = datetime.datetime.now() uptime = (datetime.datetime.now() - plugin.temp_data['start_time']).total_seconds() hours, remainder = divmod(uptime, 3600) minutes, seconds = divmod(remainder, 60) message = f"uptime: {'%02d:%02d:%02d' % (hours, minutes, seconds)} | обработано команд: " \ f"{plugin.temp_data['messages']} | " \ f"команд за 24 часа: {plugin.temp_data['messages_24h']}" v = {"text": message} if GROUP_ID: v["group_id"] = GROUP_ID elif vk.tokens: return hues.error("Невозможно установить статус! Вы не указала ID группы!") result = await vk.method("status.set", v) if result == 0: hues.error("Не удалось установить статус! Для изменения статуса необходи аккаунт администратора группы!")
def get_peer_id(vk): while True: peer_id = input( "Введите ID (пользователя/беседы/сообщества) для начала загрузки фото: " ) try: peer_id = int(peer_id) except ValueError: hues.error("ID должен быть числом!") continue # Групповая беседа if peer_id > 2000000000: hues.info(f"Групповая беседа {peer_id}") break # Сообщество if peer_id < 0: hues.info(f"Сообщество {peer_id}") break # Пользователь try: results = vk.users.get(user_ids=peer_id) hues.info( f"Найден пользователь {results[0]['first_name']} {results[0]['last_name']}" ) break except vk_api.exceptions.ApiError: hues.error("Неверный id (Пример: 105918493)") return peer_id
def scan_hostname(hostname, SerialNumber, lines, Proxy, conn, site_infos): """ try scan a hostname and get informations back (HTTP code, page title, IP address, ASN, abuse email etc). :param hostname: the hostname present in the certificate :param SerialNumber: the serial number of the certificate :param lines: list of user-agents strings :param Proxy: proxy settings :param conn: database connection :param site_infos: informations extracted on the net for the given hostname :return: True if everything went fine, False if any problem has been encountered """ title = "" try: r = get_requests(hostname, lines, conn, Proxy) if r is not None: hues.success('HTTP ' + str(r.status_code) + ' - ' + hostname) # retrieve the title of the homepage title = get_webpage_title(r) # retrieve ASN informations ipaddr = socket.gethostbyname(hostname) asn, asn_cidr, asn_country_code, asn_description, asn_abuse_email = get_ASN_Infos( ipaddr) # build the content of the alert file using certificate / webpage / ASN informations site_infos = { 'hostname': hostname, 'http_code': r.status_code, 'cert_serial_number': SerialNumber, 'webpage_title': title, 'ip_addr': ipaddr, 'asn': asn, 'asn_cidr': asn_cidr, 'asn_country_code': asn_country_code, 'asn_description': asn_description, 'asn_abuse_email': asn_abuse_email } return site_infos else: return {} except KeyboardInterrupt: print("scan_hostname() - Interrupt received, stopping ...") print("start - committing, closing DB") conn.commit conn.close print("ending - committing, closing DB") sys.exit(0) except Exception as ex: hues.error("scan_hostname() - any other kind of error: {}".format(ex)) return {}
async def enter_confirmation_сode(): hues.error("Похоже, у вас установлена двухфакторная авторизация!") hues.error("Пожалуйста, введите код подтверждения:") code = input() hues.success("Спасибо! Продолжаю приём сообщений") return code
async def process_queue(self): while True: try: if self.queue.empty() or self.requests >= settings.REQUESTS_QUANTITY: await asyncio.sleep(0.1) continue await self.execute_queue() except Exception as e: import traceback hues.error("Ошибка во время обработки запросов к ВК") traceback.print_exc()
def get_user_id(): if os.path.exists('./ids.txt'): f = open('./ids.txt', 'r') data = f.read().split('\n') f.close() if input('Use ids from ids.txt? y/n: ') == 'y': return data while True: data = input('Give me the user\'s VK URL: ').strip() if not re.findall(r'(https://)?vk\.com/[a-z0-9_]+/?', data): hues.error("Bad URL") continue break return [UserAPI.get_id_from_url(data)]
async def execute_queue(self): execute = "return [" tasks = [] for i in range(25): task = self.queue.get_nowait() if task.data is None: task.data = {} execute += 'API.' + task.key + '({' execute += ", ".join( (f"{k}: \"" + str(v).replace('"', '\\"') + "\"") for k, v in task.data.items()) execute += '}), ' tasks.append(task) if self.queue.empty(): break execute += "];" try: self.requests += 1 result = await asyncio.shield(self.execute(execute)) except (asyncio.TimeoutError, json.decoder.JSONDecodeError): self.requests += 1 result = await asyncio.shield(self.execute(execute)) for task in tasks: if result: task_result = result.pop(0) if task_result is False: hues.error( f"Ошибка! Метод \"{task.key}\" ничего не вернул!") hues.error( f"Или введены неправильные данные или проблема в чём-то другом!" ) task.set_result(task_result) else: task.set_result(None)
def wrapper(function): if commands: # Если написали, какие команды используются # Первая команда - отображается в списке команд (чтобы не было много команд не было) self.first_command = commands[0] # Если хоть в 1 команде есть пробел - она состоит из двух слов if any(' ' in cmd.strip() for cmd in commands): hues.error( 'В плагине {} была использована команда из двух слов'. format(self.name)) for command in commands: self.add_func(command, function) elif not all_commands: # Если нет - используем имя плагина в качестве команды (в нижнем регистре) self.add_func(self.name.lower(), function) # Если нужно, реагируем на все команды else: self.add_func('', function) return function
def fetchSinglePage(url): now = datetime.datetime.now() filename = 'single-' + str(now.hour) + str(now.minute) + str( now.second) + str(now.microsecond) + '.html' filepath = os.path.dirname( os.path.realpath(__file__)) + '/html/single/' + filename command = 'wget -O ' + filepath + ' \"' + url + '\"' subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).stdout.read() if os.stat(filepath).st_size == 0: hues.error(filename + ' IS NOT DOWNLOADED') else: pass #hues.success(filename + ' DOWNLOADED') return
async def method(self, key: str, data=None): """Выполняет метод API VK с дополнительными параметрами""" if data is None: data = {} # Если мы работаем от имени группы if self.token: # Если метод доступен от имени группы - используем API группы if is_available_from_group(key): api_method = self.group_api # Если метод доступен от паблик апи - используем его elif is_available_from_public(key): api_method = self.public_api elif self.user_api: api_method = self.user_api else: hues.warn(f'Метод {key} нельзя вызвать от имени сообщества!') return {} else: api_method = self.user_api try: return await api_method(key, **data) except (asyncio.TimeoutError, json.decoder.JSONDecodeError): # Пытаемся отправить запрос к API ещё раз return await api_method(key, **data) except aiovk.exceptions.VkAuthError: message = 'TOKEN' if self.token else 'LOGIN и PASSWORD' fatal("Произошла ошибка при авторизации API, " f"проверьте значение {message} в settings.py!") except aiovk.exceptions.VkAPIError as ex: # Код 9 - Flood error - слишком много одинаковых сообщений if not ex.error_code == 9: hues.error("Произошла ошибка при вызове метода API " f"{key} с значениями {data}:\n{ex}") return {} if 'message' not in data: return {} data['message'] += f'\n Анти-флуд (API): {self.anti_flood()}' try: # Пытаемся отправить сообщение ещё раз await self.method('messages.send', data) except aiovk.exceptions.VkAPIError: # Не знаю, может ли это случиться, или нет hues.error('Обход анти-флуда API не удался =(') return {}
def _init_plugin_files(self): for folder_path, folder_names, filenames in os.walk(self.folder): for filename in filenames: if filename.endswith('.py') and filename != "__init__.py": if ENABLED_PLUGINS: if filename.replace('.py', '') not in ENABLED_PLUGINS: continue # path/to/plugins/plugin/foo.py # > foo.py # > foo full_plugin_path = os.path.join(folder_path, filename) base_plugin_path = os.path.relpath(full_plugin_path, self.folder) base_plugin_name = os.path.splitext( base_plugin_path)[0].replace(os.path.sep, '.') try: loader = machinery.SourceFileLoader( base_plugin_name, full_plugin_path) spec = util.spec_from_loader(loader.name, loader) loaded_module = util.module_from_spec(spec) loader.exec_module(loaded_module) # Если при загрузке плагина произошла какая-либо ошибка except Exception: result = traceback.format_exc() # если файла нет - создаём if not isfile('log.txt'): open('log.txt', 'w').close() with open('log.txt', 'a') as log: log.write(result) hues.error(f"Ошибка при загрузке плагина: {filename}") continue try: if not self.check_plugin(loaded_module.plugin): continue self.plugins.add(loaded_module.plugin) self.register_plugin(loaded_module.plugin) self.init_variables(loaded_module.plugin) self.init_plugin(loaded_module.plugin) # Если возникла ошибка - значит плагин не имеет атрибута plugin except AttributeError: continue
async def process_command(self, msg_obj: Message): """Обрабатывает команду (объект Message)""" cmd = Command(msg_obj._data, self.convert) if not cmd.has_prefix: return False # Если команда (обычная или сконвертированная) есть в списке команд if cmd.command in self.commands: pass # Если команды нет в списке команд - можно попробовать перевести # её в другую раскладку и проверить, есть ли конвертированная команда # в списке команд elif self.convert and cmd.try_convert() in self.commands: cmd.convert() # Если есть плагины, которые срабатывают на любые команды elif self.ANY_COMMANDS: pass # Не обрабатываем сообщение msg_obj else: return cmd_text = cmd.command # Логгируем команду, если нужно (но не логгируем плагины, # которые реагируют на любые команды) if settings.LOG_COMMANDS and not self.ANY_COMMANDS: cmd.log() try: await self.system.call_command(cmd_text, msg_obj, cmd.args) return True # Если в плагине произошла какая-то ошибка except Exception: await msg_obj.answer( f"{msg_obj.vk.anti_flood()}. " f"Произошла ошибка при выполнении команды <{cmd_text}> " "пожалуйста, сообщите об этом разработчику!") hues.error( f"Произошла ошибка при вызове команды '{cmd_text}' с аргументами {cmd.args}. " f"Текст сообщения: '{msg_obj._data}'." f"Ошибка:\n{traceback.format_exc()}")
async def enter_captcha(self, url, sid): if not solver: return hues.error( 'Введите данные для сервиса решения капч в settings.py!') with self.session as ses: async with ses.get(url) as resp: img_data = await resp.read() data = solver.solve_captcha(img_data) # hues.success(f"Капча {sid} решена успешно") return data
def get_requests(hostname, lines, conn, Proxy): """ build a requests object for a hostname :param hostname: :param lines: content of the file containing user-agents strings :param conn: connection to the database :param Proxy: connection through proxy :return: the answer to the request content or None """ # if the certificate is a wildcard, display it but no testing. # and return. if '*' in hostname: hues.warn('wildcard certificate: no request for ' + hostname) return None url = 'https://' + hostname headers = get_random_UserAgent_header(lines) # set proxy if Proxy: proxy = {"https": Proxy} else: proxy = "" try: r = requests.get(url, headers=headers, proxies=proxy, timeout=5) return r except requests.exceptions.SSLError as errs: # SSL error hues.error(" {} - SSL error".format(url)) return None except requests.exceptions.ConnectionError as errc: # other connection error hues.error(" {} - Connection error".format(url)) return None except requests.exceptions.RequestException as e: # A serious problem happened hues.error(" {} Error: {}".format(url, e)) return None except KeyboardInterrupt: print("get_requests() - Interrupt received, stopping ...") print("start - committing, closing DB") conn.commit conn.close print("ending - committing, closing DB") sys.exit(0) except Exception as ex: hues.error("get_requests() - any other kind of error: {}".format(ex)) return None
def fetchArchivePage(url): now = datetime.datetime.now() filename = 'archive-' + str(now.hour) + str(now.minute) + str( now.second) + str(now.microsecond) + '.html' filepath = os.path.dirname( os.path.realpath(__file__)) + '/html/' + filename #page = urlopen(url).read() #soup = BeautifulSoup(page, 'lxml') #print(soup) command = 'wget -O ' + filepath + ' \"' + url + '\"' subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).stdout.read() if os.stat(filepath).st_size == 0: hues.error(filename + ' IS NOT DOWNLOADED') else: pass #hues.success(filename + ' DOWNLOADED') return
def wrapper(func): if TOKEN and not group: # Если бот работает от токена, и плагин не работает от имени группы # мы не добавляем эту команду # Убираем usage, чтобы команда не отображалась в помощи self.usage = [] return func if commands: # Если написали, какие команды используются # Первая команда - отображается в списке команд (чтобы не было много команд не было) self.first_command = commands[0] # Если хоть в 1 команде есть пробел - она состоит из двух слов if any(' ' in cmd.strip() for cmd in commands): hues.error(f'В плагине {self.name} была ' 'использована команда из двух слов') for command in commands: self.add_func(command, func) elif not all_commands: # Если нет - используем имя плагина в качестве команды (в нижнем регистре) self.add_func(self.name.lower(), func) # Если нужно, реагируем на все команды else: self.add_func('', func) return func
async def login(username, password, session): captcha_url = 'https://m.vk.com/captcha.php' url_login = "******" login_form_data = { 'email': username, 'pass': password, } async with session.get(url_login) as resp: html = await resp.text() login_form_action = get_form_action(html) if not login_form_action: fatal("VK changed authentication flow") async with session.post(login_form_action, data=login_form_data) as resp: html = await resp.text() response_url_query = get_url_query(resp.url) cookies = [cookie.key for cookie in session.cookie_jar] if 'remixsid' in cookies or 'remixsid6' in cookies: return if 'sid' in response_url_query: await auth_captcha_is_needed(resp, login_form_data, captcha_url, session) elif response_url_query.get('act') == 'authcheck': await auth_check_is_needed(await resp.text(), session) elif 'security_check' in response_url_query: hues.error("Phone number is needed") else: hues.error("Authorization error (incorrect password)")
async def process_command(self, msg_obj: Message): """Обрабатывает команду (объект Message)""" cmd = Command(msg_obj) if not cmd.check_command(self): return cmd_text = cmd.command # Логгируем команду, если нужно (но не логгируем плагины, # которые реагируют на любые команды) if settings.LOG_COMMANDS and not self.ANY_COMMANDS: cmd.log() try: return await self.system.call_command(cmd_text, msg_obj, cmd.args) # Если в плагине произошла какая-то ошибка except Exception: await msg_obj.answer(f"{msg_obj.vk.anti_flood()}. " f"Произошла ошибка при выполнении команды <{cmd_text}> " "пожалуйста, сообщите об этом разработчику!") hues.error( f"Произошла ошибка при вызове команды '{cmd_text}' с аргументами {cmd.args}. " f"Текст сообщения: '{msg_obj._data}'." f"Ошибка:\n{traceback.format_exc()}")
async def method(self, key: str, data=None, send_from=None, nowait=False): """Выполняет метод API VK с дополнительными параметрами""" if send_from is None: if self.group and is_available_from_group(key): send_from = SendFrom.GROUP elif is_available_from_public(key): send_from = SendFrom.USER else: send_from = SendFrom.USER task = RequestFuture(key, data, send_from) client = None if self.users and send_from == SendFrom.USER: client = self.users[self.current_user % len(self.users)] self.current_user += 1 elif self.tokens and send_from == SendFrom.GROUP: client = self.tokens[self.current_token % len(self.tokens)] self.current_token += 1 if not client: hues.error( f"Для выполнения метода({task.key}) необходимо ввести недостающие данные пользователя " f"или токен группы.") return None client.queue.put_nowait(task) if nowait: return None return await asyncio.wait_for(task, None)
async def user(self, username, password, app_id, scope): self.username = username self.password = password self.app_id = app_id self.scope = scope retries = 5 for i in range(retries): self.token = await get_token(username, password, app_id, scope) if self.token: break if not self.token: return hues.error("Can't get token!") self_data = await self.execute("return API.account.getProfileInfo();") hues.info(f"Вошёл как: {self_data['first_name']} {self_data['last_name']} " f"(https://vk.com/{self_data['screen_name']})")
def parter(book, ver1, ver2): """ Function to print bible verset From file Matio 24:14 :param book: 'Matio' :param ver1: '24' :param ver2: '14' """ filename = getFileName(book) # open file filepath = "/data/data/com.termux/files/usr/share/bi12/FloatingBible/bi12_MG/OEBPS/" try: if int(ver1) == 1: filexht = open(filepath + filename + ".xhtml", "r") else: filexht = open(filepath + filename + "-split" + ver1 + ".xhtml", "r") except FileNotFoundError: hues.error("File not found") hues.error("Invalid chapter: " + ver1) return False # parse file soup = BeautifulSoup(filexht, "html.parser") print(color.green("[" + ver1 + "]"), ver2) # for multiples verset for sver2 in ver2: sver2 = str(sver2) vrs = u"chapter" + ver1 + "_verse" + sver2 try: stringPart = soup.find("span", attrs={ "id": vrs }).next.next.next.next except AttributeError: hues.error("Invalid verset: " + sver2) break # last print to show verset print( color.green(" | ") + color.blue("[" + sver2 + "]"), wrap(stringPart), )
#!/usr/bin/python import sys import json import hues from datetime import datetime from email import utils from os.path import expanduser HOME = expanduser("~") try: file = open(HOME + '/.local/share/fakedate.json') except FileNotFoundError: hues.error("please set fake date seed at ~/.local/share/fakedate.json") sys.exit() data = json.load(file) str = data['seed'] date = datetime.strptime(str + ", 2016", "%d %b, %Y").timestamp() now = datetime.now() today = now.date().strftime("%d %b, %Y") today_timestamp = datetime.strptime(today, "%d %b, %Y").timestamp() delta = now.timestamp() - today_timestamp fake_time = utils.formatdate(date + delta)
def fatal(*args): """Отправляет args в hues.error() и выходит""" hues.error(*args) exit()
def main(argv=None): """Run from the command line interface. """ argv = argv or sys.argv[1:] try: args = docopt.docopt(__doc__, argv, version='instaLooter {}'.format(__version__)) except docopt.DocoptExit as de: print(de) return 1 argv_positional = [param for param in argv if not param.startswith("-")] if argv_positional[0] in ("post", "hashtag") and len(argv_positional) < 3: print(usage()) return 1 if args['logout']: if not os.path.exists(InstaLooter.COOKIE_FILE): hues.error('Cookie file not found.') return 1 InstaLooter().logout() hues.success('Logged out.') return 0 elif args['login']: try: args['--username'] = six.moves.input('Username: '******'-W'] not in WARNING_ACTIONS: print("Unknown warning action: {}".format(args['-W'])) print(" available action: {}".format(', '.join(WARNING_ACTIONS))) return 1 if args['batch']: with open(args['<batch_file>']) as batch_file: batch_runner = BatchRunner(batch_file) batch_runner.runAll() return 0 with warnings.catch_warnings(): warnings.simplefilter(args['-W']) # if args['<hashtag>'] and not args['--credentials']: # warnings.warn("#hashtag downloading requires an Instagram account.") # return 1 if args['<post_token>'] is not None: args['--get-videos'] = True if args['--socks_port'] is not None: args['--socks_port'] = int(args['--socks_port']) if args['--control_port'] is not None: args['--control_port'] = int(args['--control_port']) if args['--change_ip_after'] is not None: args['--change_ip_after'] = int(args['--change_ip_after']) looter = InstaLooter( directory=os.path.expanduser( args.get('<directory>') or os.getcwd()), profile=args['<profile>'], hashtag=args['<hashtag>'], add_metadata=args['--add-metadata'], get_videos=args['--get-videos'], videos_only=args['--videos-only'], jobs=int(args['--jobs']), template=args['--template'], dump_json=args['--dump-json'], dump_only=args['--dump-only'], extended_dump=args['--extended-dump'], socks_port=args['--socks_port'], control_port=args['--control_port'], change_ip_after=args['--change_ip_after'], ) try: login(looter, args) if args['--time']: timeframe = get_times_from_cli(args['--time']) else: timeframe = None except ValueError as ve: console.error(ve) if args["--traceback"]: traceback.print_exc() return 1 try: post_token = args['<post_token>'] if post_token is None: media_count = int( args['--num-to-dl']) if args['--num-to-dl'] else None looter.download( media_count=media_count, with_pbar=not args['--quiet'], timeframe=timeframe, new_only=args['--new'], ) else: if 'insta' in post_token: post_token = looter._extract_code_from_url(post_token) looter.download_post(post_token) except Exception as e: console.error(e) if args["--traceback"]: traceback.print_exc() return 1 except KeyboardInterrupt: return 1 else: return 0
def logs(aims, conditions, wants, res, yesorno, others=""): """ 0 失败 1 成功 2 警告 """ #################################### 命令行即时输出 if yesorno == 0: yesornostr = u"测试点验证未通过, 请查阅具体记录" + others colorstr = "\033[1;31;40m" #红色 if yesorno == 1: yesornostr = u"测试点验证通过" + others colorstr = "\033[1;32;40m" #绿色 if yesorno == 2: yesornostr = u"警告, 请查阅具体记录" + others colorstr = "\033[1;33;40m" #橙黄色 closecolor = "\033[0m" ##### 非LINUX不支持以上模式的彩色日志输出 if platform.system() != "Linux": colorstr = "" closecolor = "" ###### print("---------------------------------------------------------") print(u"动作名称/目的: " + aims + " " + u"前置条件/判断类型:" + " " + conditions) outputlog = u"预期: " + wants + " " + u"实际结果:" + " " + res + " " + u"\n判定: " + yesornostr #print(colorstr + outputlog + closecolor ) ## 这种模式不兼容 windows , 因此暂时停止使用 ### 暂时使用以下模式 #hues.log hues.info hues.error hues.warn hues.success if yesorno == 0: hues.error(outputlog) if yesorno == 1: hues.success(outputlog) if yesorno == 2: hues.warn(outputlog) ################################################## 报告输出 #### 获得是否报告的标记位 reports = get_reports_tag() ##### 报告标记位正常 if reports != 0: doc = documents.doc doc.insert_text("\n") # 插入表格 doc.insert_text(u"★ 用例及记录 " + str(documents.ids) + u" 判定") ###### 颜色定义 gray = 0xcdc9c9 #灰色 green = 0x228b22 #绿色 if platform.system() == "Linux": red = 0xff4500 #红色 yellow = 0xffd700 #黄色 if platform.system() == "Windows": red = 0x0045ff #红色 yellow = 0x00d7ff #黄色 ###### 结论 表格 在最上方 mytable0 = doc.insert_table(3, 1) doc.table_setattr(mytable0, "A1", "BackColor", gray) doc.insert_tabletext(mytable0, "A1", u"自动化判定结果") # 时间 times = time.strftime('%Y-%m-%d %X', time.localtime()) doc.insert_tabletext(mytable0, "A2", times) if yesorno == 0: ### 错误时的突出显示 doc.table_setattr(mytable0, "A3", "BackColor", red) # 红色 if yesorno == 1: doc.table_setattr(mytable0, "A3", "BackColor", green) # 绿色 if yesorno == 2: doc.table_setattr(mytable0, "A3", "BackColor", yellow) # 黄色 doc.insert_tabletext(mytable0, "A3", yesornostr) ##### 前提 表格 mytable1 = doc.insert_table(2, 2) doc.table_setattr(mytable1, "A1", "BackColor", gray) doc.table_setattr(mytable1, "B1", "BackColor", gray) doc.insert_tabletext(mytable1, "A1", u"动作名称/目的") doc.insert_tabletext(mytable1, "B1", u"前置条件/判断类型") doc.insert_tabletext(mytable1, "A2", aims) doc.insert_tabletext(mytable1, "B2", conditions) ##### 预期和返回 表格 mytable2 = doc.insert_table(2, 2) doc.table_setattr(mytable2, "A1", "BackColor", gray) doc.table_setattr(mytable2, "B1", "BackColor", gray) doc.insert_tabletext(mytable2, "A1", u"自动化用例预期") doc.insert_tabletext(mytable2, "B1", u"自动化获取结果") doc.insert_tabletext(mytable2, "A2", wants) doc.insert_tabletext(mytable2, "B2", res) ### 用例号 documents.ids = documents.ids + 1 ############# 最后: 错误即抛出异常,以便捕获 if yesorno == 0: raise ValueError('测试用例识别到错误')