示例#1
0
    def start(self, ev_channel=None, rss_url=None, rss_rate=None):
        """
        Start by telling the portal to start a new RSS session

        ev_channel - key of the Evennia channel to connect to
        rss_url - full URL to the RSS feed to subscribe to
        rss_update_rate - how often for the feedreader to update
        """
        global _SESSIONS
        if not _SESSIONS:
            from src.server.sessionhandler import SESSIONS as _SESSIONS

        if ev_channel:
            # connect to Evennia channel
            channel = search.channel_search(ev_channel)
            if not channel:
                raise RuntimeError("Evennia Channel '%s' not found." % ev_channel)
            channel = channel[0]
            self.db.ev_channel = channel
        if rss_url:
            self.db.rss_url = rss_url
        if rss_rate:
            self.db.rss_rate = rss_rate
        # instruct the server and portal to create a new session with
        # the stored configuration
        configdict = {"uid": self.dbid, "url": self.db.rss_url, "rate": self.db.rss_rate}
        _SESSIONS.start_bot_session("src.server.portal.rss.RSSBotFactory", configdict)
示例#2
0
    def start(self, ev_channel=None, rss_url=None, rss_rate=None):
        """
        Start by telling the portal to start a new RSS session

        ev_channel - key of the Evennia channel to connect to
        rss_url - full URL to the RSS feed to subscribe to
        rss_update_rate - how often for the feedreader to update
        """
        global _SESSIONS
        if not _SESSIONS:
            from src.server.sessionhandler import SESSIONS as _SESSIONS

        if ev_channel:
            # connect to Evennia channel
            channel = search.channel_search(ev_channel)
            if not channel:
                raise RuntimeError("Evennia Channel '%s' not found." %
                                   ev_channel)
            channel = channel[0]
            self.db.ev_channel = channel
        if rss_url:
            self.db.rss_url = rss_url
        if rss_rate:
            self.db.rss_rate = rss_rate
        # instruct the server and portal to create a new session with
        # the stored configuration
        configdict = {
            "uid": self.dbid,
            "url": self.db.rss_url,
            "rate": self.db.rss_rate
        }
        _SESSIONS.start_bot_session("src.server.portal.rss.RSSBotFactory",
                                    configdict)
示例#3
0
文件: tests.py 项目: Zurriel/evennia
    def setUp(self):
        "sets up testing environment"
        settings.DEFAULT_HOME = "#2"
        # print "creating player %i: %s" % (self.CID, self.__class__.__name__)
        self.player = create.create_player(
            "TestPlayer%i" % self.CID, "*****@*****.**", "testpassword", typeclass=TestPlayerClass
        )
        self.player2 = create.create_player(
            "TestPlayer%ib" % self.CID, "*****@*****.**", "testpassword", typeclass=TestPlayerClass
        )
        self.room1 = create.create_object("src.objects.objects.Room", key="Room%i" % self.CID, nohome=True)
        self.room1.db.desc = "room_desc"
        self.room2 = create.create_object("src.objects.objects.Room", key="Room%ib" % self.CID)
        self.obj1 = create.create_object(TestObjectClass, key="Obj%i" % self.CID, location=self.room1, home=self.room1)
        self.obj2 = create.create_object(TestObjectClass, key="Obj%ib" % self.CID, location=self.room1, home=self.room1)
        self.char1 = create.create_object(
            TestCharacterClass, key="Char%i" % self.CID, location=self.room1, home=self.room1
        )
        self.char1.permissions.add("Immortals")
        self.char2 = create.create_object(
            TestCharacterClass, key="Char%ib" % self.CID, location=self.room1, home=self.room1
        )
        self.char1.player = self.player
        self.char2.player = self.player2
        self.script = create.create_script("src.scripts.scripts.Script", key="Script%i" % self.CID)
        self.player.permissions.add("Immortals")

        # set up a fake session

        global SESSIONS
        session = ServerSession()
        session.init_session("telnet", ("localhost", "testmode"), SESSIONS)
        session.sessid = self.CID
        SESSIONS.portal_connect(session.get_sync_data())
        SESSIONS.login(SESSIONS.session_from_sessid(self.CID), self.player, testmode=True)
示例#4
0
    def func(self):
        """
        Get all connected players by polling session.
        """

        player = self.player
        session_list = SESSIONS.get_sessions()

        session_list = sorted(session_list, key=lambda o: o.player.key)

        if self.cmdstring == "doing":
            show_session_data = False
        else:
            show_session_data = player.check_permstring(
                "Immortals") or player.check_permstring("Wizards")

        nplayers = (SESSIONS.player_count())
        if show_session_data:
            # privileged info
            table = prettytable.PrettyTable([
                "{wPlayer Name", "{wOn for", "{wIdle", "{wPuppeting", "{wRoom",
                "{wCmds", "{wProtocol", "{wHost"
            ])
            for session in session_list:
                if not session.logged_in: continue
                delta_cmd = time.time() - session.cmd_last_visible
                delta_conn = time.time() - session.conn_time
                player = session.get_player()
                puppet = session.get_puppet()
                location = puppet.location.key if puppet else "None"
                table.add_row([
                    utils.crop(player.name, width=25),
                    utils.time_format(delta_conn, 0),
                    utils.time_format(delta_cmd, 1),
                    utils.crop(puppet.key if puppet else "None", width=25),
                    utils.crop(location, width=25), session.cmd_total,
                    session.protocol_key,
                    isinstance(session.address, tuple) and session.address[0]
                    or session.address
                ])
        else:
            # unprivileged
            table = prettytable.PrettyTable(
                ["{wPlayer name", "{wOn for", "{wIdle"])
            for session in session_list:
                if not session.logged_in:
                    continue
                delta_cmd = time.time() - session.cmd_last_visible
                delta_conn = time.time() - session.conn_time
                player = session.get_player()
                table.add_row([
                    utils.crop(player.key, width=25),
                    utils.time_format(delta_conn, 0),
                    utils.time_format(delta_cmd, 1)
                ])

        isone = nplayers == 1
        string = "{wPlayers:{n\n%s\n%s unique account%s logged in." % (
            table, "One" if isone else nplayers, "" if isone else "s")
        self.msg(string)
