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


Python EventManager.run_callback方法代码示例

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


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

示例1: WebPlugin

# 需要导入模块: from system.event_manager import EventManager [as 别名]
# 或者: from system.event_manager.EventManager import run_callback [as 别名]

#.........这里部分代码省略.........
                            "OpenShift?"
                        )
                        return False
                    if not self.port:
                        self.logger.error(
                            "Unknown env var: OPENSHIFT__PORT - Are you on "
                            "OpenShift?"
                        )
                        return False
                else:
                    self.logger.error("Unknown hosted service: %s" % hosted)
                    return False

        else:
            if self.config.get("hostname", "0.0.0.0").strip() == "0.0.0.0":
                self.interface = ""
            else:
                self.interface = self.config.get("hostname")

            self.listen_port = self.config.get("port", 8080)

        return True

    def start(self, _=None):
        self.stats.start()

        self.port = reactor.listenTCP(
            self.listen_port, self.application, interface=self.interface
        )

        self.logger.info("Server started")
        self.running = True

        self.events.run_callback(
            "Web/ServerStartedEvent",
            ServerStartedEvent(self, self.application)
        )

    def stop(self):
        self.application.doStop()
        d = self.port.stopListening()

        d.addCallback(lambda _: self.logger.info("Server stopped"))
        d.addCallback(lambda _: setattr(self, "running", False))
        d.addCallback(lambda _: self.events.run_callback(
            "Web/ServerStopped", ServerStoppedEvent(self)
        ))

        d.addErrback(lambda f: self.logger.error("Failed to stop: %s" % f))

        self.stats.stop()

        return d

    def restart(self):
        d = self.stop()

        d.addCallback(lambda _: [self.load(), self.start()])

    def deactivate(self):
        d = self.stop()

        self.handlers.clear()
        self.navbar_items.clear()

        return d
开发者ID:case,项目名称:Ultros-contrib,代码行数:70,代码来源:__init__.py

示例2: Manager

# 需要导入模块: from system.event_manager import EventManager [as 别名]
# 或者: from system.event_manager.EventManager import run_callback [as 别名]
class Manager(object):
    """
    Manager for keeping track of multiple factories - one per protocol.

    This is so that the bot can connect to multiple services at once, and have
    them communicate with each other.
    """

    __metaclass__ = Singleton

    #: Instance of the storage manager
    storage = None

    #: Storage for all of our factories.
    factories = {}

    #: Storage for all of the protocol configs.
    configs = {}

    #: The main configuration is stored here.
    main_config = None

    #: Whether the manager is already running or not
    running = False

    def __init__(self):
        self.commands = CommandManager()
        self.event_manager = EventManager()
        self.logger = getLogger("Manager")
        self.plugman = PluginManager(self)
        self.yapsy_logger = getLogger("yapsy")

        self.metrics = None

    @property
    def all_plugins(self):
        return self.plugman.info_objects

    @property
    def loaded_plugins(self):
        return self.plugman.plugin_objects

    def setup(self):
        signal.signal(signal.SIGINT, self.signal_callback)

        self.yapsy_logger.debug_ = self.yapsy_logger.debug
        self.yapsy_logger.debug = self.yapsy_logger.trace

        self.storage = StorageManager()
        self.main_config = self.storage.get_file(self, "config", YAML,
                                                 "settings.yml")

        self.commands.set_factory_manager(self)

        self.load_config()  # Load the configuration

        try:
            self.metrics = Metrics(self.main_config, self)
        except Exception:
            self.logger.exception(_("Error setting up metrics."))

        self.plugman.scan()
        self.load_plugins()  # Load the configured plugins
        self.load_protocols()  # Load and set up the protocols

        if not len(self.factories):
            self.logger.info(_("It seems like no protocols are loaded. "
                               "Shutting down.."))
            return

    def run(self):
        if not self.running:
            event = ReactorStartedEvent(self)

            reactor.callLater(0, self.event_manager.run_callback,
                              "ReactorStarted", event)

            self.running = True
            reactor.run()
        else:
            raise RuntimeError(_("Manager is already running!"))

    def signal_callback(self, signum, frame):
        try:
            try:
                self.unload()
            except Exception:
                self.logger.exception(_("Error while unloading!"))
                try:
                    reactor.stop()
                except Exception:
                    try:
                        reactor.crash()
                    except Exception:
                        pass
        except Exception:
            exit(0)

    # Load stuff

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

示例3: Protocol

# 需要导入模块: from system.event_manager import EventManager [as 别名]
# 或者: from system.event_manager.EventManager import run_callback [as 别名]

