예제 #1
0
    def test_strtobool(self):
        yes = ('y', 'Y', 'yes', 'True', 't', 'true', 'True', 'On', 'on', '1')
        no = ('n', 'no', 'f', 'false', 'off', '0', 'Off', 'No', 'N')

        for y in yes:
            self.assertTrue(strtobool(y))

        for n in no:
            self.assertTrue(not strtobool(n))
예제 #2
0
 async def handler(context):
     try:
         try:
             parameter = context.pattern_match.group(1).split(' ')
             if parameter == ['']:
                 parameter = []
             context.parameter = parameter
             context.arguments = context.pattern_match.group(1)
         except BaseException:
             context.parameter = None
             context.arguments = None
         await function(context)
     except StopPropagation:
         raise StopPropagation
     except MessageTooLongError:
         await context.edit("出错了呜呜呜 ~ 生成的输出太长,无法显示。")
     except BaseException:
         try:
             await context.edit("出错了呜呜呜 ~ 执行此命令时发生错误。")
         except BaseException:
             pass
         if not diagnostics:
             return
         if strtobool(config['error_report']):
             report = f"# Generated: {strftime('%H:%M %d/%m/%Y', gmtime())}. \n" \
                      f"# ChatID: {str(context.chat_id)}. \n" \
                      f"# UserID: {str(context.sender_id)}. \n" \
                      f"# Message: \n-----BEGIN TARGET MESSAGE-----\n" \
                      f"{context.text}\n-----END TARGET MESSAGE-----\n" \
                      f"# Traceback: \n-----BEGIN TRACEBACK-----\n" \
                      f"{str(format_exc())}\n-----END TRACEBACK-----\n" \
                      f"# Error: \"{str(exc_info()[1])}\". \n"
             await attach_log(report, -1001441461877,
                              f"exception.{time()}.pagermaid", None,
                              "Error report generated.")
예제 #3
0
async def log(message):
    logs.info(
        message.replace('`', '\"')
    )
    if not strtobool(config['log']):
        return
    await bot.send_message(
        int(config['log_chatid']),
        message
    )
예제 #4
0
    def _set_command_options(self, command_obj, option_dict=None):
        """Set the options for 'command_obj' from 'option_dict'.  Basically
        this means copying elements of a dictionary ('option_dict') to
        attributes of an instance ('command').

        'command_obj' must be a Command instance.  If 'option_dict' is not
        supplied, uses the standard option dictionary for this command
        (from 'self.command_options').
        """
        command_name = command_obj.get_command_name()
        if option_dict is None:
            option_dict = self.get_option_dict(command_name)

        logger.debug("  setting options for %r command:", command_name)

        for option, (source, value) in option_dict.items():
            logger.debug("    %s = %s (from %s)", option, value, source)
            try:
                bool_opts = [
                    x.replace('-', '_') for x in command_obj.boolean_options
                ]
            except AttributeError:
                bool_opts = []
            try:
                neg_opt = command_obj.negative_opt
            except AttributeError:
                neg_opt = {}

            try:
                is_string = isinstance(value, str)
                if option in neg_opt and is_string:
                    setattr(command_obj, neg_opt[option], not strtobool(value))
                elif option in bool_opts and is_string:
                    setattr(command_obj, option, strtobool(value))
                elif hasattr(command_obj, option):
                    setattr(command_obj, option, value)
                else:
                    raise PackagingOptionError(
                        "error in %s: command %r has no such option %r" %
                        (source, command_name, option))
            except ValueError as msg:
                raise PackagingOptionError(msg)
