コード例 #1
0
def idle():
    try:
        while variables.running:
            time.sleep(10)
    except KeyboardInterrupt:
        log.w("Keyboard interrupt, stopping...")
        stop()
コード例 #2
0
ファイル: bot.py プロジェクト: KaikyuLotus/kitsu-ultimate
 def _updater(self):
     last_update = None
     try:
         updates = methods.get_updates(self.token, self.offset, 120)
         for update in updates:
             last_update = update
             t = time.process_time_ns()
             self._update_elaborator(update)
             elapsed_time = (time.process_time_ns() - t) / 1_000_000
             if elapsed_time > 50:
                 log.w(f"Update #{update['update_id']} elaboration "
                       f"took {elapsed_time} ms")
         last_update = None
     except Unauthorized:
         log.e(f"Unauthorized bot {self.bot_id}, detaching...")
         lotus_interface.detach_bot(self.token)
     except Conflict:
         log.e(
             f"Telegram said that bot {self.bot_id} is already running, detaching..."
         )
         lotus_interface.detach_bot(self.token)
     except requests.ConnectionError:
         log.e(
             f"A connection error happened, waiting {_connection_retry_time} seconds before reconnecting"
         )
         time.sleep(_connection_retry_time)
     except BadRequest as e:
         log.w(f"Warning, telegram said: {e.message}")
     except Exception as e:
         log.e('Error on line {}'.format(sys.exc_info()[-1].tb_lineno),
               type(e).__name__, e)
         traceback.print_tb(e.__traceback__)
         if last_update:
             pprint(last_update)
コード例 #3
0
def parse_dummies(reply: str, infos) -> str:

    for dummy_t in dummies:
        if dummy_t == "$on_reply":
            if not infos.is_reply:
                continue

        for dummy in dummies[dummy_t]:
            if dummy in reply:
                if dummy.startswith(">") and dummy.endswith("<"):
                    if not infos.user.is_maker_owner:
                        continue
                # eval is dangerous but here it's totally under control
                to_execute = dummies[dummy_t][dummy]
                if isinstance(to_execute, str):
                    reply = reply.replace(dummy, str(eval(to_execute)))
                elif callable(to_execute):
                    sign = signature(to_execute)
                    if len(sign.parameters) == 1:
                        reply = reply.replace(dummy, str(to_execute(infos)))
                    else:
                        reply = reply.replace(dummy, str(to_execute()))
                else:
                    log.w("Unknown dummy execution type")
    return reply
コード例 #4
0
ファイル: lotus.py プロジェクト: KaikyuLotus/kitsu-ultimate
def attach_bots(tokens: list):
    log.d(f"Attaching {len(tokens)} bots")
    if not isinstance(tokens, list):
        log.w("You must pass a list to attach_bots,"
              " operation cancelled.")
    else:
        for token in tokens:
            if is_bot_token(token):
                attach_bot_by_token(token)
            else:
                log.w(f"Invalid token {token} skipping.")
コード例 #5
0
ファイル: lotus.py プロジェクト: KaikyuLotus/kitsu-ultimate
def attach_bot_by_token(token: str):
    try:
        log.d(f"Attaching bot {token}")
        b = Bot(token)
        variables.attached_bots.append(b)
        log.d(f"Bot {b.bot_id} attached successfully")
        return True
    except Unauthorized:
        log.w(f"Wrong bot token: {token}")
    except TelegramException as error:
        error_name = error.__class__.__name__
        log.e(f"Exception '{error_name}' "
              f"while initializing the bot: {error}")
    return False
コード例 #6
0
 def elaborate_data(self, data) -> str:
     try:
         data = dict(data)
         for key in data:
             if not callable(data[key]):
                 return "every value in the dict must be a callable."
         reply_parser.dummies["$base"] = {
             **reply_parser.dummies["$base"],
             **data
         }
         count = len(data)
         return f"loaded {count} custom {'dummy' if count == 1 else 'dummies'}"
     except ValueError as err:
         log.w(str(err))
         return "returned bad data."
コード例 #7
0
def get(ctx: click.core.Context, filename: str, dir: str, to_usb: bool, convert: bool, merge: bool, debug: bool):
    """
    引数に指定したファイルを取得します。省略した場合は新たに取得します。
    """
    # for debug
    if debug:
        log.set_level(log.Level.DEBUG)

    p = __get_params(ctx)

    if to_usb:
        if convert or merge:
            log.w("USB出力時は--convert, --mergeオプションは無視されます.")
        p.remote_dist_dir = os.path.join(p.usb_dir, dir)
    else:
        p.local_dist_dir = os.path.join(os.getcwd(), dir)

    # execute command
    files = None
    ret = True
    try:
        if filename is None:
            files = remote.RemoteLogger(p).get_log(to_usb)
        else:
            files = remote.RemoteLogger(p).move_log(filename, to_usb)

        if convert and not to_usb and files is not None:
            cp = conv.ConvertParams()
            cp.script_path = p.convert_rule
            for f in files:
                cp.log_path = f
                ret, out_dir = conv.Converter(cp).exec()
                ret &= ret
                if merge and not (out_dir is None):
                    ret &= mrg.Merge().exec(os.path.join(out_dir, p.merge_dir))

    except IOError as e:
        ret = False
        click.echo(e.args)
    except Exception as e:
        ret = False
        click.echo(e.args)

    # finished
    if not files is None and ret:
        click.echo("正常に終了しました。")
    else:
        click.echo("失敗しました。")