#.........这里部分代码省略.........
                    return

                self.log.info("Connected to Inter, version %s" % v)

                message = {
                    "api_key": self.config["connection"]["api_key"]
                }

                self.send(message)

            if "from" in message:
                origin = message["from"]

                for case, default in Switch(origin):
                    if case("chat"):
                        source = message["source"]
                        msg = message["message"]

                        user = self.get_user(
                            message["user"], server=source, create=True
                        )
                        if not user.server:
                            user.server = source

                        if user == self.ourselves:
                            break  # Since, well, this is us.

                        if source == self.nickname:
                            break  # Since this is also us.

                        event = general_events.PreMessageReceived(
                            self, user, user, msg, "message"  # No channels
                        )
                        self.event_manager.run_callback("PreMessageReceived",
                                                        event)
                        if event.printable:
                            for line in event.message.split("\n"):
                                self.log.info("<%s> %s" % (user, line))

                        if not event.cancelled:
                            result = self.command_manager.process_input(
                                event.message, user, user, self,
                                self.control_chars, self.nickname
                            )

                            for c, d in Switch(result[0]):
                                if c(CommandState.RateLimited):
                                    self.log.debug("Command rate-limited")
                                    user.respond("That command has been "
                                                 "rate-limited, please try "
                                                 "again later.")
                                    return  # It was a command
                                if c(CommandState.NotACommand):
                                    self.log.debug("Not a command")
                                    break
                                if c(CommandState.UnknownOverridden):
                                    self.log.debug("Unknown command "
                                                   "overridden")
                                    return  # It was a command
                                if c(CommandState.Unknown):
                                    self.log.debug("Unknown command")
                                    break
                                if c(CommandState.Success):
                                    self.log.debug("Command ran successfully")
                                    return  # It was a command
                                if c(CommandState.NoPermission):
开发者ID:EionRobb,项目名称:Ultros-contrib,代码行数:70,代码来源:protocol.py

示例4: FactoidsPlugin

# 需要导入模块: from system.event_manager import EventManager [as 别名]
# 或者: from system.event_manager.EventManager import run_callback [as 别名]