示例#5
0
    def setUp(self):
        "sets up testing environment"
        settings.DEFAULT_HOME = "#2"
        #print "creating player %i: %s" % (self.CID, self.__class__.__name__)
        self.player = create.create_player("TestPlayer%i" % self.CID, "*****@*****.**", "testpassword", typeclass=TestPlayerClass)
        self.player2 = create.create_player("TestPlayer%ib" % self.CID, "*****@*****.**", "testpassword", typeclass=TestPlayerClass)
        self.room1 = create.create_object("src.objects.objects.Room", key="Room%i"%self.CID, nohome=True)
        self.room1.db.desc = "room_desc"
        self.room2 = create.create_object("src.objects.objects.Room", key="Room%ib" % self.CID)
        self.obj1 = create.create_object(TestObjectClass, key="Obj%i" % self.CID, location=self.room1, home=self.room1)
        self.obj2 = create.create_object(TestObjectClass, key="Obj%ib" % self.CID, location=self.room1, home=self.room1)
        self.char1 = create.create_object(TestCharacterClass, key="Char%i" % self.CID, location=self.room1, home=self.room1)
        self.char1.permissions.add("Immortals")
        self.char2 = create.create_object(TestCharacterClass, key="Char%ib" % self.CID, location=self.room1, home=self.room1)
        self.char1.player = self.player
        self.char2.player = self.player2
        self.script = create.create_script("src.scripts.scripts.Script", key="Script%i" % self.CID)
        self.player.permissions.add("Immortals")

        # set up a fake session

        global SESSIONS
        session = ServerSession()
        session.init_session("telnet", ("localhost", "testmode"), SESSIONS)
        session.sessid = self.CID
        SESSIONS.portal_connect(session.get_sync_data())
        SESSIONS.login(SESSIONS.session_from_sessid(self.CID), self.player, testmode=True)
示例#6
0
 def func(self):
     "Implements command"
     if not self.args:
         self.caller.msg("Usage: @wall <message>")
         return
     message = "%s shouts \"%s\"" % (self.caller.name, self.args)
     self.msg("Announcing to all connected players ...")
     SESSIONS.announce_all(message)
示例#7
0
文件: admin.py 项目: Aumnren/evennia
 def func(self):
     "Implements command"
     if not self.args:
         self.caller.msg("Usage: @wall <message>")
         return
     message = '%s shouts "%s"' % (self.caller.name, self.args)
     self.msg("Announcing to all connected players ...")
     SESSIONS.announce_all(message)
示例#8
0
 def at_repeat(self):
     "called every 60 seconds"
     global _SESSIONS
     if not _SESSIONS:
         from src.server.sessionhandler import SESSIONS as _SESSIONS
     #print "session check!"
     #print "ValidateSessions run"
     _SESSIONS.validate_sessions()
示例#9
0
 def at_repeat(self):
     "called every 60 seconds"
     global _SESSIONS
     if not _SESSIONS:
         from src.server.sessionhandler import SESSIONS as _SESSIONS
     #print "session check!"
     #print "ValidateSessions run"
     _SESSIONS.validate_sessions()
示例#10
0
    def func(self):
        """
        Get all connected players by polling session.
        """

        caller = self.caller
        session_list = SESSIONS.get_sessions()

        if self.cmdstring == "doing":
            show_session_data = False
        else:
            show_session_data = caller.check_permstring("Immortals") or caller.check_permstring("Wizards")

        if show_session_data:
            table = [["Player Name"], ["On for"], ["Idle"], ["Room"], ["Cmds"], ["Host"]]
        else:
            table = [["Player Name"], ["On for"], ["Idle"]]

        for session in session_list:
            if not session.logged_in:
                continue

            delta_cmd = time.time() - session.cmd_last_visible
            delta_conn = time.time() - session.conn_time
            plr_pobject = session.get_character()
            if not plr_pobject:
                plr_pobject = session.get_player()
                show_session_data = False
                table = [["Player Name"], ["On for"], ["Idle"]]
            if show_session_data:
                table[0].append(plr_pobject.name[:25])
                table[1].append(utils.time_format(delta_conn, 0))
                table[2].append(utils.time_format(delta_cmd, 1))
                table[3].append(plr_pobject.location and plr_pobject.location.id or "None")
                table[4].append(session.cmd_total)
                table[5].append(session.address[0])
            else:
                table[0].append(plr_pobject.name[:25])
                table[1].append(utils.time_format(delta_conn,0))
                table[2].append(utils.time_format(delta_cmd,1))

        stable = []
        for row in table: # prettify values
            stable.append([str(val).strip() for val in row])
        ftable = utils.format_table(stable, 5)
        string = ""
        for ir, row in enumerate(ftable):
            if ir == 0:
                string += "\n" + "{w%s{n" % ("".join(row))
            else:
                string += "\n" + "".join(row)
        nplayers = (SESSIONS.player_count())
        if nplayers == 1:
            string += '\nOne player logged in.'
        else:
            string += '\n%d players logged in.' % nplayers

        caller.msg(string)
示例#11
0
文件: system.py 项目: AHecky3/evennia
 def func(self):
     """
     Reload the system.
     """
     reason = ""
     if self.args:
         reason = "(Reason: %s) " % self.args.rstrip(".")
     SESSIONS.announce_all(" Server restarting %s..." % reason)
     SESSIONS.server.shutdown(mode='reload')
示例#12
0
    def func(self):
        "Implementing the function"
        caller = self.caller
        args = self.args

        if not args:
            caller.msg("Usage: @boot[/switches] <player> [:reason]")
            return

        if ':' in args:
            args, reason = [a.strip() for a in args.split(':', 1)]
        else:
            args, reason = args, ""

        boot_list = []

        if 'port' in self.switches:
            # Boot a particular port.
            sessions = SESSIONS.get_session_list(True)
            for sess in sessions:
                # Find the session with the matching port number.
                if sess.getClientAddress()[1] == int(args):
                    boot_list.append(sess)
                    break
        else:
            # Boot by player object
            pobj = search.player_search(args)
            if not pobj:
                self.caller("Player %s was not found." % pobj.key)
                return
            pobj = pobj[0]
            if not pobj.access(caller, 'boot'):
                string = "You don't have the permission to boot %s."
                pobj.msg(string)
                return
            # we have a bootable object with a connected user
            matches = SESSIONS.sessions_from_player(pobj)
            for match in matches:
                boot_list.append(match)

        if not boot_list:
            caller.msg(
                "No matching sessions found. The Player does not seem to be online."
            )
            return

        # Carry out the booting of the sessions in the boot list.

        feedback = None
        if not 'quiet' in self.switches:
            feedback = "You have been disconnected by %s.\n" % caller.name
            if reason:
                feedback += "\nReason given: %s" % reason

        for session in boot_list:
            session.msg(feedback)
            pobj.disconnect_session_from_player(session.sessid)
