当前位置: 首页>>代码示例>>Python>>正文


Python StorageManager.get_file方法代码示例

本文整理汇总了Python中system.storage.manager.StorageManager.get_file方法的典型用法代码示例。如果您正苦于以下问题:Python StorageManager.get_file方法的具体用法?Python StorageManager.get_file怎么用?Python StorageManager.get_file使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在system.storage.manager.StorageManager的用法示例。


在下文中一共展示了StorageManager.get_file方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: ItemsPlugin

# 需要导入模块: from system.storage.manager import StorageManager [as 别名]
# 或者: from system.storage.manager.StorageManager import get_file [as 别名]
class ItemsPlugin(plugin.PluginObject):

    commands = None

    config = None
    data = None
    storage = None

    handler = None

    @property
    def storage_type(self):
        if self.config["storage"].lower() == "json":
            return "json"
        return "sqlite"

    def setup(self):
        self.commands = CommandManager()
        self.storage = StorageManager()

        self.logger.trace("Entered setup method.")
        try:
            self.config = self.storage.get_file(self, "config", YAML,
                                                "plugins/items.yml")
        except Exception:
            self.logger.exception("Error loading configuration!")
            self.logger.warn("Defaulting to SQLite for storage.")
        else:
            if not self.config.exists:
                self.logger.warn("Unable to find config/plugins/items.yml")
                self.logger.warn("Defaulting to SQLite for storage.")
            else:
                self.logger.info("Using storage type: %s" % self.storage_type)

        self._load()
        self.config.add_callback(self._load)

        self.commands.register_command("give", self.give_command, self,
                                       "items.give", default=True)
        self.commands.register_command("get", self.get_command, self,
                                       "items.get", default=True)

    def _load(self):
        if self.storage_type == "json":
            self.handler = JSONType(self, self.storage, self.logger)
        else:
            self.handler = SQLiteType(self, self.storage, self.logger)

    @RateLimiter(5, 0, 10)
    def give_command(self, *args, **kwargs):
        return self.handler.give_command(*args, **kwargs)

    @RateLimiter(5, 0, 10)
    def get_command(self, *args, **kwargs):
        return self.handler.get_command(*args, **kwargs)
开发者ID:domainr,项目名称:Ultros-contrib,代码行数:57,代码来源:__init__.py

示例2: WebhooksPlugin

# 需要导入模块: from system.storage.manager import StorageManager [as 别名]
# 或者: from system.storage.manager.StorageManager import get_file [as 别名]
class WebhooksPlugin(plugin.PluginObject):

    config = None
    data = None

    commands = None
    events = None
    plugins = None
    storage = None

    @property
    def web(self):
        """
        :rtype: plugins.web.WebPlugin
        """
        return self.plugins.get_plugin("Web")

    def setup(self):
        self.logger.trace("Entered setup method.")

        self.commands = CommandManager()
        self.events = EventManager()
        self.plugins = PluginManager()
        self.storage = StorageManager()

        try:
            self.config = self.storage.get_file(self, "config", YAML, "plugins/webhooks.yml")
        except Exception:
            self.logger.exception("Error loading configuration!")
            return self._disable_self()
        else:
            if not self.config.exists:
                self.logger.error("Unable to find config/plugins/webhooks.yml")
                return self._disable_self()

        self._load()
        self.config.add_callback(self._load)

        self.events.add_callback("Web/ServerStartedEvent", self, self.add_routes, 0)

    def _load(self):
        pass

    def add_routes(self, _=None):
        self.web.add_navbar_entry("Webhooks", "/webhooks", "url")
        self.web.add_handler("/webhooks", "plugins.webhooks.routes.webhooks.Route")
        self.logger.info("Registered route: /webhooks")

    pass  # So the regions work in PyCharm
开发者ID:EionRobb,项目名称:Ultros-contrib,代码行数:51,代码来源:__init__.py

示例3: MemosPlugin

# 需要导入模块: from system.storage.manager import StorageManager [as 别名]
# 或者: from system.storage.manager.StorageManager import get_file [as 别名]
class MemosPlugin(plugin.PluginObject):
    storage = None
    data = {}

    def setup(self):
        self.storage = StorageManager()
        self.data = self.storage.get_file(self, "data", YAML,
                                          "plugins/memos/memos.yml")

        self.commands.register_command("memo", self.memo, self, default=True,
                                       permission="memos.memo")

        self.events.add_callback("PreMessageReceived", self,
                                 self.message_received, 0)

    def memo(self, protocol, caller, source, command, raw_args, args):
        if args is None:
            args = raw_args.split()

        if len(args) < 2:
            caller.respond("Usage: {CHARS}memo <user> <message>")
            return

        user = args[0]
        message = "[{0}]: {1}".format(caller.name, " ".join(args[1:]))

        with self.data:
            if protocol.name in self.data:
                if user in self.data[protocol.name]:
                    self.data[protocol.name][user].append(message)
                else:
                    self.data[protocol.name].update({user: [message]})
            else:
                self.data[protocol.name] = {user: [message]}

        source.respond("I'll send it to {0}".format(user))

    def message_received(self, event=PreMessageReceived):
        if event.caller.name in self.data:
            if event.source.name in self.data[event.caller.name]:
                event.source.respond('Message for {0}: {1}'.format(
                    event.source.name,
                    self.data[event.caller.name][event.source.name]
                ))

                with self.data:
                    del self.data[event.caller.name][event.source.name]