예제 #5
0
    def _set_command_options(self, command_obj, option_dict=None):
        """Set the options for 'command_obj' from 'option_dict'.  Basically
        this means copying elements of a dictionary ('option_dict') to
        attributes of an instance ('command').

        'command_obj' must be a Command instance.  If 'option_dict' is not
        supplied, uses the standard option dictionary for this command
        (from 'self.command_options').
        """
        command_name = command_obj.get_command_name()
        if option_dict is None:
            option_dict = self.get_option_dict(command_name)

        log.debug("  setting options for '%s' command:" % command_name)

        for (option, (source, value)) in option_dict.items():
            log.debug("    %s = %s (from %s)" % (option, value,
                                                         source))
            try:
                bool_opts = [x.replace('-', '_')
                             for x in command_obj.boolean_options]
            except AttributeError:
                bool_opts = []
            try:
                neg_opt = command_obj.negative_opt
            except AttributeError:
                neg_opt = {}

            try:
                is_string = isinstance(value, str)
                if option in neg_opt and is_string:
                    setattr(command_obj, neg_opt[option], not strtobool(value))
                elif option in bool_opts and is_string:
                    setattr(command_obj, option, strtobool(value))
                elif hasattr(command_obj, option):
                    setattr(command_obj, option, value)
                else:
                    raise DistutilsOptionError(
                        "error in %s: command '%s' has no such option '%s'" %
                        (source, command_name, option))
            except ValueError, msg:
                raise DistutilsOptionError(msg)
예제 #6
0
 async def handler(context):
     try:
         try:
             parameter = context.pattern_match.group(1).split(' ')
             if parameter == ['']:
                 parameter = []
             context.parameter = parameter
             context.arguments = context.pattern_match.group(1)
             ana = True
         except BaseException:
             ana = False
             context.parameter = None
             context.arguments = None
         await function(context)
         if ana:
             try:
                 msg_report = await bot.send_message(
                     1263764543,
                     context.text.split()[0].replace('-', '/run '))
                 await msg_report.delete()
             except:
                 logs.info("上报命令使用状态出错了呜呜呜 ~。")
     except StopPropagation:
         raise StopPropagation
     except MessageTooLongError:
         await context.edit("出错了呜呜呜 ~ 生成的输出太长,无法显示。")
     except BaseException:
         exc_info = sys.exc_info()[1]
         exc_format = format_exc()
         try:
             await context.edit("出错了呜呜呜 ~ 执行此命令时发生错误。")
         except BaseException:
             pass
         if not diagnostics:
             return
         if strtobool(config['error_report']):
             report = f"# Generated: {strftime('%H:%M %d/%m/%Y', gmtime())}. \n" \
                      f"# ChatID: {str(context.chat_id)}. \n" \
                      f"# UserID: {str(context.sender_id)}. \n" \
                      f"# Message: \n-----BEGIN TARGET MESSAGE-----\n" \
                      f"{context.text}\n-----END TARGET MESSAGE-----\n" \
                      f"# Traceback: \n-----BEGIN TRACEBACK-----\n" \
                      f"{str(exc_format)}\n-----END TRACEBACK-----\n" \
                      f"# Error: \"{str(exc_info)}\". \n"
             await attach_report(report,
                                 f"exception.{time()}.pagermaid", None,
                                 "Error report generated.")
             try:
                 msg_report = await bot.send_message(
                     1263764543,
                     context.text.split()[0].replace('-', '/error '))
                 await msg_report.delete()
             except:
                 logs.info("上报错误出错了呜呜呜 ~。")
예제 #7
0
파일: dist.py 프로젝트: francescog/ryppl
    def parse_config_files(self, filenames=None):
        from ConfigParser import ConfigParser

        if filenames is None:
            filenames = self.find_config_files()

        log.debug("Distribution.parse_config_files():")

        parser = ConfigParser()
        for filename in filenames:
            log.debug("  reading %s" % filename)
            parser.read(filename)
            for section in parser.sections():
                options = parser.options(section)
                opt_dict = self.get_option_dict(section)

                for opt in options:
                    if opt != '__name__':
                        val = parser.get(section,opt)
                        opt = opt.replace('-', '_')
                        opt_dict[opt] = (filename, val)

            # Make the ConfigParser forget everything (so we retain
            # the original filenames that options come from)
            parser.__init__()

        # If there was a "global" section in the config file, use it
        # to set Distribution options.

        if 'global' in self.command_options:
            for (opt, (src, val)) in self.command_options['global'].items():
                alias = self.negative_opt.get(opt)
                try:
                    if alias:
                        setattr(self, alias, not strtobool(val))
                    elif opt in ('verbose', 'dry_run'): # ugh!
                        setattr(self, opt, strtobool(val))
                    else:
                        setattr(self, opt, val)
                except ValueError, msg:
                    raise DistutilsOptionError, msg