示例#13
0
 def func(self):
     """
     Reload the system.
     """
     reason = ""
     if self.args:
         reason = "(Reason: %s) " % self.args.rstrip(".")
     SESSIONS.announce_all(" Server restarting %s..." % reason)
     SESSIONS.server.shutdown(mode='reload')
示例#14
0
    def func(self):
        """
        Get all connected players by polling session.
        """

        player = self.player
        session_list = SESSIONS.get_sessions()

        session_list = sorted(session_list, key=lambda o: o.player.key)

        if self.cmdstring == "doing":
            show_session_data = False
        else:
            show_session_data = player.check_permstring("Immortals") or player.check_permstring("Wizards")

        nplayers = (SESSIONS.player_count())
        if show_session_data:
            # privileged info
            table = prettytable.PrettyTable(["{wPlayer Name",
                                             "{wOn for",
                                             "{wIdle",
                                             "{wPuppeting",
                                             "{wRoom",
                                             "{wCmds",
                                             "{wProtocol",
                                             "{wHost"])
            for session in session_list:
                if not session.logged_in: continue
                delta_cmd = time.time() - session.cmd_last_visible
                delta_conn = time.time() - session.conn_time
                player = session.get_player()
                puppet = session.get_puppet()
                location = puppet.location.key if puppet else "None"
                table.add_row([utils.crop(player.name, width=25),
                               utils.time_format(delta_conn, 0),
                               utils.time_format(delta_cmd, 1),
                               utils.crop(puppet.key if puppet else "None", width=25),
                               utils.crop(location, width=25),
                               session.cmd_total,
                               session.protocol_key,
                               isinstance(session.address, tuple) and session.address[0] or session.address])
        else:
            # unprivileged
            table = prettytable.PrettyTable(["{wPlayer name", "{wOn for", "{wIdle"])
            for session in session_list:
                if not session.logged_in:
                    continue
                delta_cmd = time.time() - session.cmd_last_visible
                delta_conn = time.time() - session.conn_time
                player = session.get_player()
                table.add_row([utils.crop(player.key, width=25),
                               utils.time_format(delta_conn, 0),
                               utils.time_format(delta_cmd, 1)])

        isone = nplayers == 1
        string = "{wPlayers:{n\n%s\n%s unique account%s logged in." % (table, "One" if isone else nplayers, "" if isone else "s")
        self.msg(string)
示例#15
0
文件: admin.py 项目: Aumnren/evennia
    def func(self):
        "Implementing the function"
        caller = self.caller
        args = self.args

        if not args:
            caller.msg("Usage: @boot[/switches] <player> [:reason]")
            return

        if ":" in args:
            args, reason = [a.strip() for a in args.split(":", 1)]
        else:
            args, reason = args, ""

        boot_list = []

        if "port" in self.switches:
            # Boot a particular port.
            sessions = SESSIONS.get_session_list(True)
            for sess in sessions:
                # Find the session with the matching port number.
                if sess.getClientAddress()[1] == int(args):
                    boot_list.append(sess)
                    break
        else:
            # Boot by player object
            pobj = search.player_search(args)
            if not pobj:
                self.caller("Player %s was not found." % pobj.key)
                return
            pobj = pobj[0]
            if not pobj.access(caller, "boot"):
                string = "You don't have the permission to boot %s."
                pobj.msg(string)
                return
            # we have a bootable object with a connected user
            matches = SESSIONS.sessions_from_player(pobj)
            for match in matches:
                boot_list.append(match)

        if not boot_list:
            caller.msg("No matching sessions found. The Player does not seem to be online.")
            return

        # Carry out the booting of the sessions in the boot list.

        feedback = None
        if not "quiet" in self.switches:
            feedback = "You have been disconnected by %s.\n" % caller.name
            if reason:
                feedback += "\nReason given: %s" % reason

        for session in boot_list:
            session.msg(feedback)
            pobj.disconnect_session_from_player(session.sessid)
示例#16
0
    def start(
        self,
        ev_channel=None,
        imc2_network=None,
        imc2_mudname=None,
        imc2_port=None,
        imc2_client_pwd=None,
        imc2_server_pwd=None,
    ):
        """
        Start by telling the portal to start a new session
        ev_channel - key of the Evennia channel to connect to
        imc2_network - IMC2 network name
        imc2_mudname - registered mudname (if not given, use settings.SERVERNAME)
        imc2_port - port number of IMC2 network
        imc2_client_pwd - client password registered with IMC2 network
        imc2_server_pwd - server password registered with IMC2 network
        """
        global _SESSIONS
        if not _SESSIONS:
            from src.server.sessionhandler import SESSIONS as _SESSIONS
        if ev_channel:
            # connect to Evennia channel
            channel = search.channel_search(ev_channel)
            if not channel:
                raise RuntimeError("Evennia Channel '%s' not found." % ev_channel)
            channel = channel[0]
            channel.connect(self)
            self.db.ev_channel = channel
        if imc2_network:
            self.db.imc2_network = imc2_network
        if imc2_port:
            self.db.imc2_port = imc2_port
        if imc2_mudname:
            self.db.imc2_mudname = imc2_mudname
        elif not self.db.imc2_mudname:
            self.db.imc2_mudname = settings.SERVERNAME
        # storing imc2 passwords in attributes - a possible
        # security issue?
        if imc2_server_pwd:
            self.db.imc2_server_pwd = imc2_server_pwd
        if imc2_client_pwd:
            self.db.imc2_client_pwd = imc2_client_pwd

        configdict = {
            "uid": self.dbid,
            "mudname": self.db.imc2_mudname,
            "network": self.db.imc2_network,
            "port": self.db.imc2_port,
            "client_pwd": self.db.client_pwd,
            "server_pwd": self.db.server_pwd,
        }

        _SESSIONS.start_bot_session("src.server.portal.imc2.IMC2BotFactory", configdict)