开发者ID:EionRobb,项目名称:Ultros-contrib,代码行数:49,代码来源:__init__.py

示例4: MoneyPlugin

# 需要导入模块: from system.storage.manager import StorageManager [as 别名]
# 或者: from system.storage.manager.StorageManager import get_file [as 别名]
class MoneyPlugin(plugin.PluginObject):

    rates_table = None
    rates_table_updated = datetime.now()

    config = None
    commands = None
    storage = None

    @property
    def precision(self):
        return self.config.get("precision", 2)

    def setup(self):
        self.storage = StorageManager()
        self.config = self.storage.get_file(self, "config", YAML,
                                            "plugins/money.yml")

        self.commands = command_manager.CommandManager()
        self.commands.register_command("money", self.money_command_called,
                                       self, "money.main", default=True)

        self._load()

        self.config.add_callback(self._load)

    def _load(self):
        mpmath.mp.dps = self.precision

        self.rates_table_updated = datetime.now()
        self.rates_table = self.get_rates_table(ignore_time=True)

    def decode_rates_table(self, data):
        rates_json = json.loads(data)
        rates_table = rates_json['rates']
        rates_table["PHTLR"] = 2.43
        rates_table["HTLR"] = (2.43 * 0.000000000001)
        return rates_table

    def get_rates_table(self, ignore_time=False):
        now = datetime.now()
        if ((now - self.rates_table_updated) > timedelta(hours=1)) \
           or ignore_time:
            # We need to get new data
            if "API-key" in self.config:
                self.logger.debug("Rates table has expired, fetching new data."
                                  "..")
                r = urllib.urlopen("http://openexchangerates.org/api/latest.js"
                                   "on?app_id=" + self.config["API-key"])
                d = r.read()

                self.rates_table_updated = datetime.now()
                return self.decode_rates_table(d)
            else:
                self.logger.error("API-key not found in config file!")
                return self.rates_table
        else:
            # The old data is still usable
            self.logger.trace("Rates table is still valid, not fetching.")
            return self.rates_table

    def money_command_called(self, protocol, caller, source, command, raw_args,
                             parsed_args):
        args = raw_args.split()  # Quick fix for new command handler signature
        # This is called when a user types .money in chat
        if len(args) < 2:
            # at least 2 arguments are needed, if the user has
            # entered one or none:
            caller.respond(
                "Usage: {CHARS}money <value> <start currency> [<end currency 1"
                "> <end currency 2>...] i.e: money 15 GBP USD")
        else:  # 2 args or more:
            self.rates_table = self.get_rates_table()
            # update the rates table if we need to.

            start_val = args[0]  # the amount of money to convert from
            start_currency = args[1]  # the currency that the above refers to
            start_currency = start_currency.upper()  # uppercase dat

            if start_currency not in self.rates_table:
                caller.respond("Unknown currency: %s" % start_currency)
                return

            end_currencies = None  # list of currencies to convert to
            if len(args) == 2:  # create the list of end currencies.
                if "default-currs" in self.config:
                    end_currencies = self.config["default-currs"]
                    # get the default if none specified
                else:
                    self.logger.error("default-currs not found in config "
                                      "file!")
            else:
                end_currencies = args[2:]  # get what the user specified
            done = []
            for i in end_currencies:  # convert each currency in turn
                i = i.upper()
                if start_currency != i:
                    # exclude the start currency from the
                    # end currencies because it's redundant.
                    if i not in self.rates_table:
#.........这里部分代码省略.........
开发者ID:domainr,项目名称:Ultros-contrib,代码行数:103,代码来源:__init__.py

示例5: DicePlugin