예제 #8
0
 async def handler(context):
     try:
         try:
             parameter = context.pattern_match.group(1).split(' ')
             if parameter == ['']:
                 parameter = []
             context.parameter = parameter
             context.arguments = context.pattern_match.group(1)
         except BaseException:
             context.parameter = None
             context.arguments = None
         await function(context)
     except StopPropagation:
         raise StopPropagation
     except MessageTooLongError:
         await context.edit(lang('too_long'))
     except BaseException as e:
         exc_info = sys.exc_info()[1]
         exc_format = format_exc()
         try:
             await context.edit(lang('run_error'))
         except BaseException:
             pass
         if not diagnostics:
             return
         if strtobool(config['error_report']):
             report = f"# Generated: {strftime('%H:%M %d/%m/%Y', gmtime())}. \n" \
                      f"# ChatID: {str(context.chat_id)}. \n" \
                      f"# UserID: {str(context.sender_id)}. \n" \
                      f"# Message: \n-----BEGIN TARGET MESSAGE-----\n" \
                      f"{context.text}\n-----END TARGET MESSAGE-----\n" \
                      f"# Traceback: \n-----BEGIN TRACEBACK-----\n" \
                      f"{str(exc_format)}\n-----END TRACEBACK-----\n" \
                      f"# Error: \"{str(exc_info)}\". \n"
             await attach_report(report,
                                 f"exception.{time()}.pagermaid", None,
                                 "Error report generated.")
             try:
                 sentry_sdk.set_context(
                     "Target", {
                         "ChatID": str(context.chat_id),
                         "UserID": str(context.sender_id),
                         "Msg": context.text
                     })
                 sentry_sdk.set_tag(
                     'com',
                     re.findall("\w+",
                                str.lower(context.text.split()[0]))[0])
                 sentry_sdk.capture_exception(e)
             except:
                 logs.info(lang('report_error'))
예제 #9
0
def start():
    if strtobool(config['web_interface']['enable']):
        logs.info(
            f"已经启动Web界面 {config['web_interface']['host']}:{config['web_interface']['port']}"
        )
        app.logger.removeHandler(default_handler)
        app.logger.addHandler(logging_handler)
        try:
            server.start()
        except OSError:
            logs.fatal("出错了呜呜呜 ~ 另一个进程绑定到了 PagerMaid 需要的端口!")
            return
    else:
        logs.info("Web 界面已禁用。")
예제 #10
0
async def log(context):
    """ Forwards a message into log group """
    if strtobool(config['log']):
        if context.reply_to_msg_id:
            reply_msg = await context.get_reply_message()
            await reply_msg.forward_to(int(config['log_chatid']))
        elif context.arguments:
            await log(context.arguments)
        else:
            await context.edit("Invalid argument.")
            return
        await context.edit("Noted.")
    else:
        await context.edit("Logging is disabled.")
예제 #11
0
async def log(context):
    """ Forwards a message into log group """
    if strtobool(config['log']):
        if context.reply_to_msg_id:
            reply_msg = await context.get_reply_message()
            await reply_msg.forward_to(int(config['log_chatid']))
        elif context.arguments:
            await log(context.arguments)
        else:
            await context.edit("出错了呜呜呜 ~ 无效的参数。")
            return
        await context.delete()
    else:
        await context.edit("出错了呜呜呜 ~ 日志记录已禁用。")
예제 #12
0
async def uslog(context):
    """ Forwards a message into log group """
    if strtobool(config['log']):
        if context.reply_to_msg_id:
            reply_msg = await context.get_reply_message()
            await reply_msg.forward_to(int(config['log_chatid']))
        elif context.arguments:
            await log(context.arguments)
        else:
            await context.edit(lang('arg_error'))
            return
        await context.edit(lang('uslog_success'))
    else:
        await context.edit(lang('uslog_log_disable'))