#.........这里部分代码省略.........
    # endregion

    # region API functions to access factoids

    def _add_factoid_interaction(self, txn, factoid_key, location, protocol,
                                 channel, factoid, info):
        """
        Appends a factoid to an existing one if there, otherwise creates it.
        :return: True if already exists, otherwise False
        """
        txn.execute("SELECT * FROM factoids WHERE "
                    "factoid_key = ? AND location = ? AND "
                    "protocol = ? AND channel = ?",
                    (
                        to_unicode(factoid_key),
                        to_unicode(location),
                        to_unicode(protocol),
                        to_unicode(channel)
                    ))
        results = txn.fetchall()
        if len(results) == 0:
            # Factoid doesn't exist yet, create it
            txn.execute("INSERT INTO factoids VALUES(?, ?, ?, ?, ?, ?)",
                        (
                            to_unicode(factoid_key),
                            to_unicode(location),
                            to_unicode(protocol),
                            to_unicode(channel),
                            to_unicode(factoid),
                            to_unicode(info)
                        ))

            e = FactoidAddedEvent(self, factoid_key, factoid)
            self.events.run_callback("Factoids/Added", e, from_thread=True)
            return False
        else:
            # Factoid already exists, append
            txn.execute("INSERT INTO factoids VALUES(?, ?, ?, ?, ?, ?)",
                        (
                            to_unicode(results[0][0]),
                            to_unicode(results[0][1]),
                            to_unicode(results[0][2]),
                            to_unicode(results[0][3]),
                            to_unicode(results[0][4]),
                            results[0][5] + u"\n" + to_unicode(info)
                        ))
            e = FactoidUpdatedEvent(self, factoid_key, factoid)
            self.events.run_callback("Factoids/Updated", e, from_thread=True)
            return True

    def _delete_factoid_interaction(self, txn, factoid_key, location, protocol,
                                    channel):
        """
        Deletes a factoid if it exists, otherwise raises MissingFactoidError
        """

        self.logger.trace("DELETE | Key: %s | Loc: %s | Pro: %s | Cha: %s"
                          % (factoid_key, location, protocol, channel))

        if location == self.CHANNEL:
            txn.execute("DELETE FROM factoids WHERE factoid_key = ? AND "
                        "location = ? AND protocol = ? AND channel = ?",
                        (
                            to_unicode(factoid_key),
                            to_unicode(location),
                            to_unicode(protocol),
开发者ID:NotAFile,项目名称:Ultros,代码行数:70,代码来源:__init__.py

示例5: Protocol

# 需要导入模块: from system.event_manager import EventManager [as 别名]
# 或者: from system.event_manager.EventManager import run_callback [as 别名]
class Protocol(SingleChannelProtocol):

    TYPE = "mumble"

    VERSION_MAJOR = 1
    VERSION_MINOR = 2
    VERSION_PATCH = 4

    VERSION_DATA = (VERSION_MAJOR << 16)\
        | (VERSION_MINOR << 8) \
        | VERSION_PATCH

    # From the Mumble protocol documentation
    PREFIX_FORMAT = ">HI"
    PREFIX_LENGTH = 6

    # This specific order of IDs is extracted from
    # https://github.com/mumble-voip/mumble/blob/master/src/Message.h
    ID_MESSAGE = [
        Mumble_pb2.Version,
        Mumble_pb2.UDPTunnel,
        Mumble_pb2.Authenticate,
        Mumble_pb2.Ping,
        Mumble_pb2.Reject,
        Mumble_pb2.ServerSync,
        Mumble_pb2.ChannelRemove,
        Mumble_pb2.ChannelState,
        Mumble_pb2.UserRemove,
        Mumble_pb2.UserState,
        Mumble_pb2.BanList,
        Mumble_pb2.TextMessage,
        Mumble_pb2.PermissionDenied,
        Mumble_pb2.ACL,
        Mumble_pb2.QueryUsers,
        Mumble_pb2.CryptSetup,
        Mumble_pb2.ContextActionModify,
        Mumble_pb2.ContextAction,
        Mumble_pb2.UserList,
        Mumble_pb2.VoiceTarget,
        Mumble_pb2.PermissionQuery,
        Mumble_pb2.CodecVersion,
        Mumble_pb2.UserStats,
        Mumble_pb2.RequestBlob,
        Mumble_pb2.ServerConfig
    ]

    # Reversing the IDs, so we are able to backreference.
    MESSAGE_ID = dict([(v, k) for k, v in enumerate(ID_MESSAGE)])

    PING_REPEAT_TIME = 5

    channels = {}
    users = {}
    _acls = {}

    @property
    def num_channels(self):
        return len(self.channels)

    control_chars = "."

    pinging = True

    ourselves = None

    def __init__(self, name, factory, config):
        self.name = name
        self.factory = factory
        self.config = config

        self.received = ""
        self.log = getLogger(self.name)
        self.log.info("Setting up..")

        self.command_manager = CommandManager()
        self.event_manager = EventManager()

        self.username = config["identity"]["username"]
        self.password = config["identity"]["password"]
        self.networking = config["network"]
        self.tokens = config["identity"]["tokens"]

        self.control_chars = config["control_chars"]

        audio_conf = config.get("audio", {})
        self.should_mute_self = audio_conf.get("should_mute_self", True)
        self.should_deafen_self = audio_conf.get("should_deafen_self", True)

        event = general_events.PreConnectEvent(self, config)
        self.event_manager.run_callback("PreConnect", event)

        context = self._get_client_context()
        if context is None:
            # Could not create a context (problem loading cert file)
            self.factory.manager.remove_protocol(self.name)
            return

        reactor.connectSSL(
            self.networking["address"],
            self.networking["port"],
#.........这里部分代码省略.........
开发者ID:gsingh123,项目名称:Ultros,代码行数:103,代码来源:protocol.py

示例6: CommandManager

# 需要导入模块: from system.event_manager import EventManager [as 别名]
# 或者: from system.event_manager.EventManager import run_callback [as 别名]

#.........这里部分代码省略.........
                    "Protocol %s doesn't have a control character sequence." %
                    protocol.name
                )

        if our_name is None:
            if hasattr(protocol, "nickname"):
                our_name = protocol.nickname

        if our_name is not None:
            control_char = control_char.replace("{NAME}", our_name)
            control_char = control_char.replace("{NICK}", our_name)

        if len(in_str) < len(control_char):
            self.logger.trace("Control character sequence is longer than the "
                              "input string, so this cannot be a command.")
            return CommandState.NotACommand, None

        if in_str.lower().startswith(control_char.lower()):  # It's a command!
            # Remove the command char(s) from the start
            replaced = in_str[len(control_char):]

            split = replaced.split(None, 1)
            if not split:
                return False
            command = split[0]
            args = ""
            if len(split) > 1:
                args = split[1]

            printable = "<%s:%s> %s" % (caller, source, in_str)

            event = events.PreCommand(protocol, command, args, caller,
                                      source, printable, in_str)
            self.event_manager.run_callback("PreCommand", event)

            if event.printable:
                self.logger.info("%s | %s" % (protocol.name,
                                              event.printable)
                                 )

            result = self.run_command(event.command, event.source,
                                      event.target, protocol, event.args)

            return result

        self.logger.debug("Command not found.")
        return CommandState.NotACommand, None

    def run_command(self, command, caller, source, protocol, args):
        """Run a command, provided it's been registered.

        :param command: The command, a string
        :param caller: Who ran the command
        :param source: Where they ran the command
        :param protocol: The protocol they're part of
        :param args: A list of arguments for the command

        :type command: str
        :type caller: User
        :type source: User
        :type protocol: Protocol
        :type args: list

        :return: Tuple containing CommandState representing the state of
            the command, and either None or an Exception.
        :rtype: tuple(CommandState, None or Exception)
开发者ID:NotAFile,项目名称:Ultros,代码行数:70,代码来源:command_manager.py


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