# 需要导入模块: from system.storage.manager import StorageManager [as 别名]
# 或者: from system.storage.manager.StorageManager import get_file [as 别名]
class DicePlugin(plugin.PluginObject):

    _MODS_REGEX = re.compile(
        r"(?P<sort>s)|(?P<total>t)|(?:\^(?P<high>\d+))|(?:v(?P<low>\d+))"
    )
    _ROLL_REGEX = re.compile(
        r"^(?P<dice>\d+)?(?:d(?P<sides>\d+))?(?P<mods>(?:t|s|\^\d+|v\d+)*)?$"
    )

    _commands = None
    _config = None
    _storage = None

    def setup(self):
        ### Grab important shit
        self._commands = CommandManager()
        self._storage = StorageManager()

        ### Initial config load
        try:
            self._config = self._storage.get_file(self, "config", YAML,
                                                  "plugins/dice.yml")
        except Exception:
            self.logger.exception("Error loading configuration!")
            self.logger.error("Disabling...")
            self._disable_self()
            return
        if not self._config.exists:
            self.logger.error("Unable to find config/plugins/dice.yml")
            self.logger.error("Disabling...")
            self._disable_self()
            return

        ### Register commands
        self._commands.register_command("roll",
                                        self.roll_cmd,
                                        self,
                                        "dice.roll",
                                        aliases=["dice"],
                                        default=True)

    @property
    def max_dice(self):
        return self._config["max_dice"]

    @property
    def max_sides(self):
        return self._config["max_sides"]

    @property
    def default_dice(self):
        return self._config["default_dice"]

    @property
    def default_sides(self):
        return self._config["default_sides"]

    def _respond(self, target, msg):
        target.respond("Dice: %s" % msg)

    def roll_cmd(self, protocol, caller, source, command, raw_args,
                 parsed_args):
        try:
            result = self.roll(raw_args)
            self._respond(source, str(result))
        except DiceFormatError:
            self._respond(caller, "Usage: {CHARS}%s [roll info]" % command)
        except NotEnoughDice:
            self._respond(caller, "Too many dice.")
        except NotEnoughSides:
            self._respond(caller, "Too many sides.")

    def roll(self, description=""):
        match = self._ROLL_REGEX.match(description.strip())
        if match is None:
            raise DiceFormatError("Invalid dice roll expression")

        parts = match.groupdict()
        dice = int(parts["dice"] or self.default_dice)
        sides = int(parts["sides"] or self.default_sides)
        mods = parts["mods"] or ""

        if dice > self.max_dice:
            raise NotEnoughDice()
        if sides > self.max_sides:
            raise NotEnoughSides()

        # Roll
        result = [random.randint(1, sides) for x in xrange(dice)]
        return self.apply_mods(result, mods)

    def apply_mods(self, numbers, mods):
        pos = 0
        while True:
            match = self._MODS_REGEX.match(mods, pos=pos)
            if match is None:
                break
            if match.lastgroup == "sort":
                numbers.sort()
                pos += 1
#.........这里部分代码省略.........
开发者ID:EionRobb,项目名称:Ultros-contrib,代码行数:103,代码来源:__init__.py

示例6: ReplPlugin

# 需要导入模块: from system.storage.manager import StorageManager [as 别名]
# 或者: from system.storage.manager.StorageManager import get_file [as 别名]
class ReplPlugin(plugin.PluginObject):
    commands = None
    events = None
    storage = None

    config = None

    proto = None
    channel = None
    formatting = None

    def __init__(self):
        self.protocol_events = {
            "general": [
                # This is basically just *args.
                ["MessageReceived", self, self.message_received, 0]
            ],
            "inter": [
                ["Inter/PlayerConnected", self,
                    self.inter_player_connected, 0],
                ["Inter/PlayerDisconnected", self,
                    self.inter_player_disconnected, 0],
                ["Inter/ServerConnected", self,
                    self.inter_server_connected, 0],
                ["Inter/ServerDisconnected", self,
                    self.inter_server_disconnected, 0]
            ]
        }

        super(ReplPlugin, self).__init__()

    def setup(self):
        self.logger.trace("Entered setup method.")

        self.commands = CommandManager()
        self.events = EventManager()
        self.storage = StorageManager()

        try:
            self.config = self.storage.get_file(self, "config", YAML,
                                                "plugins/inter.yml")
        except Exception:
            self.logger.exception("Error loading configuration!")
            self.logger.error(_("Disabling.."))
            self._disable_self()
            return

        if not self.config.exists:
            self.logger.error("Unable to find config/plugins/inter.yml")
            self.logger.error(_("Disabling.."))
            self._disable_self()
            return

        self.config.add_callback(self.reload)

        self.commands.register_command("players", self.players_command, self,
                                       "inter.players", default=True)

        self.events.add_callback("ReactorStarted", self, self.first_load, 0)

    def first_load(self, event):
        if not self.reload():
            self.logger.error(_("Disabling.."))
            self._disable_self()

    def reload(self):
        self.events.remove_callbacks_for_plugin(self.info.name)
        proto = self.factory_manager.get_protocol(self.config["protocol"])

        if proto is None:
            self.logger.error(_("Unknown protocol: %s")
                              % self.config["protocol"])
            return False

        if proto.TYPE == "inter":
            self.logger.error(_("You cannot relay between two Inter "
                                "protocols!"))
            return False

        self.proto = proto
        self.channel = self.config["channel"]
        self.formatting = self.config["formatting"]

        for event in self.protocol_events["general"]:
            self.events.add_callback(*event)

        for event in self.protocol_events["inter"]:
            self.events.add_callback(*event)

        if proto.TYPE in self.protocol_events:
            for event in self.protocol_events[proto.TYPE]:
                self.events.add_callback(*event)

        return True

    def get_inters(self):
        inters = {}

        for key in self.factory_manager.factories.keys():
            if self.factory_manager.get_protocol(key).TYPE == "inter":
#.........这里部分代码省略.........
开发者ID:domainr,项目名称:Ultros-contrib,代码行数:103,代码来源:__init__.py

示例7: WolframPlugin