コード例 #8
0
ファイル: watch.py プロジェクト: ujiro99/auto_logger
def file(dirname, filename, timeout):
    """
    Wait until a file created.
    :param str dirname: Directory path to be watched.
    :param str filename: File name to be watched.
    :param num timeout: How many seconds to be wait. [sec]
    :return: Is created the file.
    :rtype bool
    """
    is_glob = filename.find('*') >= 0
    handler = ChangeHandler(dirname, filename, is_glob)
    observer = Observer()
    observer.schedule(handler, dirname, recursive=False)
    observer.start()

    try:
        UPDATE_INTERVAL = 0.5
        interval = UPDATE_INTERVAL
        while interval >= 0 and timeout > 0:
            time.sleep(0.1)
            timeout -= 0.1
            interval -= 0.1
            log.d('- time out remain %.2f, update interval %.2f' %
                  (timeout, interval))
            if handler.modified is True:
                log.i('- now writing... %s ' % filename)
                handler.modified = False
                interval = UPDATE_INTERVAL

    except KeyboardInterrupt:
        observer.stop()

    if not is_glob:
        is_exists = os.path.exists(os.path.join(dirname, filename))
        if is_exists:
            if timeout <= 0:
                log.w("- The file still updating.")
        else:
            log.i("- time out")
            return False

    observer.stop()
    observer.join(timeout)

    return True
コード例 #9
0
ファイル: lotus.py プロジェクト: KaikyuLotus/kitsu-ultimate
def _elab_module_fun(function, instance, Module):
    if not hasattr(instance, function.name):
        if not function.optional:
            log.w(f"{Module.__name__} has no function {function.name}")
        return function.optional

    real_function = getattr(instance, function.name)
    if not callable(real_function):
        if not function.optional:
            log.w(f"{Module.__name__}.{function.name} is not a function")
        return function.optional

    if function.name == "on_new_trigger":
        variables.on_new_trigger_functions.append(real_function)
        log.i("Registered callback")
        return True
    if function.name == "on_trigger_change":
        variables.on_trigger_change_functions.append(real_function)
        log.i("Registered callback")
        return True

    return_value = real_function()
    if type(return_value) is not function.type:
        log.w(f"{Module.__name__}.{function.name} returns '{type(return_value).__name__}',"
              f" '{type(function.type).__name__}' is required")
        return False

    log_string = function.elaborate_data(return_value)
    log.i(f"Module: {log_string}")
    return True
コード例 #10
0
def elaborate_multx(reply: str, infos):
    last_msg_id = None
    for action, var in re.findall(
            r"(send|action|wait|edit):(?:(.+?)(?: then|]$))", reply,
            re.DOTALL):
        # TODO this can cause loops
        log.d(f"Action: {action}, var: {var}")
        if action == "send" or action == "edit":
            # dialogs = mongo_interface.get_dialogs_of_section(infos.bot.bot_id, var, infos.db.language)
            # if not dialogs:
            #     log.d(f"No dialogs for section {var}")
            #     continue
            # dialog = choice(dialogs)
            # log.d(f"Choosed reply {dialog.reply}")
            if action == "send":
                last_msg_id = infos.reply(var, parse_mode=None)["message_id"]
            else:
                if not last_msg_id:
                    log.w(
                        "This action has not sent a message before, so there's nothing to edit."
                    )
                    continue
                infos.edit(var, parse_mode=None, msg_id=last_msg_id)
        elif action == "action":
            actions = {"type": "typing"}
            if var not in actions:
                log.d(f"Unknown action: {var}")
                continue
            methods.send_chat_action(infos.bot.token, infos.chat.cid,
                                     actions[var])
        elif action == "wait":
            try:
                var = int(var)
            except ValueError:
                log.w(f"Invalid value: {var}")
                continue
            time.sleep(var)
コード例 #11
0
    def __is_files_exists(self):
        """
        Checks required files exists.
        :return: True: All file exists. False: Not exists.
        :rtype bool
        """
        if (not self.__p.log_path is None) and (not os.path.exists(
                self.__p.log_path)):
            log.w("- not found: %s" % self.__p.log_path)
            return False
        if (not self.__p.file is None) and (not os.path.exists(self.__p.file)):
            log.w("- not found: %s" % self.__p.file)
            return False
        if not os.path.exists(self.__p.script_path):
            log.w("- not found: %s" % self.__p.script_path)
            return False

        return True
コード例 #12
0
ファイル: test_log.py プロジェクト: ujiro99/auto_logger
 def test_color(self):
     log.d("debug")
     log.i("info")
     log.w("warn")
     log.e("error")
コード例 #13
0
ファイル: test_log.py プロジェクト: ujiro99/auto_logger
    def test_w(self):
        out = io.StringIO()
        log.logger.addHandler(StreamHandler(stream=out))

        log.w("message")
        self.assertEqual(out.getvalue(), "message\n")
コード例 #14
0
ファイル: lotus.py プロジェクト: KaikyuLotus/kitsu-ultimate
def load_module(Module: Type):
    module = Module()
    for function in _overrideable_module_function:
        if not _elab_module_fun(function, module, Module):
            log.w(f"Incompatible module, stopping load of {Module.__name__}")
            break