示例#17
0
    def start(self,
              ev_channel=None,
              imc2_network=None,
              imc2_mudname=None,
              imc2_port=None,
              imc2_client_pwd=None,
              imc2_server_pwd=None):
        """
        Start by telling the portal to start a new session
        ev_channel - key of the Evennia channel to connect to
        imc2_network - IMC2 network name
        imc2_mudname - registered mudname (if not given, use settings.SERVERNAME)
        imc2_port - port number of IMC2 network
        imc2_client_pwd - client password registered with IMC2 network
        imc2_server_pwd - server password registered with IMC2 network
        """
        global _SESSIONS
        if not _SESSIONS:
            from src.server.sessionhandler import SESSIONS as _SESSIONS
        if ev_channel:
            # connect to Evennia channel
            channel = search.channel_search(ev_channel)
            if not channel:
                raise RuntimeError("Evennia Channel '%s' not found." %
                                   ev_channel)
            channel = channel[0]
            channel.connect(self)
            self.db.ev_channel = channel
        if imc2_network:
            self.db.imc2_network = imc2_network
        if imc2_port:
            self.db.imc2_port = imc2_port
        if imc2_mudname:
            self.db.imc2_mudname = imc2_mudname
        elif not self.db.imc2_mudname:
            self.db.imc2_mudname = settings.SERVERNAME
        # storing imc2 passwords in attributes - a possible
        # security issue?
        if imc2_server_pwd:
            self.db.imc2_server_pwd = imc2_server_pwd
        if imc2_client_pwd:
            self.db.imc2_client_pwd = imc2_client_pwd

        configdict = {
            "uid": self.dbid,
            "mudname": self.db.imc2_mudname,
            "network": self.db.imc2_network,
            "port": self.db.imc2_port,
            "client_pwd": self.db.client_pwd,
            "server_pwd": self.db.server_pwd
        }

        _SESSIONS.start_bot_session("src.server.portal.imc2.IMC2BotFactory",
                                    configdict)
示例#18
0
    def start(self,
              ev_channel=None,
              irc_botname=None,
              irc_channel=None,
              irc_network=None,
              irc_port=None):
        """
        Start by telling the portal to start a new session.

        ev_channel - key of the Evennia channel to connect to
        irc_botname - name of bot to connect to irc channel. If not set, use self.key
        irc_channel - name of channel on the form #channelname
        irc_network - url of network, like irc.freenode.net
        irc_port - port number of irc network, like 6667
        """
        global _SESSIONS
        if not _SESSIONS:
            from src.server.sessionhandler import SESSIONS as _SESSIONS

        # if keywords are given, store (the BotStarter script
        # will not give any keywords, so this should normally only
        # happen at initialization)
        if irc_botname:
            self.db.irc_botname = irc_botname
        elif not self.db.irc_botname:
            self.db.irc_botname = self.key
        if ev_channel:
            # connect to Evennia channel
            channel = search.channel_search(ev_channel)
            if not channel:
                raise RuntimeError("Evennia Channel '%s' not found." %
                                   ev_channel)
            channel = channel[0]
            channel.connect(self)
            self.db.ev_channel = channel
        if irc_channel:
            self.db.irc_channel = irc_channel
        if irc_network:
            self.db.irc_network = irc_network
        if irc_port:
            self.db.irc_port = irc_port

        # instruct the server and portal to create a new session with
        # the stored configuration
        configdict = {
            "uid": self.dbid,
            "botname": self.db.irc_botname,
            "channel": self.db.irc_channel,
            "network": self.db.irc_network,
            "port": self.db.irc_port
        }
        _SESSIONS.start_bot_session("src.server.portal.irc.IRCBotFactory",
                                    configdict)
示例#19
0
 def func(self):
     "Define function"
     try:
         session = self.caller.sessions[0]
     except Exception:
         return
     self.caller.msg('Shutting down server ...')
     announcement = "\nServer is being SHUT DOWN!\n"
     if self.args:
         announcement += "%s\n" % self.args
     logger.log_infomsg('Server shutdown by %s.' % self.caller.name)
     SESSIONS.announce_all(announcement)
     SESSIONS.portal_shutdown()
     SESSIONS.server.shutdown(mode='shutdown')
示例#20
0
 def func(self):
     switches = [switch.lower() for switch in self.switches]
     character = self.character
     if self.cmdstring.lower() == 'ws':
         if not switches and not self.args:
             if not character:
                 self.msg("{RYou have no location.  (See {rhelp @char{R for more information)")
                 return
             if not character.location:
                 self.msg("{RYou don't seem to have any specific location.")
                 return
             self.display_users([ con for con in character.location.contents if utils.inherits_from(con, "src.objects.objects.Character") ])
             return
     else:
         if (not switches or switches == ['characters']) and not self.args:
             characters = set()
             for session in SESSIONS.get_sessions():
                 character = session.get_character()
                 if character:
                     character = character.typeclass
                     characters.add(character)
             self.display_users(characters)
             return
         if switches == ['players'] and not self.args:
             players = set()
             for session in SESSIONS.get_sessions():
                 player = session.get_player()
                 if player:
                     player = player.typeclass
                     players.add(player)
             self.display_users(players)
             return
         if switches == ['far'] and self.args:
             target = match(self.args)
             if not target:
                 self.msg('%cnNo match found for "' + self.args + "'")
                 return
             self.display_users([target])
             return
         if switches == ['room'] and not self.args:
             if not character:
                 self.msg("{RYou have no location.  (See {rhelp @char{R for more information)")
                 return
             if not character.location:
                 self.msg("{RYou don't seem to have any specific location.")
                 return
             self.display_users([ con for con in character.location.contents if utils.inherits_from(con, "src.objects.objects.Character") ])
             return
     self.msg("Invalid '%s' command.  See 'help %s' for usage" % (self.cmdstring, self.key))
示例#21
0
 def func(self):
     "Define function"
     try:
         # Only allow shutdown if caller has session
         self.caller.sessions[0]
     except Exception:
         return
     self.msg("Shutting down server ...")
     announcement = "\nServer is being SHUT DOWN!\n"
     if self.args:
         announcement += "%s\n" % self.args
     logger.log_infomsg("Server shutdown by %s." % self.caller.name)
     SESSIONS.announce_all(announcement)
     SESSIONS.portal_shutdown()
     SESSIONS.server.shutdown(mode="shutdown")