# 需要导入模块: from system.storage.manager import StorageManager [as 别名]
# 或者: from system.storage.manager.StorageManager import get_file [as 别名]
class WolframPlugin(plugin.PluginObject):

    app = None

    config = None
    commands = None
    storage = None

    def setup(self):
        self.logger.trace("Entered setup method.")
        self.storage = StorageManager()
        try:
            self.config = self.storage.get_file(self, "config", YAML,
                                                "plugins/wolfram.yml")
        except Exception:
            self.logger.exception("Error loading configuration!")
            self.logger.error("Disabling..")
            self._disable_self()
            return
        if not self.config.exists:
            self.logger.error("Unable to find config/plugins/wolfram.yml")
            self.logger.error("Disabling..")
            self._disable_self()
            return

        self.commands = CommandManager()

        self._load()
        self.config.add_callback(self._load)

        self.commands.register_command("wolfram", self.wolfram_command, self,
                                       "wolfram.wolfram", default=True)

    def _load(self):
        self.app = wolframalpha.Client(self.config["app_id"])

    @run_async_threadpool
    def wolfram_command(self, protocol, caller, source, command, raw_args,
                        parsed_args):
        target = caller
        if isinstance(source, Channel):
            target = source

        if len(raw_args):
            try:
                res = self.app.query(raw_args)
                first = next(res.results)
                text = first.text.replace("\n", " ")

                target.respond(text)
            except Exception as e:
                if len(str(e)):
                    raise e
                else:
                    target.respond("No answer was found for your query.")

        else:
            caller.respond("Usage: .wolfram <query>")

    def deactivate(self):
        pass
开发者ID:EionRobb,项目名称:Ultros-contrib,代码行数:63,代码来源:__init__.py

示例8: FeedsPlugin

# 需要导入模块: from system.storage.manager import StorageManager [as 别名]
# 或者: from system.storage.manager.StorageManager import get_file [as 别名]
class FeedsPlugin(plugin.PluginObject):

    config = None
    events = None
    manager = None
    plugman = None
    storage = None

    feeds = []

    failures = {}
    feed_times = {}
    targets = {}
    tasks = {}

    @property
    def urls(self):
        return self.plugman.get_plugin("URLs")

    def setup(self):
        self.logger.trace("Entered setup method.")
        self.storage = StorageManager()
        try:
            self.config = self.storage.get_file(self, "config", YAML,
                                                "plugins/feeds.yml")
        except Exception:
            self.logger.exception("Error loading configuration!")
            self.logger.error("Disabling..")
            self._disable_self()
            return
        if not self.config.exists:
            self.logger.error("Unable to find config/plugins/feeds.yml")
            self.logger.error("Disabling..")
            self._disable_self()
            return

        self.config.add_callback(self.delayed_setup)

        self.events = EventManager()
        self.plugman = PluginManager()

        self.logger.info("Waiting 30 seconds to set up.")

        reactor.callLater(30, self.delayed_setup)

    def delayed_setup(self):
        self.feeds = []

        self.failures.clear()
        self.feed_times.clear()
        self.targets.clear()
        self.tasks.clear()

        for name, target in self.config["targets"].items():
            proto = target["protocol"]
            if proto in self.factory_manager.factories:
                self.targets[name] = target
            else:
                self.logger.warn("Unknown protocol '%s' in target '%s'"
                                 % (proto, name))

        for feed in self.config["feeds"]:
            append = True
            for target in feed["targets"]:
                if target["name"] not in self.targets:
                    self.logger.warn("Unknown target '%s' for feed '%s'"
                                     % (target["name"], feed["name"]))
                    append = False
                    break

            if append:
                self.feeds.append(feed)

        for feed in self.feeds:
            task = LoopingCall(self.check_feed, feed)
            self.tasks[feed["name"]] = task
            task.start(feed["frequency"])

    @run_async_threadpool
    def check_feed(self, feed):
        name = "<Unable to get feed name>"
        self.logger.trace("Feed: %s" % feed)
        try:  # Have to catch all exceptions, or the task will cancel.
            name = feed["name"]

            if name not in self.failures:
                self.failures[name] = 0

            if self.failures[name] > 5:
                self.logger.warn("Disabling update task for feed '%s' as "
                                 "there has been too many errors." % name)

                if name in self.tasks:
                    self.tasks[name].stop()

                return

            d = feedparser.parse(feed["url"])

            if name in self.feed_times:
#.........这里部分代码省略.........
开发者ID:EionRobb,项目名称:Ultros-contrib,代码行数:103,代码来源:__init__.py

示例9: xkcdPlugin

