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


Python CommandManager.register_command方法代码示例

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


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

示例1: UrbanDictionaryPlugin

# 需要导入模块: from system.command_manager import CommandManager [as 别名]
# 或者: from system.command_manager.CommandManager import register_command [as 别名]
class UrbanDictionaryPlugin(plugin.PluginObject):

    commands = None
    config = None

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

        ### Register commands
        self.commands.register_command("urbandictionary",
                                       self.urbandictionary_cmd,
                                       self,
                                       "urbandictionary.definition",
                                       aliases=["ud"], default=True)

    def urbandictionary_cmd(self, protocol, caller, source, command, raw_args,
                            parsed_args):
        args = raw_args.split()  # Quick fix for new command handler signature
        ### Get LastFM username to use
        username = None
        if len(args) == 0:
            caller.respond("Usage: {CHARS}urbandictionary <term>")
            return

        term = " ".join(args)

        try:
            definition, permalink = self.get_definition(term)
            if definition is None:
                source.respond('[UD] "%s" is not defined yet' % term)
            else:
                # TODO: Limit definition length
                source.respond('[UD] "%s" - %s - (%s)' %
                               (term,
                                to_bytes(definition)
                                .replace('\r', '')
                                .replace('\n', ' '),
                                to_bytes(permalink)))
        except:
            self.logger.exception("Cannot get definition for '%s'" % term)
            source.respond("There was an error while fetching the definition -"
                           " please try again later, or alert a bot admin.")

    def get_definition(self, term):
        request = urllib2.Request("http://api.urbandictionary.com/v0/define?" +
                                  urllib.urlencode({'term': term}))
        # Fuck you PEP8. Fuck you with the largest, spikiest dragon dildo, in
        # every orifice you have, and more.
        request.add_header('User-agent', 'Mozilla/5.0 '
                                         '(X11; U; Linux i686; '
                                         'en-US; rv:1.9.0.1) '
                                         'Gecko/2008071615 '
                                         'Fedora/3.0.1-1.fc9-1.fc9 '
                                         'Firefox/3.0.1')
        try:
            definition = json.load(urllib2.urlopen(request))["list"][0]
            return definition["definition"], definition["permalink"]
        except IndexError:
            return None, None
开发者ID:EionRobb,项目名称:Ultros-contrib,代码行数:62,代码来源:__init__.py

示例2: RoulettePlugin

# 需要导入模块: from system.command_manager import CommandManager [as 别名]
# 或者: from system.command_manager.CommandManager import register_command [as 别名]
class RoulettePlugin(plugin.PluginObject):

    commands = None

    channels = {}
    users = {}

    def setup(self):
        self.commands = CommandManager()
        self.commands.register_command("rroulette", self.play, self,
                                       "russianroulette.rroulette",
                                       aliases=["roulette"], default=True)

    def addChannel(self, channel):
        if channel not in self.channels.keys():
            players = []
            curplayers = []
            shots = 0
            deaths = 0
            chambers = 6

            data = {"players": players, "shots": shots, "deaths": deaths,
                    "chambers": chambers, "curplayers": curplayers}

            self.channels[channel] = data

    def play(self, protocol, caller, source, command, raw_args,
             parsed_args):
        args = raw_args.split()  # Quick fix for new command handler signature
        self.logger.trace("Caller: %s" % repr(caller))
        self.logger.trace("Source: %s" % repr(source))
        self.logger.trace("Result: %s" % isinstance(source, Channel))
        if not isinstance(source, Channel):
            caller.respond("This command may only be used in a channel.")
            return

        self.addChannel(source.name)

        chambers_left = self.channels[source.name]["chambers"]

        random.seed()

        if random.randint(1, chambers_left) == 1:
            # Boom!
            source.respond("BANG")
            protocol.send_action(source, "*reloads the gun*")
            chambers_left = 6
            source.respond(
                'There are %s new chambers. You have a %s%% chance of dying.'
                % (chambers_left, int(100.0 / chambers_left)))

        else:
            # Click..
            chambers_left -= 1
            source.respond(
                '*click* You\'re safe for now. There are %s chambers left. '
                'You have a %s%% chance of dying.'
                % (chambers_left, int(100.0 / chambers_left)))
        self.channels[source.name]["chambers"] = chambers_left
开发者ID:domainr,项目名称:Ultros-contrib,代码行数:61,代码来源:__init__.py

示例3: ItemsPlugin

# 需要导入模块: from system.command_manager import CommandManager [as 别名]
# 或者: from system.command_manager.CommandManager import register_command [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