示例#22
0
 def func(self):
     "Define function"
     try:
         # Only allow shutdown if caller has session
         self.caller.sessions[0]
     except Exception:
         return
     self.msg('Shutting down server ...')
     announcement = "\nServer is being SHUT DOWN!\n"
     if self.args:
         announcement += "%s\n" % self.args
     logger.log_infomsg('Server shutdown by %s.' % self.caller.name)
     SESSIONS.announce_all(announcement)
     SESSIONS.portal_shutdown()
     SESSIONS.server.shutdown(mode='shutdown')
示例#23
0
 def func(self):
     player = self.player
     character = self.character
     # Check arguments
     message = self.args
     if not message:
         self.msg("{R[Invalid '{r%s{R' command.  See '{rhelp %s{R' for usage]" % (self.cmdstring, self.key))
         return
     # Format the message
     if character:
         # If we have a character, then we can use the 'say' routines to format the message.
         if message.startswith(':'):
             message = character.speech_pose(message[1:])
         elif message.startswith('"'):
             message = character.speech_say(message[1:])
         else:
             message = character.speech_say(message)
     else:
         # If we have no character, we'll have to take care of the formatting
         if message.startswith(':'):
             message = '{b' + player.key + '{n ' + message[1:].replace('{', '{{').replace('%', '%%')
         elif message.startswith('"'):
             message = '{b' + player.key + '{n: ' + message[1:].replace('{', '{{').replace('%', '%%')
         else:
             message = '{b' + player.key + '{n: ' + message.replace('{', '{{').replace('%', '%%')
     message = "{Y[ {cShout {Y| {n%s {Y]" % (message)
     # Send it
     for session in SESSIONS.get_sessions():
         session_sessid = session.sessid
         session_player = session.get_player()
         if not session_player:
             continue
         session_player.msg(message, sessid=session_sessid)
示例#24
0
文件: models.py 项目: Aumnren/evennia
    def msg(self, text=None, from_obj=None, sessid=0, **kwargs):
        """
        Emits something to a session attached to the object.

        message (str): The message to send
        from_obj (obj): object that is sending.
        data (object): an optional data object that may or may not
                       be used by the protocol.
        sessid (int): sessid to relay to, if any.
                      If set to 0 (default), use either from_obj.sessid (if set) or self.sessid automatically
                      If None, echo to all connected sessions
        """
        global _SESSIONS
        if not _SESSIONS:
            from src.server.sessionhandler import SESSIONS as _SESSIONS

        text = to_str(text, force_string=True) if text else ""

        if "data" in kwargs:
            # deprecation warning
            logger.log_depmsg("ObjectDB.msg(): 'data'-dict keyword is deprecated. Use **kwargs instead.")
            data = kwargs.pop("data")
            if isinstance(data, dict):
                kwargs.update(data)

        if from_obj:
            # call hook
            try:
                _GA(from_obj, "at_msg_send")(text=text, to_obj=self, **kwargs)
            except Exception:
                pass

        session = _SESSIONS.session_from_sessid(sessid if sessid else _GA(self, "sessid"))
        if session:
            session.msg(text=text, **kwargs)
示例#25
0
 def at_repeat(self):
     """
     Calls subscriptions every self.interval seconds
     """
     for (func_key, sessid, interval, args, kwargs) in self.ndb.subscriptions.values():
         session = SESSIONS.session_from_sessid(sessid)
         OOB_HANDLER.execute_cmd(session, func_key, *args, **kwargs)
示例#26
0
    def get_all_connections(self, channel, online=False):
        """
        Return the connections of all players listening
        to this channel. If Online is true, it only returns
        connected players.
        """
        global _SESSIONS
        if not _SESSIONS:
            from src.server.sessionhandler import SESSIONS as _SESSIONS

        PlayerChannelConnection = ContentType.objects.get(app_label="comms",
                                                          model="playerchannelconnection").model_class()
        ExternalChannelConnection = ContentType.objects.get(app_label="comms",
                                                            model="externalchannelconnection").model_class()
        players = []
        if online:
            session_list = _SESSIONS.get_sessions()
            unique_online_users = set(sess.uid for sess in session_list if sess.logged_in)
            online_players = (sess.get_player() for sess in session_list if sess.uid in unique_online_users)
            for player in online_players:
                players.extend(PlayerChannelConnection.objects.filter(
                    db_player=player.dbobj, db_channel=channel.dbobj))
        else:
            players.extend(PlayerChannelConnection.objects.get_all_connections(channel))

        external_connections = ExternalChannelConnection.objects.get_all_connections(channel)

        return itertools.chain(players, external_connections)
示例#27
0
    def func(self):
        """
        Contructs the desired loop based on switches.
        """
        construction = [ self.get_name, self.get_online_time, self.get_idle_time, self.get_status, self.get_location ]
        self.switches = [ switch.lower() for switch in self.switches ]
        if not getattr(self.caller, 'locks', None) or not \
            ('wiz' in self.switches and self.caller.locks.check_lockstring(self.caller, 'admin:perm(Immortals)')):
            self.admin = False # This is a session, not a player.
            construction.append(self.get_doing)
        else:
            construction.append(self.get_host)
            self.admin = True
        header = ''
        separator = ' '
        for function in construction:
             header += '%s%s{n' % (function.color, function.title)
             padding = function.spacing - len(function.title)
             header += separator * padding

        self.caller.msg(header)

        users = [ [session, ''] for session in SESSIONS.get_sessions() if check_ignores(self.caller, [session.get_character()], silent=True) ]

        if not self.admin:
            users = [ user for user in users if user[Who.SESSION].get_character() ]

        for user in users:
             for function in construction:
                 user[Who.STRING] += function.color + "%%-%ss" % function.spacing % function(user[Who.SESSION]) + '{n'
             self.caller.msg(user[Who.STRING])