# 需要导入模块: from system.storage.manager import StorageManager [as 别名]
# 或者: from system.storage.manager.StorageManager import get_file [as 别名]
class xkcdPlugin(plugin.PluginObject):

    _commands = None
    _config = None
    _storage = None

    _comic_cache = None
    _archive = None

    def setup(self):
        ### Grab important shit
        self._commands = CommandManager()
        self._storage = StorageManager()

        ### Initial config load
        try:
            self._config = self._storage.get_file(self, "config", YAML,
                                                  "plugins/xkcd.yml")
        except:
            self.logger.exception("Error loading configuration!")
            self.logger.error("Disabling...")
            self._disable_self()
            return
        if not self._config.exists:
            self.logger.error("Unable to find config/plugins/xkcd.yml")
            self.logger.error("Disabling...")
            self._disable_self()
            return
        ### Same for the data files
        try:
            self._comic_cache = self._storage.get_file(
                self, "data", YAML,
                "plugins/xkcd/comic-cache.yml")
        except:
            self.logger.exception("Error loading comic-cache!")
            self.logger.error("Disabling...")
            self._disable_self()
        try:
            self._archive = self._storage.get_file(self, "data", YAML,
                                                   "plugins/xkcd/archive.yml")
        except:
            self.logger.exception("Error loading archive!")
            self.logger.error("Disabling...")
            self._disable_self()

        ### Initial data file setup and stuff
        self._load()

        self._config.add_callback(self._load)
        self._comic_cache.add_callback(self._load)
        self._archive.add_callback(self._load)

        ### Register commands
        self._commands.register_command("xkcd",
                                        self.xkcd_cmd,
                                        self,
                                        "xkcd.xkcd", default=True)

    def reload(self):
        # Reload config
        try:
            self._config.reload()
        except:
            self.logger.exception("Error reloading config file!")
            return False
        # Reload data
        try:
            self._comic_cache.reload()
            self._archive.reload()
        except:
            self.logger.exception("Error reloading data files!")
            return False
        # Everything went fine
        return True

    def _load(self):
        altered = False
        if "last-update" not in self._archive:
            self._archive["last-update"] = 0
            altered = True
        if "latest" not in self._archive:
            self._archive["latest"] = 0
            altered = True
        if "by-id" not in self._archive:
            self._archive["by-id"] = {}
            altered = True
        if altered:
            self._archive.save()

    def _archive_time(self):
        return self._config["archive-time"]

    def _respond(self, target, msg):
        """
        Convenience function for responding to something with a prefix. Not
        only does this avoid confusion, but it also stops people being able to
        execute other bot commands in the case that we need to put any
        user-supplied data at the start of a message.
        """
        target.respond("[xkcd] " + msg)
#.........这里部分代码省略.........
开发者ID:EionRobb,项目名称:Ultros-contrib,代码行数:103,代码来源:__init__.py

示例10: TwilioPlugin

# 需要导入模块: from system.storage.manager import StorageManager [as 别名]
# 或者: from system.storage.manager.StorageManager import get_file [as 别名]
class TwilioPlugin(plugin.PluginObject):

    config = None
    data = None

    commands = None
    events = None
    plugins = None
    storage = None

    twilio = None

    @property
    def web(self):
        """
        :rtype: WebPlugin
        """
        return self.plugins.get_plugin("Web")

    def setup(self):
        self.logger.trace("Entered setup method.")

        self.commands = CommandManager()
        self.events = EventManager()
        self.plugins = PluginManager()
        self.storage = StorageManager()

        try:
            self.config = self.storage.get_file(self, "config", YAML,
                                                "plugins/twilio.yml")
        except Exception:
            self.logger.exception("Error loading configuration!")
            return self._disable_self()
        else:
            if not self.config.exists:
                self.logger.error("Unable to find config/plugins/twilio.yml")
                return self._disable_self()

        try:
            self.data = self.storage.get_file(self, "data", JSON,
                                              "plugins/twilio/contacts.json")
        except Exception:
            self.logger.exception("Error loading data!")
            self.logger.error("This data file is required. Shutting down...")
            return self._disable_self()

        self._load()
        self.config.add_callback(self._load)

        self.events.add_callback("Web/ServerStartedEvent", self,
                                 self.add_routes,
                                 0)

        self.commands.register_command("sms", self.sms_command, self,
                                       "twilio.sms")
        self.commands.register_command("mms", self.mms_command, self,
                                       "twilio.mms")
        self.commands.register_command("tw", self.tw_command, self,
                                       "twilio.tw")

    def _load(self):
        self.twilio = TwilioRestClient(
            self.config["identification"]["sid"],
            self.config["identification"]["token"]
        )

        account = self.twilio.accounts.get(
            self.config["identification"]["sid"]
        )

        self.logger.info("Logged in as [%s] %s." % (account.type,
                                                    account.friendly_name))

    def add_routes(self, event):
        self.web.add_handler(
            r"/twilio/%s" % self.config["security"]["api_key"],
            "plugins.twilio.route.Route"
        )
        self.logger.info("Registered route: /twilio/<apikey>")

    def tw_command(self, protocol, caller, source, command, raw_args,
                   parsed_args):

        args = raw_args.split(" ")
        if len(args) < 1:
            caller.respond("Usage: {CHARS}tw <contact/reload> [<set/del/get> "
                           "<[name] [number]>]")
            return

        action = args[0].lower()

        if action == "reload":
            self.config.reload()
            self.data.reload()

            source.respond("Files reloaded.")
            return

        if action != "contact":
            caller.respond("Unknown action: %s" % action)
#.........这里部分代码省略.........
开发者ID:EionRobb,项目名称:Ultros-contrib,代码行数:103,代码来源:__init__.py

示例11: LastseenPlugin

