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


Python EventManager.add_callback方法代码示例

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


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

示例1: MemosPlugin

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

示例2: WebhooksPlugin

# 需要导入模块: from system.event_manager import EventManager [as 别名]
# 或者: from system.event_manager.EventManager import add_callback [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: AssPlugin

# 需要导入模块: from system.event_manager import EventManager [as 别名]
# 或者: from system.event_manager.EventManager import add_callback [as 别名]
class AssPlugin(plugin.PluginObject):

    events = None
    regex = None

    def setup(self):
        self.events = EventManager()
        self.regex = re.compile(r"(\w+)-ass (\w+)")

        self.events.add_callback("MessageReceived", self, self.ass_swap, 1)

    def ass_swap(self, event=MessageReceived):
        source = event.source
        target = event.target
        message = event.message

        if re.search(self.regex, message) is None:
            return

        result = re.sub(self.regex, r"\1 ass-\2", message)

        target.respond("%s: %s" % (source.nickname, result))
开发者ID:EionRobb,项目名称:Ultros-contrib,代码行数:24,代码来源:__init__.py

示例4: ReplPlugin

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

示例5: WebPlugin

# 需要导入模块: from system.event_manager import EventManager [as 别名]
# 或者: from system.event_manager.EventManager import add_callback [as 别名]
class WebPlugin(PluginObject):
    """
    Web plugin object
    """

    api_log = None
    api_keys = None

    api_key_data = {}
    config = {}
    data = {}

    namespace = {}  # Global, not used right now

    handlers = {}  # Cyclone handlers

    interface = ""  # Listening interface
    listen_port = 8080

    running = False

    application = None  # Cyclone application
    port = None  # Twisted's server port
    storage = None
    template_loader = None

    navbar_items = {}

    ## Stuff plugins might find useful

    commands = None
    events = None
    packages = None
    plugins = None
    sessions = None
    stats = None

    ## Internal(ish) functions

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

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

        try:
            self.data = self.storage.get_file(self, "data", JSON,
                                              "plugins/web/data.json")
            self.logger.debug("Data loaded")
        except Exception:
            self.logger.exception("Error loading data file!")
            return self._disable_self()

        try:
            _sessions = self.storage.get_file(self, "data", JSON,
                                              "plugins/web/sessions.json")
            self.logger.debug("Sessions loaded")
        except Exception:
            self.logger.exception("Error loading sessions file!")
            return self._disable_self()

        try:
            self.api_log = open("logs/api.log", "w")
        except Exception:
            self.logger.exception("Unable to open api log file!")
            return self._disable_self()

        try:
            self.api_key_data = self.storage.get_file(
                self, "data", JSON, "plugins/web/apikeys.json"
            )
            self.logger.debug("Sessions loaded")
        except Exception:
            self.logger.exception("Error loading API keys!")
            return self._disable_self()

        try:
            self.api_log = open("logs/api.log", "w")
        except Exception:
            self.logger.exception("Unable to open api log file!")
            return self._disable_self()

        self.config.add_callback(self.restart)
        self.data.add_callback(self.restart)

        # Index page

        self.add_handler(r"/", "plugins.web.routes.index.Route")

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

示例6: DrunkPlugin

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

示例7: LastseenPlugin

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

示例8: AuthPlugin