示例4: MemosPlugin

# 需要导入模块: from system.command_manager import CommandManager [as 别名]
# 或者: from system.command_manager.CommandManager import register_command [as 别名]
class MemosPlugin(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", SQLITE,
        #                                   "plugins/memos/memos.sqlite")

        # with self.data as c:
        #     # Multiline strings because of an IDE bug
        #     c.execute("""CREATE TABLE IF NOT EXISTS memos
        #               (to TEXT, from TEXT, memo TEXT)""")

        self.events.add_callback("PreMessageReceived", self,
                                 self.message_received, 0)
        self.commands.register_command("memo", self.memo_command, self,
                                       "memo.send", default=True)

    def save_memo(self, sender, recipient, memo):
        recipient = recipient.lower()
        # with self.data as c:
        #     c.execute("""INSERT INTO memos VALUES (?, ?, ?)""",
        #               (recipient, sender, memo))

    def get_memos(self, recipient):
        recipient = recipient.lower()
        # with self.data as c:
        #     c.execute("""SELECT * FROM memos WHERE from=?""", (recipient,))
        #     d = c.fetchall()
        #     return d

    def message_received(self, event=PreMessageReceived):
        user = event.source
        target = event.target if isinstance(event.target, Channel) else user
        memos = self.get_memos(user.name)
        if memos:
            for memo in memos:
                sender = memo[1]
                text = memo[2]
                target.respond("Memo for %s (from %s): %s" % (user.name,
                                                              sender, text))

    def memo_command(self, protocol, caller, source, command, raw_args,
                     parsed_args):
        args = raw_args.split()  # Quick fix for new command handler signature
        raise NotImplementedError("This isn't done yet.")
开发者ID:case,项目名称:Ultros-contrib,代码行数:55,代码来源:__init__.py

示例5: ExamplePlugin

# 需要导入模块: from system.command_manager import CommandManager [as 别名]
# 或者: from system.command_manager.CommandManager import register_command [as 别名]
class ExamplePlugin(plugin.PluginObject):  # Create the plugin class
    """
    Example plugin object
    """

    commands = None

    def setup(self):
        """
        Called when the plugin is loaded. Performs initial setup.
        """

        # Get an instance of the command manager
        self.commands = CommandManager()

        # Register the command in our system
        self.commands.register_command(
            "example",  # The name of the command
            self.example_command,  # The command's function
            self,  # This plugin
            # permission="example.example",  # Required permission for command
            default=True  # Whether this command should be available to all
        )

        self.commands.register_command(  # Another example command
            "example2", self.example_command, self, default=True
        )

    def example_command(self, protocol, caller, source, command, raw_args,
                        args):
        """
        Command handler for the example command
        """

        if args is None:
            # You'll probably always want this, so you always have
            # arguments if quote-parsing fails
            args = raw_args.split()

        # Send to the channel
        source.respond("Hello, world! You ran the %s command!" % command)

        # Send to the user that ran the command
        caller.respond("Raw arguments: %s" % raw_args)
        caller.respond("Parsed arguments: %s" % args)

        # Send directly through the protocol
        protocol.send_msg(source.name, "Message through the protocol!")
开发者ID:NotAFile,项目名称:Ultros,代码行数:50,代码来源:__init__.py

示例6: HeartbleedPlugin

# 需要导入模块: from system.command_manager import CommandManager [as 别名]
# 或者: from system.command_manager.CommandManager import register_command [as 别名]
class HeartbleedPlugin(plugin.PluginObject):
    commands = None

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

        self.commands.register_command("hb",
                                       self.hb_command,
                                       self,
                                       "hb.hb", default=True)

    @run_async_threadpool
    def hb_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: {CHARS}hb <address> [port]")
            return
        else:
            host = args[0]
            port = 443

            if len(args) > 1:
                port = args[1]
                try:
                    port = int(port)
                except:
                    source.respond("Port '%s' is invalid, trying on port "
                                   "443." % port)
            try:
                source.respond("Checking %s:%s" % (host, port))
                result = hb.try_host(host, port)
                if result:
                    source.respond("Host %s is vulnerable!" % host)
                elif result is None:
                    source.respond("Host %s returned an error. It's probably "
                                   "not vulnerable." % host)
                else:
                    source.respond("Host %s is not vulnerable." % host)
            except:
                self.logger.exception("Error querying host %s" % host)
                source.respond("Unable to determine whether host %s is "
                               "vulnerable." % host)
开发者ID:EionRobb,项目名称:Ultros-contrib,代码行数:45,代码来源:__init__.py

示例7: TranslatePlugin

# 需要导入模块: from system.command_manager import CommandManager [as 别名]
# 或者: from system.command_manager.CommandManager import register_command [as 别名]
class TranslatePlugin(PluginObject):
    commands = None
    goslate = None

    def setup(self):
        self.commands = CommandManager()
        self.goslate = Goslate()

        self.commands.register_command(
            "translate", self.translate_command, self, "translate.translate",
            ["tr", "t"], True
        )

    @run_async_threadpool
    def translate_command(self, protocol, caller, source, command, raw_args,
                          parsed_args):
        if len(parsed_args) < 2:
            caller.respond(
                "Usage: {CHARS}" + command + " <languages> <text>"
            )
            return

        langs = parsed_args[0]
        text = u" ".join([to_unicode(x) for x in parsed_args[1:]])

        if u":" in langs:
            split = langs.split(u":")
            from_lang, to_lang = split[0], split[1]
        else:
            from_lang, to_lang = u"", langs

        try:
            translation = self.goslate.translate(text, to_lang, from_lang)

            source.respond(u"[{}] {}".format(to_lang, translation))
        except Error as e:
            source.respond(u"Translation error: {}".format(e))
        except Exception as e:
            self.logger.exception("Translation error")
            source.respond(u"Translation error: {}".format(e))
开发者ID:EionRobb,项目名称:Ultros-contrib,代码行数:42,代码来源:__init__.py

示例8: GeoIPPlugin

# 需要导入模块: from system.command_manager import CommandManager [as 别名]
# 或者: from system.command_manager.CommandManager import register_command [as 别名]
class GeoIPPlugin(plugin.PluginObject):

    commands = None
    api_url = "http://freegeoip.net/json/%s"

    def setup(self):
        self.commands = CommandManager()
        self.commands.register_command("geoip", self.command, self,
                                       "geoip.command", default=True)

    def 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: {CHARS}geoip <address>")
        else:
            addr = urllib.quote_plus(args[0])
            resp = urllib.urlopen(self.api_url % addr)
            data = resp.read()

            self.logger.trace("Data: %s" % repr(data))

            if data == "Not Found\n":
                source.respond("%s | Not found" % args[0])
            else:
                parsed = json.loads(data)
                country = parsed["country_name"]
                region = parsed["region_name"]
                city = parsed["city"]

                if not country and not city and not region:
                    source.respond("%s | Not found" % args[0])

                source.respond("%s | %s, %s, %s" % (args[0],
                                                    city or "???",
                                                    region or "???",
                                                    country or "???"))
开发者ID:case,项目名称:Ultros-contrib,代码行数:39,代码来源:__init__.py

示例9: DicePlugin

# 需要导入模块: from system.command_manager import CommandManager [as 别名]
# 或者: from system.command_manager.CommandManager import register_command [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

示例10: AoSPlugin

# 需要导入模块: from system.command_manager import CommandManager [as 别名]
# 或者: from system.command_manager.CommandManager import register_command [as 别名]
class AoSPlugin(plugin.PluginObject):

    commands = None
    storage = None

    _STEAM_PLAYERS_REGEX = re.compile(
        r'apphub_NumInApp">(?P<players>.+) In-Game'
    )
    _IP_REGEX = re.compile(
        r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9]'
        r'[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'
    )

    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/aoshelper.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/aoshelper.yml")
            self.logger.error("Disabling...")
            self._disable_self()
            return

        ### Load options from config
        self._load()

        self._config.add_callback(self._load)

        ### Register commands
        self.commands.register_command("aosplayercount",
                                       self.playercount_cmd,
                                       self,
                                       "aoshelper.playercount",
                                       [
                                           "playercount"
                                       ], default=True)
        self.commands.register_command("aostoip",
                                       self.aos_to_ip_command,
                                       self,
                                       "aoshelper.aostoip",
                                       [
                                           "aos2ip"
                                       ])
        self.commands.register_command("iptoaos",
                                       self.ip_to_aos_command,
                                       self,
                                       "aoshelper.iptoaos",
                                       [
                                           "ip2aos"
                                       ])

        ### Setup soem variables
        self._last_update_voxlap = 0
        self._last_update_steam = 0
        self._last_voxlap_player_count = -1
        self._last_steam_player_count = -1

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

    def _load(self):
        self.cache_time = self._config["cache-time"]
        self.max_misses = self._config["max-misses"]

    def playercount_cmd(self, protocol, caller, source, command, raw_args,
                        parsed_args):
        voxlap_players = self.get_voxlap_player_count()
        steam_players = self.get_steam_player_count()
        percentage_players = "-1%"
        if voxlap_players is not None and steam_players is not None:
            percentage_players = str(
                round(
                    voxlap_players / float(
                        steam_players.translate(None, " ,")
                    ) * 100, 1
                )
            ) + '%'
        source.respond(
            "There are currently %s people playing 0.x, and %s people playing "
            "1.0. 0.x player count is %s the size of 1.0's. Graph at "
            "http://goo.gl/M5h3q" % (
                voxlap_players,
                steam_players,
#.........这里部分代码省略.........
开发者ID:EionRobb,项目名称:Ultros-contrib,代码行数:103,代码来源:__init__.py

示例11: xkcdPlugin

# 需要导入模块: from system.command_manager import CommandManager [as 别名]
# 或者: from system.command_manager.CommandManager import register_command [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

示例12: ControlPlugin

# 需要导入模块: from system.command_manager import CommandManager [as 别名]
# 或者: from system.command_manager.CommandManager import register_command [as 别名]
class ControlPlugin(plugin.PluginObject):
    """
    Control plugin object
    """

    commands = None

    def setup(self):
        """
        The list of bridging rules
        """

        self.commands = CommandManager()

        self.commands.register_command("join", self.join_command,
                                       self, "control.join")
        self.commands.register_command("leave", self.leave_command,
                                       self, "control.leave")
        self.commands.register_command("say", self.say_command,
                                       self, "control.say")
        self.commands.register_command("action", self.action_command,
                                       self, "control.action")
        self.commands.register_command("raw", self.raw_command,
                                       self, "control.raw")
        self.commands.register_command("func", self.func_command,
                                       self, "control.func")

    def join_command(self, protocol, caller, source, command, raw_args,
                     args):
        """
        Command handler for the join command
        """

        if not len(args) > 0:
            caller.respond(__("Usage: {CHARS}join <channel>"))
            return

        if hasattr(protocol, "join_channel"):
            result = protocol.join_channel(args[0])

            if result:
                caller.respond(__("Done!"))
            else:
                caller.respond(__("Unable to join channel. Does this "
                                  "protocol support joining channels?"))
        else:
            caller.respond(__("This protocol doesn't support channels."))

    def leave_command(self, protocol, caller, source, command, raw_args,
                      args):
        """
        Command handler for the leave command
        """

        if not len(args) > 0:
            caller.respond(__("Usage: {CHARS}leave <channel>"))
            return

        if hasattr(protocol, "leave_channel"):
            result = protocol.leave_channel(args[0])

            if result:
                caller.respond(__("Done!"))
            else:
                caller.respond(__("Unable to leave channel. Does this "
                                  "protocol support leaving channels?"))
        else:
            caller.respond(__("This protocol doesn't support channels."))

    def raw_command(self, protocol, caller, source, command, raw_args,
                    args):
        """
        Command handler for the raw command
        """

        if not len(args) > 0:
            caller.respond(__("Usage: {CHARS}raw <data>"))
            return

        if hasattr(protocol, "send_raw"):
            protocol.send_raw(raw_args)

            caller.respond(__("Done!"))
        else:
            caller.respond(__("This protocol doesn't support sending raw "
                              "data."))

    def say_command(self, protocol, caller, source, command, raw_args,
                    args):
        """
        Command handler for the say command
        """

        if not len(args) > 1:
            caller.respond(__("Usage: {CHARS}say <target> <message>"))
            return

        channel = args[0]
        message = raw_args[len(channel):].strip()

#.........这里部分代码省略.........
开发者ID:NotAFile,项目名称:Ultros,代码行数:103,代码来源:__init__.py

示例13: DrunkPlugin

# 需要导入模块: from system.command_manager import CommandManager [as 别名]
# 或者: from system.command_manager.CommandManager import register_command [as 别名]
class DrunkPlugin(plugin.PluginObject):

    commands = None
    config = None
    storage = None

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

        ### Initial config load
        try:
            self.config = self.storage.get_file(self, "config", YAML,
                                                "plugins/drunkoctopus.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/drunkoctopus.yml")
            self.logger.error("Disabling...")
            self._disable_self()
            return

        ### Create vars and stuff
        self._sobering_call = None
        self._drunktalk = DrunkTalk()

        ### Load options from config
        self._load()

        self.config.add_callback(self._load)

        ### Register events and commands

        self.events.add_callback("MessageSent",
                                 self,
                                 self.outgoing_message_handler,
                                 1)
        self.commands.register_command("drunkenness",
                                       self.drunkenness_command,
                                       self,
                                       "drunkoctopus.drunkenness",
                                       default=True)
        self.commands.register_command("drink",
                                       self.drink_command,
                                       self,
                                       "drunkoctopus.drink")

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

    def _load(self):
        self._drunktalk.drunkenness = self.config["drunkenness"]
        self._cooldown_enabled = self.config["cooldown"]["enabled"]
        self._cooldown_time = self.config["cooldown"]["time"]
        self._cooldown_amount = self.config["cooldown"]["amount"]
        self._drinks = self.config["drinks"]

        # Sort out the sobering deferred as necessary
        if self._cooldown_enabled:
            if self._sobering_call is None:
                self.logger.trace("Starting sobering call due to config "
                                  "change")
                self._sobering_call = reactor.callLater(self._cooldown_time,
                                                        self._sober_up)
        else:
            if self._sobering_call is not None:
                self.logger.trace("Cancelling sobering call due to config "
                                  "change")
                self._sobering_call.cancel()

    def _sober_up(self):
        self.logger.trace("Sobering up")
        drunk = self._drunktalk.drunkenness
        drunk -= self._cooldown_amount
        if drunk < 0:
            drunk = 0
        self._drunktalk.drunkenness = drunk
        if self._cooldown_enabled:
            reactor.callLater(self._cooldown_time, self._sober_up)

    def drunkenness_command(self, protocol, caller, source, command, raw_args,
                            parsed_args):
        args = raw_args.split()  # Quick fix for new command handler signature
        if len(args) == 0:
            caller.respond("Drunkenness level: %s" %
                           self._drunktalk.drunkenness)
            return
        elif len(args) == 1:
            try:
                new_drunk = int(args[0])
#.........这里部分代码省略.........
开发者ID:EionRobb,项目名称:Ultros-contrib,代码行数:103,代码来源:__init__.py

示例14: LastFMPlugin

# 需要导入模块: from system.command_manager import CommandManager [as 别名]
# 或者: from system.command_manager.CommandManager import register_command [as 别名]
class LastFMPlugin(plugin.PluginObject):

    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/lastfm.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/lastfm.yml")
            self.logger.error("Disabling...")
            self._disable_self()
            return
            ### Same for the data file (nickname=>lastfmusername map)
        try:
            self._nickmap = self.storage.get_file(self, "data", YAML, "plugins/lastfm-nickmap.yml")
        except Exception:
            self.logger.exception("Error loading nickmap!")
            self.logger.error("Disabling...")
            self._disable_self()

        ### Load options from config and nick map from data
        self._load()

        self._config.add_callback(self._load)

        ### Register commands
        self.commands.register_command(
            "nowplaying", self.nowplaying_cmd, self, "lastfm.nowplaying", aliases=["np"], default=True
        )
        self.commands.register_command("lastfmnick", self.lastfmnick_cmd, self, "lastfm.lastfmnick", default=True)
        self.commands.register_command(
            "lastfmcompare", self.compare_cmd, self, "lastfm.compare", aliases=["musiccompare", "compare"], default=True
        )

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

    def _load(self):
        self.api = LastFM(self._apikey)

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

    @property
    def _recent_play_limit(self):
        # Allow for old configs without this setting
        if "recent_play_limit" in self._config:
            return self._config["recent_play_limit"]
        else:
            return 300  # 5 minutes in seconds

    def _get_username(self, user, none_if_unset=False):
        user = user.lower()
        try:
            return self._nickmap[user]
        except KeyError:
            if none_if_unset:
                return None
            else:
                return user

    def _set_username(self, user, lastfm_user):
        with self._nickmap:
            self._nickmap[user.lower()] = lastfm_user

    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("LastFM: " + msg)

    def lastfmnick_cmd(self, protocol, caller, source, command, raw_args, parsed_args):
        args = raw_args.split()  # Quick fix for new command handler signature
        if len(args) == 0:
            username = self._get_username(caller.nickname, True)
            if username is None:
                caller.respond("You have no stored username")
#.........这里部分代码省略.........
开发者ID:EionRobb,项目名称:Ultros-contrib,代码行数:103,代码来源:__init__.py

示例15: FactoidsPlugin

# 需要导入模块: from system.command_manager import CommandManager [as 别名]
# 或者: from system.command_manager.CommandManager import register_command [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


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