# 需要导入模块: from system.storage.manager import StorageManager [as 别名]
# 或者: from system.storage.manager.StorageManager import get_file [as 别名]
class LastseenPlugin(plugin.PluginObject):

    commands = None
    events = None
    storage = None

    data = None  # SQLite for a change

    def setup(self):
        self.commands = CommandManager()
        self.events = EventManager()
        self.storage = StorageManager()
        self.data = self.storage.get_file(
            self,
            "data",
            DBAPI,
            "sqlite3:data/plugins/lastseen/users.sqlite",
            "data/plugins/lastseen/users.sqlite",
            check_same_thread=False
        )

        self.data.runQuery("CREATE TABLE IF NOT EXISTS users ("
                           "user TEXT, "
                           "protocol TEXT, "
                           "at INTEGER)")

        self.commands.register_command("seen", self.seen_command, self,
                                       "seen.seen", default=True)

        # General events

        self.events.add_callback("PreMessageReceived", self,
                                 self.event_handler, 0, cancelled=True,
                                 extra_args=[self.event_source_caller])
        self.events.add_callback("PreCommand", self,
                                 self.event_handler, 0, cancelled=True,
                                 extra_args=[self.event_source_caller])
        self.events.add_callback("NameChanged", self,
                                 self.event_handler, 0, cancelled=True,
                                 extra_args=[self.event_user_caller])
        self.events.add_callback("UserDisconnected", self,
                                 self.event_handler, 0, cancelled=True,
                                 extra_args=[self.event_user_caller])

        # Mumble events

        self.events.add_callback("Mumble/UserRemove", self,
                                 self.event_handler, 0, cancelled=True,
                                 extra_args=[self.event_user_caller])
        self.events.add_callback("Mumble/UserJoined", self,
                                 self.event_handler, 0, cancelled=True,
                                 extra_args=[self.event_user_caller])
        self.events.add_callback("Mumble/UserMoved", self,
                                 self.event_handler, 0, cancelled=True,
                                 extra_args=[self.event_user_caller])
        self.events.add_callback("Mumble/UserSelfMuteToggle", self,
                                 self.event_handler, 0, cancelled=True,
                                 extra_args=[self.event_user_caller])
        self.events.add_callback("Mumble/UserSelfDeafToggle", self,
                                 self.event_handler, 0, cancelled=True,
                                 extra_args=[self.event_user_caller])
        self.events.add_callback("Mumble/UserRecordingToggle", self,
                                 self.event_handler, 0, cancelled=True,
                                 extra_args=[self.event_user_caller])

    def _get_user_txn(self, txn, user, protocol):
        user = user.lower()
        txn.execute("SELECT * FROM users WHERE user=? AND protocol=?",
                    (user, protocol))
        r = txn.fetchone()
        return r

    def _get_user_callback(self, result, user, protocol, source):
        if result is None:
            source.respond("User '%s' not found." % user)
        else:
            then = math.floor(result[2])
            now = math.floor(time.time())
            seconds = now - then

            m, s = divmod(seconds, 60)
            h, m = divmod(m, 60)
            d, h = divmod(h, 24)

            s = int(s)
            m = int(m)
            h = int(h)
            d = int(d)

            if (s + m + h + d) == 0:
                source.respond("'%s' was seen just now!" % user)
            else:
                constructed = "'%s' was seen" % user
                to_append = []
                if d > 0:
                    to_append.append("%s days" % d)
                if h > 0:
                    to_append.append("%s hours" % h)
                if m > 0:
                    to_append.append("%s minutes" % m)
#.........这里部分代码省略.........
开发者ID:domainr,项目名称:Ultros-contrib,代码行数:103,代码来源:__init__.py

示例12: JargonPlugin

# 需要导入模块: from system.storage.manager import StorageManager [as 别名]
# 或者: from system.storage.manager.StorageManager import get_file [as 别名]
class JargonPlugin(plugin.PluginObject):

    commands = None
    storage = None

    def setup(self):
        ### Grab important shit
        self.commands = CommandManager()
        self.storage = StorageManager()

        ### Initial config load
        try:
            self._config = self.storage.get_file(self,
                                                 "config",
                                                 YAML,
                                                 "plugins/jargon.yml")
        except Exception:
            self.logger.exception("Error loading configuration!")
            self.logger.error("Disabling...")
            self._disable_self()
            return
        if not self._config.exists:
            self.logger.error("Unable to find config/plugins/jargon.yml")
            self.logger.error("Disabling...")
            self._disable_self()
            return

        ### Register commands
        self.commands.register_command("jargon",
                                       self.jargon_cmd,
                                       self,
                                       "jargon.jargon", default=True)

    def reload(self):
        try:
            self._config.reload()
        except Exception:
            self.logger.exception("Error reloading configuration!")
            return False
        return True

    def jargon_cmd(self, protocol, caller, source, command, raw_args,
                   parsed_args):
        source.respond(self.generate_sentence())

    def get_word(self, word_type):
        word_type = word_type.lower()
        if word_type == "verb":
            return random.choice(self._config["verbs"])["plain"]
        elif word_type == "verbing":
            verb = random.choice(self._config["verbs"])
            if "ing" in verb:
                return verb["ing"]
            else:
                return verb["plain"] + "ing"
        elif word_type == "noun":
            return random.choice(self._config["nouns"])
        elif word_type == "adjective":
            return random.choice(self._config["adjectives"])
        elif word_type == "abbreviation":
            return random.choice(self._config["abbreviations"])

    def generate_sentence(self):
        sentenceFormat = random.choice(self._config["formats"])
        words = []
        for word in sentenceFormat["types"]:
            words.append(self.get_word(word))
        return sentenceFormat["format"] % tuple(words)