示例#28
0
    def start(self, ev_channel=None, irc_botname=None, irc_channel=None, irc_network=None, irc_port=None):
        """
        Start by telling the portal to start a new session.

        ev_channel - key of the Evennia channel to connect to
        irc_botname - name of bot to connect to irc channel. If not set, use self.key
        irc_channel - name of channel on the form #channelname
        irc_network - url of network, like irc.freenode.net
        irc_port - port number of irc network, like 6667
        """
        global _SESSIONS
        if not _SESSIONS:
            from src.server.sessionhandler import SESSIONS as _SESSIONS

        # if keywords are given, store (the BotStarter script
        # will not give any keywords, so this should normally only
        # happen at initialization)
        if irc_botname:
            self.db.irc_botname = irc_botname
        elif not self.db.irc_botname:
            self.db.irc_botname = self.key
        if ev_channel:
            # connect to Evennia channel
            channel = search.channel_search(ev_channel)
            if not channel:
                raise RuntimeError("Evennia Channel '%s' not found." % ev_channel)
            channel = channel[0]
            channel.connect(self)
            self.db.ev_channel = channel
        if irc_channel:
            self.db.irc_channel = irc_channel
        if irc_network:
            self.db.irc_network = irc_network
        if irc_port:
            self.db.irc_port = irc_port

        # instruct the server and portal to create a new session with
        # the stored configuration
        configdict = {
            "uid": self.dbid,
            "botname": self.db.irc_botname,
            "channel": self.db.irc_channel,
            "network": self.db.irc_network,
            "port": self.db.irc_port,
        }
        _SESSIONS.start_bot_session("src.server.portal.irc.IRCBotFactory", configdict)
示例#29
0
文件: models.py 项目: Aumnren/evennia
 def get_session(self, sessid):
     """
     Return session with given sessid connected to this player.
     """
     global _SESSIONS
     if not _SESSIONS:
         from src.server.sessionhandler import SESSIONS as _SESSIONS
     return _SESSIONS.session_from_player(self, sessid)
示例#30
0
 def get_session(self, sessid):
     """
     Return session with given sessid connected to this player.
     """
     global _SESSIONS
     if not _SESSIONS:
         from src.server.sessionhandler import SESSIONS as _SESSIONS
     return _SESSIONS.session_from_player(self, sessid)
示例#31
0
 def get_session(self, sessid):
     """
     Return session with given sessid connected to this player.
     note that the sessionhandler also accepts sessid as an iterable.
     """
     global _SESSIONS
     if not _SESSIONS:
         from src.server.sessionhandler import SESSIONS as _SESSIONS
     return _SESSIONS.session_from_player(self, sessid)
示例#32
0
def webclient(request):
    """
    Webclient page template loading. 
    """
    # as an example we send the number of connected players to the template
    pagevars = {'num_players_connected': SESSIONS.player_count()}

    context_instance = RequestContext(request)
    return render_to_response('webclient.html', pagevars, context_instance)
示例#33
0
 def get_session(self, sessid):
     """
     Return session with given sessid connected to this player.
     note that the sessionhandler also accepts sessid as an iterable.
     """
     global _SESSIONS
     if not _SESSIONS:
         from src.server.sessionhandler import SESSIONS as _SESSIONS
     return _SESSIONS.session_from_player(self, sessid)
示例#34
0
def webclient(request):
    """
    Webclient page template loading. 
    """    
    # as an example we send the number of connected players to the template
    pagevars = {'num_players_connected': SESSIONS.player_count()}

    context_instance = RequestContext(request)
    return render_to_response('webclient.html', pagevars, context_instance)
示例#35
0
 def _callback(self):
     "See original for more info"
     for key, (_, args, kwargs) in self.subscriptions.items():
         # args = (sessid, callback_function)
         session = SESSIONS.session_from_sessid(args[0])
         try:
             # execute the oob callback
             yield args[1](OOB_HANDLER, session, *args[2:], **kwargs)
         except Exception:
             logger.log_trace()
示例#36
0
 def _callback(self):
     "See original for more info"
     for key, (_, args, kwargs) in self.subscriptions.items():
         # args = (sessid, callback_function)
         session = SESSIONS.session_from_sessid(args[0])
         try:
             # execute the oob callback
             yield args[1](OOB_HANDLER, session, *args[2:], **kwargs)
         except Exception:
             logger.log_trace()
示例#37
0
 def func(self):
     if self.args and self.args.isdigit():
         self.show_whereare(int(self.args))
     elif not self.args and not self.switches:
         # Default threshold is 5% of the server's population
         characters = 0
         for session in SESSIONS.get_sessions():
             if session.get_character():
                 characters += 1
         self.show_whereare(characters / 20)
     else:
         self.msg("{R[Invalid '{r%s{R' command.  See '{rhelp %s{R' for usage]" % (self.cmdstring, self.key))
示例#38
0
文件: bots.py 项目: AHecky3/evennia
 def at_repeat(self):
     """
     Called self.interval seconds to keep connection. We cannot use
     the IDLE command from inside the game since the system will
     not catch it (commands executed from the server side usually
     has no sessions). So we update the idle counter manually here
     instead. This keeps the bot getting hit by IDLE_TIMEOUT.
     """
     global _SESSIONS
     if not _SESSIONS:
         from src.server.sessionhandler import SESSIONS as _SESSIONS
     for session in _SESSIONS.sessions_from_player(self.player):
         session.update_session_counters(idle=True)
示例#39
0
 def at_repeat(self):
     """
     Called self.interval seconds to keep connection. We cannot use
     the IDLE command from inside the game since the system will
     not catch it (commands executed from the server side usually
     has no sessions). So we update the idle counter manually here
     instead. This keeps the bot getting hit by IDLE_TIMEOUT.
     """
     global _SESSIONS
     if not _SESSIONS:
         from src.server.sessionhandler import SESSIONS as _SESSIONS
     for session in _SESSIONS.sessions_from_player(self.player):
         session.update_session_counters(idle=True)
示例#40
0
    def msg(self, text=None, from_obj=None, sessid=0, **kwargs):
        """
        Emits something to a session attached to the object.

        message (str): The message to send
        from_obj (obj): object that is sending.
        data (object): an optional data object that may or may not
                       be used by the protocol.
        sessid (int): sessid to relay to, if any.
                      If set to 0 (default), use either from_obj.sessid (if set) or self.sessid automatically
                      If None, echo to all connected sessions

        When this message is called, from_obj.at_msg_send and self.at_msg_receive are called.

        """
        global _SESSIONS
        if not _SESSIONS:
            from src.server.sessionhandler import SESSIONS as _SESSIONS

        text = to_str(text, force_string=True) if text else ""

        if "data" in kwargs:
            # deprecation warning
            logger.log_depmsg(
                "ObjectDB.msg(): 'data'-dict keyword is deprecated. Use **kwargs instead."
            )
            data = kwargs.pop("data")
            if isinstance(data, dict):
                kwargs.update(data)

        if from_obj:
            # call hook
            try:
                _GA(from_obj, "at_msg_send")(text=text,
                                             to_obj=_GA(self, "typeclass"),
                                             **kwargs)
            except Exception:
                logger.log_trace()
        try:
            if not _GA(_GA(self, "typeclass"), "at_msg_receive")(text=text,
                                                                 **kwargs):
                # if at_msg_receive returns false, we abort message to this object
                return
        except Exception:
            logger.log_trace()

        sessions = _SESSIONS.session_from_sessid(
            [sessid] if sessid else make_iter(_GA(self, "sessid").get()))
        for session in sessions:
            session.msg(text=text, **kwargs)