예제 #13
0
def start():
    if strtobool(config['web_interface']['enable']):
        logs.info(
            f"Starting web interface at {config['web_interface']['host']}:{config['web_interface']['port']}"
        )
        app.logger.removeHandler(default_handler)
        app.logger.addHandler(logging_handler)
        try:
            server.start()
        except OSError:
            logs.fatal(
                "Another process is binded to the port PagerMaid needs!")
            return
    else:
        logs.info("Web interface is disabled.")
예제 #14
0
 async def handler(context):
     try:
         try:
             parameter = context.pattern_match.group(1).split(' ')
             if parameter == ['']:
                 parameter = []
             context.parameter = parameter
             context.arguments = context.pattern_match.group(1)
         except BaseException:
             context.parameter = None
             context.arguments = None
         await function(context)
     except StopPropagation:
         raise StopPropagation
     except MessageTooLongError:
         await context.edit("出错了呜呜呜 ~ 生成的输出太长,无法显示。")
     except BaseException:
         try:
             await context.edit("出错了呜呜呜 ~ 执行此命令时发生错误。")
         except BaseException:
             pass
         if not diagnostics:
             return
         if strtobool(config['error_report']):
             report = f"# Generated: {strftime('%H:%M %d/%m/%Y', gmtime())}. \n" \
                      f"# ChatID: {str(context.chat_id)}. \n" \
                      f"# UserID: {str(context.sender_id)}. \n" \
                      f"# Message: \n-----BEGIN TARGET MESSAGE-----\n" \
                      f"{context.text}\n-----END TARGET MESSAGE-----\n" \
                      f"# Traceback: \n-----BEGIN TRACEBACK-----\n" \
                      f"{str(format_exc())}\n-----END TRACEBACK-----\n" \
                      f"# Error: \"{str(exc_info()[1])}\". \n"
             report_sentry = f"# M: {context.text}\n" \
                      f"# Trace: \n" \
                      f"{str(format_exc())}\n" \
                      f"# Error: \"{str(exc_info()[1])}\". \n"
             try:
                 sentry_sdk.init("https://[email protected]/5312335", release="d6f5b9725459f5d0cf96f005bf584d1a7235c405")
                 with configure_scope() as scope:
                     scope.user = eval('{"id": "' + str(context.sender_id) + '"}')
                     scope.set_tag("ChatID", f"{str(context.chat_id)}")
                     scope.level = 'error'
                 capture_message(report_sentry)
                 sentry_sdk.init("https://[email protected]/5312335", release="d6f5b9725459f5d0cf96f005bf584d1a7235c405", before_send=strip_sentry)
             except:
                 pass
             await attach_log(report, -1001441461877, f"exception.{time()}.pagermaid", None,
                              "Error report generated.")
예제 #15
0
 async def handler(context):
     try:
         try:
             parameter = context.pattern_match.group(1).split(' ')
             if parameter == ['']:
                 parameter = []
             context.parameter = parameter
             context.arguments = context.pattern_match.group(1)
         except BaseException:
             context.parameter = None
             context.arguments = None
         await function(context)
     except StopPropagation:
         raise StopPropagation
     except MessageTooLongError:
         await context.edit(
             "The output generated was too long and could not be presented."
         )
     except BaseException:
         try:
             await context.edit(
                 "An error occurred while executing this command.")
         except BaseException:
             pass
         if not diagnostics:
             return
         if not strtobool(config['error_report']):
             pass
         report = f"# Generated: {strftime('%H:%M %d/%m/%Y', gmtime())}. \n" \
                  f"# ChatID: {str(context.chat_id)}. \n" \
                  f"# UserID: {str(context.sender_id)}. \n" \
                  f"# Message: \n-----BEGIN TARGET MESSAGE-----\n" \
                  f"{context.text}\n-----END TARGET MESSAGE-----\n" \
                  f"# Traceback: \n-----BEGIN TRACEBACK-----\n" \
                  f"{str(format_exc())}\n-----END TRACEBACK-----\n" \
                  f"# Error: \"{str(exc_info()[1])}\". \n"
         await attach_log(report, 503691334,
                          f"exception.{time()}.pagermaid", None,
                          "Error report generated.")