开发者ID:case,项目名称:Ultros-contrib,代码行数:70,代码来源:__init__.py

示例13: FactoidsPlugin

# 需要导入模块: from system.storage.manager import StorageManager [as 别名]
# 或者: from system.storage.manager.StorageManager import get_file [as 别名]
class FactoidsPlugin(plugin.PluginObject):

    CHANNEL = "channel"
    PROTOCOL = "protocol"
    GLOBAL = "global"

    PERM_ADD = "factoids.add.%s"
    PERM_SET = "factoids.set.%s"
    PERM_DEL = "factoids.delete.%s"
    PERM_GET = "factoids.get.%s"

    (RES_INVALID_LOCATION,
     RES_INVALID_METHOD,  # _FOR_LOCATION - i.e. CHANNEL in PM
     RES_NO_PERMS,
     RES_MISSING_FACTOID) = xrange(4)

    def setup(self):
        # ## Grab important shit
        self.commands = CommandManager()
        self.events = EventManager()
        self.storage = StorageManager()
        self.plugman = PluginManager()

        # ## Set up database
        self.database = self.storage.get_file(
            self,
            "data",
            DBAPI,
            "sqlite3:data/plugins/factoids.sqlite",
            "data/plugins/factoids.sqlite",
            check_same_thread=False
        )

        self.database.add_callback(self.reload)
        self.reload()

        # ## Register commands
        # We have multiple possible permissions per command, so we have to do
        # permission handling ourselves
        self.commands.register_command("addfactoid",
                                       self.factoid_add_command,
                                       self,
                                       None)
        self.commands.register_command("setfactoid",
                                       self.factoid_set_command,
                                       self,
                                       None)
        self.commands.register_command("deletefactoid",
                                       self.factoid_delete_command,
                                       self,
                                       None,
                                       ["delfactoid"])
        self.commands.register_command("getfactoid",
                                       self.factoid_get_command,
                                       self,
                                       None, default=True)

        # ## Register events
        self.events.add_callback("MessageReceived",
                                 self,
                                 self.message_handler,
                                 1)

        self.events.add_callback("Web/ServerStartedEvent",
                                 self,
                                 self.web_routes,
                                 1)

    def reload(self):
        with self.database as db:
            db.runQuery("CREATE TABLE IF NOT EXISTS factoids ("
                        "factoid_key TEXT, "
                        "location TEXT, "
                        "protocol TEXT, "
                        "channel TEXT, "
                        "factoid_name TEXT, "
                        "info TEXT, "
                        "UNIQUE(factoid_key, location, protocol, channel) "
                        "ON CONFLICT REPLACE)")

    # region Util functions

    def __check_perm(self, perm, caller, source, protocol):
        self.logger.trace(_("Checking for permission: '%s'"), perm)
        allowed = self.commands.perm_handler.check(perm,
                                                   caller,
                                                   source,
                                                   protocol)
        return allowed

    def _parse_args(self, raw_args):
        """
        Grabs the location, factoid name, and info from a raw_args string
        """
        pos = raw_args.find(" ")
        if pos < 0:
            raise ValueError(_("Invalid args"))
        location = raw_args[:pos]
        pos2 = raw_args.find(" ", pos + 1)
        if pos2 < 0:
#.........这里部分代码省略.........
开发者ID:NotAFile,项目名称:Ultros,代码行数:103,代码来源:__init__.py

示例14: URLToolsPlugin

# 需要导入模块: from system.storage.manager import StorageManager [as 别名]
# 或者: from system.storage.manager.StorageManager import get_file [as 别名]