示例#41
0
def webclient(request):
    """
    Webclient page template loading.
    """

    # analyze request to find which port we are on
    if int(request.META["SERVER_PORT"]) == 8000:
        # we relay webclient to the portal port
        print "Called from port 8000!"
        #return redirect("http://localhost:8001/webclient/", permanent=True)

    # as an example we send the number of connected players to the template
    pagevars = {'num_players_connected': SESSIONS.player_count()}

    context_instance = RequestContext(request)
    return render_to_response('webclient.html', pagevars, context_instance)
示例#42
0
文件: views.py 项目: Aumnren/evennia
def webclient(request):
    """
    Webclient page template loading.
    """

    # analyze request to find which port we are on
    if int(request.META["SERVER_PORT"]) == 8000:
        # we relay webclient to the portal port
        print "Called from port 8000!"
        # return redirect("http://localhost:8001/webclient/", permanent=True)

    # as an example we send the number of connected players to the template
    pagevars = {"num_players_connected": SESSIONS.player_count()}

    context_instance = RequestContext(request)
    return render_to_response("webclient.html", pagevars, context_instance)
示例#43
0
 def call(self,
          cmdobj,
          args,
          msg=None,
          cmdset=None,
          noansi=True,
          caller=None):
     """
     Test a command by assigning all the needed
     properties to cmdobj and  running
         cmdobj.at_pre_cmd()
         cmdobj.parse()
         cmdobj.func()
         cmdobj.at_post_cmd()
     The msgreturn value is compared to eventual
     output sent to caller.msg in the game
     """
     cmdobj.caller = caller if caller else self.char1
     #print "call:", cmdobj.key, cmdobj.caller, caller if caller else cmdobj.caller.player
     #print "perms:", cmdobj.caller.permissions.all()
     cmdobj.cmdstring = cmdobj.key
     cmdobj.args = args
     cmdobj.cmdset = cmdset
     cmdobj.sessid = self.CID
     cmdobj.session = SESSIONS.session_from_sessid(self.CID)
     cmdobj.player = self.player
     cmdobj.raw_string = cmdobj.key + " " + args
     cmdobj.obj = caller if caller else self.char1
     # test
     self.char1.player.ndb.stored_msg = []
     cmdobj.at_pre_cmd()
     cmdobj.parse()
     cmdobj.func()
     cmdobj.at_post_cmd()
     # clean out prettytable sugar
     stored_msg = self.char1.player.ndb.stored_msg if self.char1.player else self.char1.ndb.stored_msg
     returned_msg = "|".join(_RE.sub("", mess) for mess in stored_msg)
     #returned_msg = "|".join(self.char1.player.ndb.stored_msg)
     returned_msg = ansi.parse_ansi(returned_msg, strip_ansi=noansi).strip()
     if msg != None:
         if msg == "" and returned_msg or not returned_msg.startswith(
                 msg.strip()):
             sep1 = "\n" + "=" * 30 + "Wanted message" + "=" * 34 + "\n"
             sep2 = "\n" + "=" * 30 + "Returned message" + "=" * 32 + "\n"
             sep3 = "\n" + "=" * 78
             retval = sep1 + msg.strip() + sep2 + returned_msg + sep3
             raise AssertionError(retval)
示例#44
0
    def merge_players(self, to_player, from_player):
        self.msg('Merging "%s" into "%s"...' % (from_player, to_player))
        self.msg('  Disconnecting %s (if applicable)...' % (from_player))
        from_player.unpuppet_all()
        for session in SESSIONS.sessions_from_player(from_player):
            from_player.msg('\nYour account has been merged into "%s".\n' % (to_player), sessid=session.sessid)
            from_player.disconnect_session_from_player(session.sessid)
        self.msg('  Transfering characters...')
        transfer_characters = from_player.get_characters()
        if transfer_characters:
            for character in transfer_characters:
                character.set_owner(to_player)
                character.locks.add("puppet:id(%i) or pid(%i) or perm(Janitors)" % (character.id, to_player.id))
                self.msg('    %s' % (character.key))
        else:
            self.msg('    No characters.')
        self.msg('  Transfering friends...')
        if from_player.db.friends_list:
            for friend in from_player.db.friends_list:
                if friend == to_player:
                    # Your other account is friends with you?
                    continue
                self.msg('      ' + friend.key)
                to_player.db.friends_list.add(friend)
        self.msg('  Transfering outstanding friend requests...')
        if from_player.db.friends_requests:
            for request_player in from_player.db.friends_requests:
                if request_player == to_player:
                    # Your other account sent you a friend request?
                    continue
                self.msg('      ' + request_player.key)
                to_player.db.friends_requests.add(request_player)
                # Alter this requesting player's friend roster if needed
                if from_player in request_player.db.friends_list:
                    request_player.db.friends_list.remove(from_player)
                    request_player.db.friends_list.add(to_player)
        self.msg('  Transfering bonuses...')
        if from_player.db.bonus_lat1:
            self.msg('    lat1')
            to_player.db.bonus_lat1 = True
        self.msg('  Deleting "%s"...' % (from_player))
#        from_player.user.delete()
        from_player.delete()
        self.msg('Merge from "%s" to "%s" complete.' % (from_player, to_player))