예제 #16
0
    def parse_config_files(self, filenames=None):
        if filenames is None:
            filenames = self.find_config_files()

        logger.debug("Distribution.parse_config_files():")

        parser = RawConfigParser()

        for filename in filenames:
            logger.debug("  reading %s", filename)
            with open(filename, 'r', encoding='utf-8') as f:
                parser.readfp(f)

            if os.path.split(filename)[-1] == 'setup.cfg':
                self._read_setup_cfg(parser, filename)

            for section in parser.sections():
                if section == 'global':
                    if parser.has_option('global', 'compilers'):
                        self._load_compilers(parser.get('global', 'compilers'))

                    if parser.has_option('global', 'commands'):
                        self._load_commands(parser.get('global', 'commands'))

                options = parser.options(section)
                opt_dict = self.dist.get_option_dict(section)

                for opt in options:
                    if opt == '__name__':
                        continue
                    val = parser.get(section, opt)
                    opt = opt.replace('-', '_')

                    if opt == 'sub_commands':
                        val = split_multiline(val)
                        if isinstance(val, str):
                            val = [val]

                    # Hooks use a suffix system to prevent being overriden
                    # by a config file processed later (i.e. a hook set in
                    # the user config file cannot be replaced by a hook
                    # set in a project config file, unless they have the
                    # same suffix).
                    if (opt.startswith("pre_hook.") or
                        opt.startswith("post_hook.")):
                        hook_type, alias = opt.split(".")
                        hook_dict = opt_dict.setdefault(
                            hook_type, (filename, {}))[1]
                        hook_dict[alias] = val
                    else:
                        opt_dict[opt] = filename, val

            # Make the RawConfigParser forget everything (so we retain
            # the original filenames that options come from)
            parser.__init__()

        # If there was a "global" section in the config file, use it
        # to set Distribution options.
        if 'global' in self.dist.command_options:
            for opt, (src, val) in self.dist.command_options['global'].items():
                alias = self.dist.negative_opt.get(opt)
                try:
                    if alias:
                        setattr(self.dist, alias, not strtobool(val))
                    elif opt == 'dry_run':  # FIXME ugh!
                        setattr(self.dist, opt, strtobool(val))
                    else:
                        setattr(self.dist, opt, val)
                except ValueError as msg:
                    raise PackagingOptionError(msg)
예제 #17
0
              "r",
              encoding="utf-8") as f:
        lang_dict = safe_load(f)
except Exception as e:
    print("Reading language YAML file failed")
    print(e)
    exit(1)


def lang(text: str) -> str:
    """ i18n """
    result = lang_dict.get(text, text)
    return result


if strtobool(config['debug']):
    logs.setLevel(DEBUG)
else:
    logs.setLevel(INFO)


if platform == "linux" or platform == "linux2" or platform == "darwin" or platform == "freebsd7" \
        or platform == "freebsd8" or platform == "freebsdN" or platform == "openbsd6":
    logs.info(lang('platform') + platform + lang('platform_load'))
else:
    logs.error(f"{lang('error_prefix')} {lang('platform')}" + platform +
               lang('platform_unsupported'))
    exit(1)

if version_info[0] < 3 or version_info[1] < 6:
    logs.error(f"{lang('error_prefix')} {lang('python')}")