# 需要导入模块: from system.event_manager import EventManager [as 别名]
# 或者: from system.event_manager.EventManager import add_callback [as 别名]
class AuthPlugin(plugin.PluginObject):
    """
    Auth plugin. In charge of logins and permissions.
    """

    config = None
    passwords = None
    permissions = None
    blacklist = None

    commands = None
    events = None
    storage = None

    auth_h = None
    perms_h = None

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

        reload(auth_handler)
        reload(permissions_handler)

        self.logger.trace(_("Entered setup method."))

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

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

        if self.config["use-permissions"]:
            try:
                self.permissions = self.storage.get_file(self, "data", YAML,
                                                         "plugins/auth/"  # PEP
                                                         "permissions.yml")
            except Exception:
                self.logger.exception(_("Unable to load permissions. They "
                                        "will be unavailable!"))
            else:
                self.perms_h = permissions_handler.permissionsHandler(
                    self, self.permissions)
                result = self.commands.set_permissions_handler(self.perms_h)
                if not result:
                    self.logger.warn(_("Unable to set permissions handler!"))

        if self.config["use-auth"]:
            try:
                self.passwords = self.storage.get_file(self, "data", YAML,
                                                       "plugins/auth/"  # PEP!
                                                       "passwords.yml")
                self.blacklist = self.storage.get_file(self, "data", YAML,
                                                       "plugins/auth/"  # PEP!
                                                       "blacklist.yml")
            except Exception:
                self.logger.exception(_("Unable to load user accounts. They "
                                        "will be unavailable!"))
            else:
                self.auth_h = auth_handler.authHandler(self, self.passwords,
                                                       self.blacklist)
                result = self.commands.set_auth_handler(self.auth_h)
                if not result:
                    self.logger.warn(_("Unable to set auth handler!"))

        self.logger.debug(_("Registering commands."))
        self.commands.register_command("login", self.login_command,
                                       self, "auth.login", default=True)
        self.commands.register_command("logout", self.logout_command,
                                       self, "auth.login", default=True)
        self.commands.register_command("register", self.register_command,
                                       self, "auth.register", default=True)
        self.commands.register_command("passwd", self.passwd_command, self,
                                       "auth.passwd", default=True)

        self.events.add_callback("PreCommand", self, self.pre_command, 10000)

    def pre_command(self, event=PreCommand):
        """
        Pre-command hook to remove passwords from the log output.
        """

        self.logger.trace(_("Command: %s") % event.command)
        if event.command.lower() in ["login", "register"]:
            if len(event.args) >= 2:
                split_ = event.printable.split("%s " % event.command)
                second_split = split_[1].split()
#.........这里部分代码省略.........
开发者ID:NotAFile,项目名称:Ultros,代码行数:103,代码来源:__init__.py

示例9: TriggersPlugin