示例#45
0
    def msg(self, text=None, from_obj=None, sessid=0, **kwargs):
        """
        Emits something to a session attached to the object.

        message (str): The message to send
        from_obj (obj): object that is sending.
        data (object): an optional data object that may or may not
                       be used by the protocol.
        sessid (int): sessid to relay to, if any.
                      If set to 0 (default), use either from_obj.sessid (if set) or self.sessid automatically
                      If None, echo to all connected sessions

        When this message is called, from_obj.at_msg_send and self.at_msg_receive are called.

        """
        global _SESSIONS
        if not _SESSIONS:
            from src.server.sessionhandler import SESSIONS as _SESSIONS

        text = to_str(text, force_string=True) if text else ""

        if "data" in kwargs:
            # deprecation warning
            logger.log_depmsg("ObjectDB.msg(): 'data'-dict keyword is deprecated. Use **kwargs instead.")
            data = kwargs.pop("data")
            if isinstance(data, dict):
                kwargs.update(data)

        if from_obj:
            # call hook
            try:
                _GA(from_obj, "at_msg_send")(text=text, to_obj=_GA(self, "typeclass"), **kwargs)
            except Exception:
                logger.log_trace()
        try:
            if not _GA(_GA(self, "typeclass"), "at_msg_receive")(text=text, **kwargs):
                # if at_msg_receive returns false, we abort message to this object
                return
        except Exception:
            logger.log_trace()

        sessions = _SESSIONS.session_from_sessid([sessid] if sessid else make_iter(_GA(self, "sessid").get()))
        for session in sessions:
            session.msg(text=text, **kwargs)
示例#46
0
    def func(self):
        """
        Contructs the desired loop based on switches.
        """
        construction = [
            self.get_name, self.get_online_time, self.get_idle_time,
            self.get_status, self.get_location
        ]
        self.switches = [switch.lower() for switch in self.switches]
        if not getattr(self.caller, 'locks', None) or not \
            ('wiz' in self.switches and self.caller.locks.check_lockstring(self.caller, 'admin:perm(Immortals)')):
            self.admin = False  # This is a session, not a player.
            construction.append(self.get_doing)
        else:
            construction.append(self.get_host)
            self.admin = True
        header = ''
        separator = ' '
        for function in construction:
            header += '%s%s{n' % (function.color, function.title)
            padding = function.spacing - len(function.title)
            header += separator * padding

        self.caller.msg(header)

        users = [[session, ''] for session in SESSIONS.get_sessions()
                 if check_ignores(self.caller, [session.get_character()],
                                  silent=True)]

        if not self.admin:
            users = [
                user for user in users if user[Who.SESSION].get_character()
            ]

        for user in users:
            for function in construction:
                user[
                    Who.
                    STRING] += function.color + "%%-%ss" % function.spacing % function(
                        user[Who.SESSION]) + '{n'
            self.caller.msg(user[Who.STRING])
示例#47
0
文件: tests.py 项目: Zurriel/evennia
 def call(self, cmdobj, args, msg=None, cmdset=None, noansi=True, caller=None):
     """
     Test a command by assigning all the needed
     properties to cmdobj and  running
         cmdobj.at_pre_cmd()
         cmdobj.parse()
         cmdobj.func()
         cmdobj.at_post_cmd()
     The msgreturn value is compared to eventual
     output sent to caller.msg in the game
     """
     cmdobj.caller = caller if caller else self.char1
     # print "call:", cmdobj.key, cmdobj.caller, caller if caller else cmdobj.caller.player
     # print "perms:", cmdobj.caller.permissions.all()
     cmdobj.cmdstring = cmdobj.key
     cmdobj.args = args
     cmdobj.cmdset = cmdset
     cmdobj.sessid = self.CID
     cmdobj.session = SESSIONS.session_from_sessid(self.CID)
     cmdobj.player = self.player
     cmdobj.raw_string = cmdobj.key + " " + args
     cmdobj.obj = caller if caller else self.char1
     # test
     self.char1.player.ndb.stored_msg = []
     cmdobj.at_pre_cmd()
     cmdobj.parse()
     cmdobj.func()
     cmdobj.at_post_cmd()
     # clean out prettytable sugar
     stored_msg = self.char1.player.ndb.stored_msg if self.char1.player else self.char1.ndb.stored_msg
     returned_msg = "|".join(_RE.sub("", mess) for mess in stored_msg)
     # returned_msg = "|".join(self.char1.player.ndb.stored_msg)
     returned_msg = ansi.parse_ansi(returned_msg, strip_ansi=noansi).strip()
     if msg != None:
         if msg == "" and returned_msg or not returned_msg.startswith(msg.strip()):
             sep1 = "\n" + "=" * 30 + "Wanted message" + "=" * 34 + "\n"
             sep2 = "\n" + "=" * 30 + "Returned message" + "=" * 32 + "\n"
             sep3 = "\n" + "=" * 78
             retval = sep1 + msg.strip() + sep2 + returned_msg + sep3
             raise AssertionError(retval)
示例#48
0
 def func(self):
     char_num = 0
     output = "{x________________{W_______________{w_______________{W_______________{x_________________\n"
     output += '%cnName         OnTime Idle  Name         OnTime Idle  Name         Ontime Idle\n'
     output += '\n'
     for session in SESSIONS.get_sessions():
         character = session.get_character()
         if not character:
             continue
         char_num += 1
         name = character.key
         onseconds = int(character.status_online())
         onminutes = onseconds / 60
         ontime = '%02d:%02d' % (onminutes / 60, onminutes % 60)
         idletime = self.tdelta_string(int(character.status_idle()))
         output += '%-12s %6s %-5s ' % (name[:12], ontime[:6], idletime[:5])
         if char_num and char_num % 3 == 0:
             output += '\n'
     if not output.endswith('\n'):
         output += '\n'
     output += "{x________________{W_______________{w_______________{W_______________{x_________________\n"
     self.msg(output.rstrip('\n'))
示例#49
0
 def get_all_sessions(self):
     "Return all sessions connected to this player"
     global _SESSIONS
     if not _SESSIONS:
         from src.server.sessionhandler import SESSIONS as _SESSIONS
     return _SESSIONS.sessions_from_player(self)
示例#50
0
 def func(self):
     """
     Reload the system.
     """
     SESSIONS.announce_all(" Server resetting/restarting ...")
     SESSIONS.server.shutdown(mode='reset')
示例#51
0
文件: models.py 项目: Aumnren/evennia
 def get_all_sessions(self):
     "Return all sessions connected to this player"
     global _SESSIONS
     if not _SESSIONS:
         from src.server.sessionhandler import SESSIONS as _SESSIONS
     return _SESSIONS.sessions_from_player(self)