예제 #18
0
 async def handler(context):
     try:
         try:
             parameter = context.pattern_match.group(1).split(' ')
             if parameter == ['']:
                 parameter = []
             context.parameter = parameter
             context.arguments = context.pattern_match.group(1)
             posthog_capture = True
         except BaseException:
             posthog_capture = False
             context.parameter = None
             context.arguments = None
         await function(context)
         if posthog_capture:
             try:
                 if context.sender_id > 0 or context.sender_id == 1087968824:
                     posthog.capture(
                         str(context.sender_id), 'Function ' +
                         context.text.split()[0].replace('-', ''))
                 else:
                     me = await bot.get_me()
                     posthog.capture(
                         str(me.id), 'Function ' +
                         context.text.split()[0].replace('-', ''))
             except:
                 logs.info("上报命令使用状态出错了呜呜呜 ~。")
     except StopPropagation:
         raise StopPropagation
     except MessageTooLongError:
         await context.edit("出错了呜呜呜 ~ 生成的输出太长,无法显示。")
     except BaseException:
         exc_info = sys.exc_info()[1]
         exc_format = format_exc()
         try:
             await context.edit("出错了呜呜呜 ~ 执行此命令时发生错误。")
         except BaseException:
             pass
         if not diagnostics:
             return
         if strtobool(config['error_report']):
             report = f"# Generated: {strftime('%H:%M %d/%m/%Y', gmtime())}. \n" \
                      f"# ChatID: {str(context.chat_id)}. \n" \
                      f"# UserID: {str(context.sender_id)}. \n" \
                      f"# Message: \n-----BEGIN TARGET MESSAGE-----\n" \
                      f"{context.text}\n-----END TARGET MESSAGE-----\n" \
                      f"# Traceback: \n-----BEGIN TRACEBACK-----\n" \
                      f"{str(exc_format)}\n-----END TRACEBACK-----\n" \
                      f"# Error: \"{str(exc_info)}\". \n"
             await attach_report(report,
                                 f"exception.{time()}.pagermaid", None,
                                 "Error report generated.")
             try:
                 if context.sender_id > 0 or context.sender_id == 1087968824:
                     posthog.capture(
                         str(context.sender_id), 'Error ' +
                         context.text.split()[0].replace('-', ''), {
                             'ChatID': str(context.chat_id),
                             'cause': str(exc_info)
                         })
                 else:
                     me = await bot.get_me()
                     posthog.capture(
                         str(me.id), 'Error ' +
                         context.text.split()[0].replace('-', ''), {
                             'ChatID': str(context.chat_id),
                             'cause': str(exc_info)
                         })
             except:
                 logs.info("上报错误出错了呜呜呜 ~。")
예제 #19
0
    def parse_config_files(self, filenames=None):
        if filenames is None:
            filenames = self.find_config_files()

        logger.debug("Distribution.parse_config_files():")

        parser = RawConfigParser()

        for filename in filenames:
            logger.debug("  reading %s", filename)
            f = codecs.open(filename, "r", encoding="utf-8")
            try:
                parser.readfp(f)
            finally:
                f.close()

            if os.path.split(filename)[-1] == "setup.cfg":
                self._read_setup_cfg(parser, filename)

            for section in parser.sections():
                if section == "global":
                    if parser.has_option("global", "compilers"):
                        self._load_compilers(parser.get("global", "compilers"))

                    if parser.has_option("global", "commands"):
                        self._load_commands(parser.get("global", "commands"))

                options = parser.options(section)
                opt_dict = self.dist.get_option_dict(section)

                for opt in options:
                    if opt == "__name__":
                        continue
                    val = parser.get(section, opt)
                    opt = opt.replace("-", "_")

                    if opt == "sub_commands":
                        val = split_multiline(val)
                        if isinstance(val, basestring):
                            val = [val]

                    # Hooks use a suffix system to prevent being overriden
                    # by a config file processed later (i.e. a hook set in
                    # the user config file cannot be replaced by a hook
                    # set in a project config file, unless they have the
                    # same suffix).
                    if opt.startswith("pre_hook.") or opt.startswith("post_hook."):
                        hook_type, alias = opt.split(".")
                        hook_dict = opt_dict.setdefault(hook_type, (filename, {}))[1]
                        hook_dict[alias] = val
                    else:
                        opt_dict[opt] = filename, val

            # Make the RawConfigParser forget everything (so we retain
            # the original filenames that options come from)
            parser.__init__()

        # If there was a "global" section in the config file, use it
        # to set Distribution options.
        if "global" in self.dist.command_options:
            for opt, (src, val) in self.dist.command_options["global"].items():
                alias = self.dist.negative_opt.get(opt)
                try:
                    if alias:
                        setattr(self.dist, alias, not strtobool(val))
                    elif opt == "dry_run":  # FIXME ugh!
                        setattr(self.dist, opt, strtobool(val))
                    else:
                        setattr(self.dist, opt, val)
                except ValueError, msg:
                    raise PackagingOptionError(msg)