# 需要导入模块: from system.event_manager import EventManager [as 别名]
# 或者: from system.event_manager.EventManager import add_callback [as 别名]
class TriggersPlugin(plugin.PluginObject):

    commands = None
    events = None
    storage = None

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

        ### Register event handlers
        def _message_event_filter(event=MessageReceived):
            return isinstance(event.target, Channel)

        self.events.add_callback("MessageReceived",
                                 self,
                                 self.message_handler,
                                 1,
                                 _message_event_filter)

        self.events.add_callback("ActionReceived",
                                 self,
                                 self.action_handler,
                                 1,
                                 _message_event_filter)

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

    @property
    def _triggers(self):
        return self._config.get("triggers", {})

    def message_handler(self, event=MessageReceived):
        self.event_handler(
            event.caller,
            event.source,
            event.target,
            event.message,
            event.type
        )

    def action_handler(self, event=ActionReceived):
        self.event_handler(
            event.caller,
            event.source,
            event.target,
            event.message,
            "action"
        )

    def event_handler(self, protocol, source, target, message, e_type):
        """
        Event handler for general messages
        """

        allowed = self.commands.perm_handler.check("triggers.trigger",
                                                   source,
                                                   target,
                                                   protocol)
        if not allowed:
            return

        # TODO: Rewrite this when Matcher is finished

        # TODO: We check the types of half of these - do the rest

        global_triggers = self._triggers.get("global", [])
        proto_trigger_block = self._triggers.get("protocols", {})

        proto_triggers = proto_trigger_block.get(protocol.name, {})
        if not isinstance(proto_triggers, dict):
            self.logger.error(
                "Invalid triggers for protocol '%s'" % protocol.name
#.........这里部分代码省略.........
开发者ID:domainr,项目名称:Ultros-contrib,代码行数:103,代码来源:__init__.py

示例10: FactoidsPlugin

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

示例11: DialectizerPlugin

# 需要导入模块: from system.event_manager import EventManager [as 别名]
# 或者: from system.event_manager.EventManager import add_callback [as 别名]
class DialectizerPlugin(plugin.PluginObject):
    """Dialectizer plugin object"""

    commands = None
    data = None
    events = None
    storage = None

    dialectizers = {"chef": Chef(),
                    "fudd": Fudd(),
                    "lower": Lower(),
                    "off": Dialectizer(),
                    "olde": Olde(),
                    "reverse": Reverse(),
                    "upper": Upper()}

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

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

        self.data = self.storage.get_file(self, "data", YAML,
                                          "plugins/dialectizer/settings.yml")

        self.events.add_callback("MessageSent", self, self.handle_msg_sent,
                                 1)
        self.commands.register_command("dialectizer", self.dialectizer_command,
                                       self, "dialectizer.set",
                                       aliases=["dialectiser"])

    def handle_msg_sent(self, event=MessageSent):
        """Handler for general message sent event"""

        if isinstance(event.target, User):
            return

        name = event.caller.name
        target = event.target.name

        with self.data:
            if name not in self.data:
                self.data[name] = {}

            if target not in self.data[name]:
                self.data[name][target] = "off"

        subber = self.dialectizers[self.data[name][target]]

        message = event.message
        message = subber.sub(message)
        event.message = message

    def dialectizer_command(self, protocol, caller, source, command, raw_args,
                            parsed_args):
        """Handler for the dialectizer command"""

        args = raw_args.split()  # Quick fix for new command handler signature
        if isinstance(source, User):
            caller.respond(__("This command only applies to channels."))
            return
        if not len(args) > 0:
            caller.respond(__("Usage: {CHARS}dialectizer <dialectizer>"))
            caller.respond(__("Available dialectizers: %s")
                           % ", ".join(self.dialectizers.keys()))
            return

        with self.data:
            if protocol.name not in self.data:
                self.data[protocol.name] = {}

            if source.name not in self.data[protocol.name]:
                self.data[protocol.name][source.name] = "off"

            setting = args[0].lower()
            if setting not in self.dialectizers:
                caller.respond(__("Unknown dialectizer: %s") % setting)
                return

            self.data[protocol.name][source.name] = setting
            caller.respond(__("Dialectizer set to '%s'") % setting)
开发者ID:NotAFile,项目名称:Ultros,代码行数:84,代码来源:__init__.py

示例12: BlowfishPlugin

# 需要导入模块: from system.event_manager import EventManager [as 别名]
# 或者: from system.event_manager.EventManager import add_callback [as 别名]
class BlowfishPlugin(plugin.PluginObject):
    """
    Blowfish-CBC support, as seen in Eggdrop and mIRC scripts
    """

    config = None
    events = None
    storage = None

    def get_target(self, protocol, target):
        return self.config.get(  # PEP! \o/
            protocol, {}
        ).get(
            "targets", {}
        ).get(
            target, None
        )

    def get_global(self, protocol):
        return self.config.get(protocol, {}).get("global", None)

    def setup(self):
        self.events = EventManager()
        self.storage = StorageManager()

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

        self.events.add_callback(
            "PreMessageReceived", self, self.pre_message, 10001
        )

        self.events.add_callback(
            "MessageSent", self, self.message_sent, 10001
        )

        self.events.add_callback(
            "ActionReceived", self, self.message_sent, 10001
        )

        self.events.add_callback(
            "ActionSent", self, self.message_sent, 10001
        )

    def pre_message(self, event=PreMessageReceived):
        if not event.caller:
            return

        target = event.target
        if not target:
            target = event.source

        key = self.get_target(event.caller.name, target)
        if not key:
            key = self.get_global(event.caller.name)
        if key:
            if event.message.startswith("+OK "):
                message = event.message[4:]

                try:
                    result = self.decode(key, message)
                except Exception:
                    self.logger.exception("Unable to decode message")
                    event.cancelled = True
                else:
                    event.message = result
            else:
                event.cancelled = True

    def message_sent(self, event=MessageSent):
        if not event.caller:
            return

        key = self.get_target(event.caller.name, event.target.name)
        if not key:
            key = self.get_global(event.caller.name)
        if key:
            message = event.message

            try:
                result = self.encode(key, message)
            except Exception:
                self.logger.exception("Unable to encode message")
                event.cancelled = True
            else:
                event.message = "+OK %s" % result

    def action_received(self, event=ActionReceived):
        if not event.caller:
            return

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

示例13: TwilioPlugin

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

示例14: URLsPlugin

# 需要导入模块: from system.event_manager import EventManager [as 别名]
# 或者: from system.event_manager.EventManager import add_callback [as 别名]
class URLsPlugin(plugin.PluginObject):
    """
    URLs plugin object
    """

    catcher = None
    channels = None
    commands = None
    config = None
    events = None
    shortened = None
    storage = None

    blacklist = []
    handlers = {}
    shorteners = {}
    spoofing = {}

    content_types = ["text/html", "text/webviewhtml", "message/rfc822",
                     "text/x-server-parsed-html", "application/xhtml+xml"]

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

        self.logger.trace(_("Entered setup method."))
        self.storage = StorageManager()
        try:
            self.config = self.storage.get_file(self, "config", YAML,
                                                "plugins/urls.yml")
        except Exception:
            self.logger.exception(_("Error loading configuration!"))
        else:
            if not self.config.exists:
                self.logger.warn(_("Unable to find config/plugins/urls.yml"))
            else:
                self.content_types = self.config["content_types"]
                self.spoofing = self.config["spoofing"]

        self.logger.debug(_("Spoofing: %s") % self.spoofing)

        self.channels = self.storage.get_file(self, "data", YAML,
                                              "plugins/urls/channels.yml")
        self.shortened = self.storage.get_file(
            self,
            "data",
            DBAPI,
            "sqlite3:data/plugins/urls/shortened.sqlite",
            "data/plugins/urls/shortened.sqlite",
            check_same_thread=False
        )

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

        self.reload()

        def message_event_filter(event=MessageReceived):
            target = event.target
            type_ = event.type

            return type_ == "message" \
                or isinstance(target, Channel) \
                or isinstance(target, User)

        self.add_shortener("tinyurl", self.tinyurl)

        self.events.add_callback("MessageReceived", self, self.message_handler,
                                 1, message_event_filter)
        self.commands.register_command("urls", self.urls_command, self,
                                       "urls.manage")
        self.commands.register_command("shorten", self.shorten_command, self,
                                       "urls.shorten", default=True)

    def reload(self):
        """
        Reload files and create tables as necessary
        """

        self.shortened.runQuery("CREATE TABLE IF NOT EXISTS urls ("
                                "url TEXT, "
                                "shortener TEXT, "
                                "result TEXT)")

        self.catcher = Catcher(self, self.config, self.storage, self.logger)

        self.blacklist = []
        blacklist = self.config.get("blacklist", [])

        for element in blacklist:
            try:
                self.blacklist.append(re.compile(element))
            except Exception:
                self.logger.exception("Unable to compile regex '%s'" % element)

    def check_blacklist(self, url):
        """
        Check whether a URL is in the user-defined blacklist

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

示例15: BridgePlugin

# 需要导入模块: from system.event_manager import EventManager [as 别名]
# 或者: from system.event_manager.EventManager import add_callback [as 别名]
class BridgePlugin(plugin.PluginObject):
    """
    Message bridging plugin object
    """

    config = None
    events = None
    commands = None
    storage = None

    rules = {}

    @property
    def rules(self):
        """
        The list of bridging rules
        """

        return self.config["rules"]

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

        self.logger.trace(_("Entered setup method."))
        self.storage = StorageManager()

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

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

        # General

        self.events.add_callback("PreMessageReceived", self, self.handle_msg,
                                 1000)

        self.events.add_callback("MessageSent", self, self.handle_msg_sent,
                                 0)

        # self.events.add_callback("PreCommand", self, self.handle_command,
        #                          1000)

        self.events.add_callback("ActionSent", self, self.handle_action_sent,
                                 0)

        self.events.add_callback("UserDisconnected", self,
                                 self.handle_disconnect, 1000)

        # IRC

        self.events.add_callback("IRC/UserJoined", self,
                                 self.handle_irc_join, 1000)

        self.events.add_callback("IRC/UserParted", self,
                                 self.handle_irc_part, 1000)

        self.events.add_callback("IRC/UserKicked", self,
                                 self.handle_irc_kick, 1000)

        self.events.add_callback("IRC/UserQuit", self,
                                 self.handle_irc_quit, 1000)

        self.events.add_callback("IRC/CTCPQueryReceived", self,
                                 self.handle_irc_action, 1000)

        # Mumble

        self.events.add_callback("Mumble/UserRemove", self,
                                 self.handle_mumble_remove, 1000)

        self.events.add_callback("Mumble/UserJoined", self,
                                 self.handle_mumble_join, 1000)

        self.events.add_callback("Mumble/UserMoved", self,
                                 self.handle_mumble_move, 1000)

    def handle_irc_join(self, event=UserJoinedEvent):
        """
        Event handler for IRC join events
        """

        self.do_rules("", event.caller, event.user, event.channel,
                      f_str=["general", "join"],
                      tokens={"CHANNEL": event.channel.name})

    def handle_irc_part(self, event=UserPartedEvent):
#.........这里部分代码省略.........
开发者ID:NotAFile,项目名称:Ultros,代码行数:103,代码来源:__init__.py


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