#.........这里部分代码省略.........
    GITHUB_RELEASE = u"[GitHub release] %s/%s/%s by %s - %s assets, %s " \
                     u"downloads"
    GITHUB_RELEASE_NONE = u"[GitHub repo] %s/%s - No releases found"

    GITHUB_ISSUES = u"[GitHub repo / %s issues] %s/%s - %s open, %s closed"
    GITHUB_ISSUE = u"[GitHub issue] %s/%s/%s by %s (%s) - %s (%s)"
    GITHUB_ISSUE_MILESTONE = u"[GitHub issue] %s/%s/%s %s by %s (%s) - %s (%s)"
    GITHUB_ISSUE_ASSIGNED = u"[GitHub issue] %s/%s/%s by %s (%s) - %s (%s) " \
                            u"- Assigned to %s"
    GITHUB_ISSUE_ASSIGNED_MILESTONE = u"[GitHub issue] %s/%s/%s %s by %s " \
                                      u"(%s) - %s (%s) - Assigned to %s"

    # GITHUB_COMMITS = u"[GitHub repo / last %s commits] %s/%s - +%s/-%s/±%s" \
    #                  u" (%s individual file edits) by %s authors."
    GITHUB_COMMITS = u"[GitHub repo / last %s commits] %s/%s - %s commits by" \
                     u" %s authors."
    GITHUB_COMMITS_COMMIT = u"[GitHub commit] %s/%s +%s/-%s/±%s (%s files) " \
                            u"by %s - %s"
    GITHUB_COMMITS_COMPARE = u"[GitHub commit comparison] %s/%s - Comparing " \
                             u"%s by %s and %s by %s with %s intermediary " \
                             u"commits"

    GITHUB_PULLS = u"[GitHub repo / %s pull requests] %s/%s - %s open, %s " \
                   u"closed"
    GITHUB_PULLS_PULL = u"[GitHub pull request] %s/%s/%s by %s (%s) - %s"

    @property
    def urls(self):
        return self.plugman.get_plugin("URLs")

    def setup(self):
        self.storage = StorageManager()
        try:
            self.config = self.storage.get_file(self, "config", YAML,
                                                "plugins/urltools.yml")
        except Exception:
            self.logger.exception("Unable to load the configuration!")
            self._disable_self()
            return

        self.sites["osu.ppy.sh"] = self.site_osu
        self.sites["youtube.com"] = self.site_youtube
        self.sites["github.com"] = self.site_github

        self.shorteners["is.gd"] = self.shortener_isgd
        self.shorteners["nazr.in"] = self.shortener_nazrin
        self.shorteners["v.gd"] = self.shortener_vgd
        self.shorteners["waa.ai"] = self.shortener_waaai

        self.plugman = PluginManager()

        self._load()
        self.config.add_callback(self._load)

    def _load(self):
        shorteners = self.config["shorteners"]
        sites = self.config["sites"]

        sites_enabled = []
        shorteners_enabled = []

        for site in sites["enabled"]:
            if site.lower() == "osu.ppy.sh":
                if not sites["apikeys"]["osu"]:
                    self.logger.warn("Osu! support enabled, but no API key was"
                                     " configured. You'll need to add one if "
开发者ID:domainr,项目名称:Ultros-contrib,代码行数:70,代码来源:__init__.py

示例15: DictPlugin

# 需要导入模块: from system.storage.manager import StorageManager [as 别名]
# 或者: from system.storage.manager.StorageManager import get_file [as 别名]
class DictPlugin(plugin.PluginObject):

    api_key = ""
    api_client = None
    word_api = None
    words_api = None

    commands = None
    config = None
    plugman = None
    storage = None

    @property
    def urls(self):
        return self.plugman.get_plugin("URLs")

    def setup(self):
        self.storage = StorageManager()
        try:
            self.config = self.storage.get_file(self, "config", YAML,
                                                "plugins/wordnik.yml")
        except Exception:
            self.logger.exception("Unable to load the configuration!")
            return self._disable_self()
        if not self.config.exists:
            self.logger.error("Unable to find the configuration at "
                              "config/plugins/wordnik.yml - Did you fill "
                              "it out?")
            return self._disable_self()
        if "apikey" not in self.config or not self.config["apikey"]:
            self.logger.error("Unable to find an API key; did you fill out the"
                              " config?")
            return self._disable_self()

        self._load()
        self.config.add_callback(self._load)

        self.plugman = PluginManager()

        self.commands = CommandManager()

        self.commands.register_command("dict", self.dict_command,
                                       self, "wordnik.dict", default=True)
        self.commands.register_command("wotd", self.wotd_command,
                                       self, "wordnik.wotd", default=True)

    def _load(self):
        self.api_key = self.config["apikey"]
        self.api_client = swagger.ApiClient(self.api_key,
                                            "http://api.wordnik.com/v4")
        self.word_api = WordApi(self.api_client)
        self.words_api = WordsApi(self.api_client)

    def dict_command(self, protocol, caller, source, command, raw_args,
                     parsed_args):
        args = raw_args.split()  # Quick fix for new command handler signature
        if len(args) < 1:
            caller.respond("Usage: {CHAR}dict <word to look up>")
        else:
            try:
                definition = self.get_definition(args[0])
                if not definition:
                    if isinstance(source, User):
                        caller.respond("%s | No definition found." % args[0])
                    else:
                        source.respond("%s | No definition found." % args[0])
                    return
                word = definition.word
                text = definition.text

                wiktionary_url = "http://en.wiktionary.org/wiki/%s" \
                                 % urllib.quote_plus(word)

                short_url = self.urls.tinyurl(wiktionary_url)
            except Exception as e:
                self.logger.exception("Error looking up word: %s" % args[0])
                caller.respond("Error getting definition: %s" % e)
            else:

                # Necessary attribution as per the Wordnik TOS
                if isinstance(source, User):
                    caller.respond("%s | %s (%s) - Provided by Wiktionary via "
                                   "the Wordnik API" % (word, text, short_url))
                else:
                    source.respond("%s | %s (%s) - Provided by Wiktionary via "
                                   "the Wordnik API" % (word, text, short_url))

    def wotd_command(self, protocol, caller, source, command, raw_args,
                     parsed_args):
        args = raw_args.split()  # Quick fix for new command handler signature
        try:
            wotd = self.get_wotd()
            definition = self.get_definition(wotd)
            if not definition:
                if isinstance(source, User):
                    caller.respond("%s | No definition found." % wotd)
                else:
                    source.respond("%s | No definition found." % wotd)
                return
            word = definition.word
#.........这里部分代码省略.........
开发者ID:case,项目名称:Ultros-contrib,代码行数:103,代码来源:__init__.py


注:本文中的system.storage.manager.StorageManager.get_file方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。