Exemplo n.º 1
0
    def func(self):
        "Implement the command"

        caller = self.caller

        if self.args and self.args.isdigit():
            nlim = int(self.args)
        else:
            nlim = 10

        string = "\n{wDatabase totals:{n"

        nplayers = PlayerDB.objects.count()
        nobjs = ObjectDB.objects.count()
        base_char_typeclass = settings.BASE_CHARACTER_TYPECLASS
        nchars = ObjectDB.objects.filter(db_typeclass_path=base_char_typeclass).count()
        nrooms = ObjectDB.objects.filter(db_location__isnull=True).exclude(db_typeclass_path=base_char_typeclass).count()
        nexits = ObjectDB.objects.filter(db_location__isnull=False, db_destination__isnull=False).count()

        string += "\n{wPlayers:{n %i" % nplayers
        string += "\n{wObjects:{n %i" % nobjs
        string += "\n{w Characters (BASE_CHARACTER_TYPECLASS):{n %i" % nchars
        string += "\n{w Rooms (location==None):{n %i" % nrooms
        string += "\n{w Exits (destination!=None):{n %i" % nexits
        string += "\n{w Other:{n %i\n" % (nobjs - nchars - nrooms - nexits)

        dbtotals = ObjectDB.objects.object_totals()
        table = [["Count"], ["Typeclass"]]
        for path, count in dbtotals.items():
            table[0].append(count)
            table[1].append(path)
        ftable = utils.format_table(table, 3)
        for irow, row in enumerate(ftable):
            srow = "\n" + "".join(row)
            srow = srow.rstrip()
            if irow == 0:
                srow = "{w%s{n" % srow
            string += srow

        string += "\n\n{wLast %s Objects created:{n" % min(nobjs, nlim)
        objs = ObjectDB.objects.all().order_by("db_date_created")[max(0, nobjs - nlim):]

        table = [["Created"], ["dbref"], ["name"], ["typeclass"]]
        for i, obj in enumerate(objs):
            table[0].append(utils.datetime_format(obj.date_created))
            table[1].append(obj.dbref)
            table[2].append(obj.key)
            table[3].append(str(obj.typeclass.path))
        ftable = utils.format_table(table, 5)
        for irow, row in enumerate(ftable):
            srow = "\n" + "".join(row)
            srow = srow.rstrip()
            if irow == 0:
                srow = "{w%s{n" % srow
            string += srow

        caller.msg(string)
Exemplo n.º 2
0
    def func(self):
        "Implement function"

        caller = self.caller

        # all channels we have available to listen to
        channels = [chan for chan in Channel.objects.get_all_channels() if chan.access(caller, 'listen')]
        if not channels:
            caller.msg("No channels available.")
            return
        # all channel we are already subscribed to
        subs = [conn.channel for conn in PlayerChannelConnection.objects.get_all_player_connections(caller)]

        if self.cmdstring != "comlist":

            string = "\nChannels available:"
            cols = [[" "], ["Channel"], ["Aliases"], ["Perms"], ["Description"]]
            for chan in channels:
                if chan in subs:
                    cols[0].append(">")
                else:
                    cols[0].append(" ")
                cols[1].append(chan.key)
                cols[2].append(",".join(chan.aliases))
                cols[3].append(str(chan.locks))
                cols[4].append(chan.desc)
            # put into table
            for ir, row in enumerate(utils.format_table(cols)):
                if ir == 0:
                    string += "\n{w" + "".join(row) + "{n"
                else:
                    string += "\n" + "".join(row)
            self.caller.msg(string)

        string = "\nChannel subscriptions:"
        if not subs:
            string += "(None)"
        else:
            nicks = [nick for nick in caller.nicks.get(nick_type="channel")]
            cols = [[" "], ["Channel"], ["Aliases"], ["Description"]]
            for chan in subs:
                cols[0].append(" ")
                cols[1].append(chan.key)
                cols[2].append(",".join([nick.db_nick for nick in nicks
                                         if nick.db_real.lower() == chan.key.lower()] + chan.aliases))
                cols[3].append(chan.desc)
            # put into table
            for ir, row in enumerate(utils.format_table(cols)):
                if ir == 0:
                    string += "\n{w" + "".join(row) + "{n"
                else:
                    string += "\n" + "".join(row)
        caller.msg(string)
Exemplo n.º 3
0
    def func(self):
        "Show times."

        table = [["Current server uptime:",
                  "Total server running time:",
                  "Total in-game time (realtime x %g):" % (gametime.TIMEFACTOR),
                  "Server time stamp:"
                  ],
                 [utils.time_format(time.time() - SESSIONS.server.start_time, 3),
                  utils.time_format(gametime.runtime(format=False), 2),
                  utils.time_format(gametime.gametime(format=False), 2),
                  datetime.datetime.now()
                  ]]
        if utils.host_os_is('posix'):
            loadavg = os.getloadavg()
            table[0].append("Server load (per minute):")
            table[1].append("%g" % (loadavg[0]))
        stable = []
        for col in table:
            stable.append([str(val).strip() for val in col])
        ftable = utils.format_table(stable, 5)
        string = ""
        for row in ftable:
            string += "\n " + "{w%s{n" % row[0] + "".join(row[1:])
        self.caller.msg(string)
Exemplo n.º 4
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)
Exemplo n.º 5
0
    def func(self):
        "Setup the rss-channel mapping"

        if not settings.RSS_ENABLED:
            string = """RSS is not enabled. You need to activate it in game/settings.py."""
            self.caller.msg(string)
            return

        if 'list' in self.switches:
            # show all connections
            connections = ExternalChannelConnection.objects.filter(db_external_key__startswith='rss_')
            if connections:
                cols = [["Evennia-channel"], ["RSS-url"]]
                for conn in connections:
                    cols[0].append(conn.channel.key)
                    cols[1].append(conn.external_config.split('|')[0])
                ftable = utils.format_table(cols)
                string = ""
                for ir, row in enumerate(ftable):
                    if ir == 0:
                        string += "{w%s{n" % "".join(row)
                    else:
                        string += "\n" + "".join(row)
                self.caller.msg(string)
            else:
                self.caller.msg("No connections found.")
            return

        if not self.args or not self.rhs:
            string = "Usage: @rss2chan[/switches] <evennia_channel> = <rss url>"
            self.caller.msg(string)
            return
        channel = self.lhs
        url = self.rhs

        if 'disconnect' in self.switches or 'remove' in self.switches or 'delete' in self.switches:
            chanmatch = find_channel(self.caller, channel, silent=True)
            if chanmatch:
                channel = chanmatch.key

            ok = rss.delete_connection(channel, url)
            if not ok:
                self.caller.msg("RSS connection/reader could not be removed, does it exist?")
            else:
                self.caller.msg("RSS connection destroyed.")
            return

        channel = find_channel(self.caller, channel)
        if not channel:
            return
        interval = settings.RSS_UPDATE_INTERVAL
        if not interval:
            interval = 10*60
        ok = rss.create_connection(channel, url, interval)
        if not ok:
            self.caller.msg("This RSS connection already exists.")
            return
        self.caller.msg("Connection created. Starting RSS reader.")
Exemplo n.º 6
0
    def func(self):
        "Setup the imc-channel mapping"

        if not settings.IMC2_ENABLED:
            string = """IMC is not enabled. You need to activate it in game/settings.py."""
            self.caller.msg(string)
            return

        if 'list' in self.switches:
            # show all connections
            connections = ExternalChannelConnection.objects.filter(db_external_key__startswith='imc2_')
            if connections:
                cols = [["Evennia channel"], ["<->"], ["IMC channel"]]
                for conn in connections:
                    cols[0].append(conn.channel.key)
                    cols[1].append("")
                    cols[2].append(conn.external_config)
                ftable = utils.format_table(cols)
                string = ""
                for ir, row in enumerate(ftable):
                    if ir == 0:
                        string += "{w%s{n" % "".join(row)
                    else:
                        string += "\n" + "".join(row)
                self.caller.msg(string)
            else:
                self.caller.msg("No connections found.")
            return

        if not self.args or not self.rhs:
            string = "Usage: @imc2chan[/switches] <evennia_channel> = <imc2_channel>"
            self.caller.msg(string)
            return

        channel = self.lhs
        imc2_channel = self.rhs

        if 'disconnect' in self.switches or 'remove' in self.switches or 'delete' in self.switches:
            # we don't search for channels before this since we want to clear the link
            # also if the channel no longer exists.
            ok = imc2.delete_connection(channel, imc2_channel)
            if not ok:
                self.caller.msg("IMC2 connection could not be removed, does it exist?")
            else:
                self.caller.msg("IMC2 connection destroyed.")
            return

        # actually get the channel object
        channel = find_channel(self.caller, channel)
        if not channel:
            return

        ok = imc2.create_connection(channel, imc2_channel)
        if not ok:
            self.caller.msg("The connection %s <-> %s  already exists." % (channel.key, imc2_channel))
            return
        self.caller.msg("Created connection channel %s <-> IMC channel %s." % (channel.key, imc2_channel))
Exemplo n.º 7
0
    def func(self):
        "Create the nickname"

        caller = self.caller
        switches = self.switches

        nicks = Nick.objects.filter(db_obj=caller.dbobj).exclude(db_type="channel")
        if 'list' in switches:
            string = "{wDefined Nicks:{n"
            cols = [["Type"],["Nickname"],["Translates-to"] ]
            for nick in nicks:
                cols[0].append(nick.db_type)
                cols[1].append(nick.db_nick)
                cols[2].append(nick.db_real)
            for ir, row in enumerate(utils.format_table(cols)):
                if ir == 0:
                    string += "\n{w" + "".join(row) + "{n"
                else:
                    string += "\n" + "".join(row)
            caller.msg(string)
            return
        if 'clearall' in switches:
            nicks.delete()
            caller.msg("Cleared all aliases.")
            return
        if not self.args or not self.lhs:
            caller.msg("Usage: nick[/switches] nickname = [realname]")
            return
        nick = self.lhs
        real = self.rhs

        if real == nick:
            caller.msg("No point in setting nick same as the string to replace...")
            return

        # check so we have a suitable nick type
        if not any(True for switch in switches if switch in ("object", "player", "inputline")):
            switches = ["inputline"]
        string = ""
        for switch in switches:
            oldnick = Nick.objects.filter(db_obj=caller.dbobj, db_nick__iexact=nick, db_type__iexact=switch)
            if not real:
                # removal of nick
                if oldnick:
                    # clear the alias
                    string += "\nNick '%s' (= '%s') was cleared." % (nick, oldnick[0].db_real)
                    caller.nicks.delete(nick, nick_type=switch)
                else:
                    string += "\nNo nick '%s' found, so it could not be removed." % nick
            else:
                # creating new nick
                if oldnick:
                    string += "\nNick %s changed from '%s' to '%s'." % (nick, oldnick[0].db_real, real)
                else:
                    string += "\nNick set: '%s' = '%s'." % (nick, real)
                caller.nicks.add(nick, real, nick_type=switch)
        caller.msg(string)
Exemplo n.º 8
0
    def func(self):
        "Show color tables"

        if not self.args or not self.args in ("ansi", "xterm256"):
            self.caller.msg("Usage: @color ansi|xterm256")
            return

        if self.args == "ansi":
            from src.utils import ansi

            ap = ansi.ANSI_PARSER
            # ansi colors
            # show all ansi color-related codes
            col1 = ["%s%s{n" % (code, code.replace("{", "{{")) for code, _ in ap.ext_ansi_map[:-1]]
            hi = "%ch"
            col2 = ["%s%s{n" % (code, code.replace("%", "%%")) for code, _ in ap.mux_ansi_map[:-2]]
            col3 = ["%s%s{n" % (hi + code, (hi + code).replace("%", "%%")) for code, _ in ap.mux_ansi_map[:-2]]
            table = utils.format_table([col1, col2, col3], extra_space=1)
            string = "ANSI colors:"
            for row in table:
                string += "\n" + "".join(row)
            print string
            self.caller.msg(string)
            self.caller.msg("{{X and %%cx are black-on-black)")
        elif self.args == "xterm256":
            table = [[], [], [], [], [], [], [], [], [], [], [], []]
            for ir in range(6):
                for ig in range(6):
                    for ib in range(6):
                        # foreground table
                        table[ir].append("%%c%i%i%i%s{n" % (ir, ig, ib, "{{%i%i%i" % (ir, ig, ib)))
                        # background table
                        table[6 + ir].append(
                            "%%cb%i%i%i%%c%i%i%i%s{n" % (ir, ig, ib, 5 - ir, 5 - ig, 5 - ib, "{{b%i%i%i" % (ir, ig, ib))
                        )
            table = utils.format_table(table)
            string = "Xterm256 colors:"
            for row in table:
                string += "\n" + "".join(row)
            self.caller.msg(string)
            self.caller.msg("(e.g. %%c123 and %%cb123 also work)")
Exemplo n.º 9
0
def format_script_list(scripts):
    "Takes a list of scripts and formats the output."
    if not scripts:
        return "<No scripts>"

    table = [["id"], ["obj"], ["key"], ["intval"], ["next"], ["rept"], ["db"], ["typeclass"], ["desc"]]
    for script in scripts:

        table[0].append(script.id)
        if not hasattr(script, 'obj') or not script.obj:
            table[1].append("<Global>")
        else:
            table[1].append(script.obj.key)
        table[2].append(script.key)
        if not hasattr(script, 'interval') or script.interval < 0:
            table[3].append("--")
        else:
            table[3].append("%ss" % script.interval)
        next = script.time_until_next_repeat()
        if not next:
            table[4].append("--")
        else:
            table[4].append("%ss" % next)

        if not hasattr(script, 'repeats') or not script.repeats:
            table[5].append("--")
        else:
            table[5].append("%s" % script.repeats)
        if script.persistent:
            table[6].append("*")
        else:
            table[6].append("-")
        typeclass_path = script.typeclass_path.rsplit('.', 1)
        table[7].append("%s" % typeclass_path[-1])
        table[8].append(script.desc)

    ftable = utils.format_table(table)
    string = ""
    for irow, row in enumerate(ftable):
        if irow == 0:
            srow = "\n" + "".join(row)
            srow = "{w%s{n" % srow.rstrip()
        else:
            srow = "\n" + "{w%s{n" % row[0] + "".join(row[1:])
        string += srow.rstrip()
    return string.strip()
Exemplo n.º 10
0
    def func(self):
        "Show color tables"

        if self.args.startswith("a"):
            # show ansi 16-color table
            from src.utils import ansi
            ap = ansi.ANSI_PARSER
            # ansi colors
            # show all ansi color-related codes
            col1 = ["%s%s{n" % (code, code.replace("{", "{{")) for code, _ in ap.ext_ansi_map[6:14]]
            col2 = ["%s%s{n" % (code, code.replace("{", "{{")) for code, _ in ap.ext_ansi_map[14:22]]
            col3 = ["%s%s{n" % (code.replace("\\",""), code.replace("{", "{{").replace("\\", "")) for code, _ in ap.ext_ansi_map[-8:]]
            col2.extend(["" for i in range(len(col1)-len(col2))])
            #hi = "%ch"
            #col2 = ["%s%s{n" % (code, code.replace("%", "%%")) for code, _ in ap.mux_ansi_map[6:]]
            #col3 = ["%s%s{n" % (hi + code, (hi + code).replace("%", "%%")) for code, _ in ap.mux_ansi_map[3:-2]]
            table = utils.format_table([col1, col2, col3])
            string = "ANSI colors:"
            for row in table:
                string += "\n " + " ".join(row)
            #print string
            self.msg(string)
            self.msg("{{X : black. {{\ : return, {{- : tab, {{_ : space, {{* : invert")
            self.msg("To combine background and foreground, add background marker last, e.g. {{r{{[b.")

        elif self.args.startswith("x"):
            # show xterm256 table
            table = [[], [], [], [], [], [], [], [], [], [], [], []]
            for ir in range(6):
                for ig in range(6):
                    for ib in range(6):
                        # foreground table
                        table[ir].append("{%i%i%i%s{n" % (ir, ig, ib, "{{%i%i%i" % (ir, ig, ib)))
                        # background table
                        table[6+ir].append("{[%i%i%i{%i%i%i%s{n" % (ir, ig, ib,
                                                            5 - ir, 5 - ig, 5 - ib,
                                                        "{{[%i%i%i" % (ir, ig, ib)))
            table = self.table_format(table)
            string = "Xterm256 colors (if not all hues show, your client might not report that it can handle xterm256):"
            for row in table:
                string += "\n" + "".join(row)
            self.msg(string)
            #self.msg("(e.g. %%123 and %%[123 also work)")
        else:
            # malformed input
            self.msg("Usage: @color ansi|xterm256")
Exemplo n.º 11
0
    def func(self):
        "Show color tables"

        if self.args.startswith("a"):
            # show ansi 16-color table
            from src.utils import ansi
            ap = ansi.ANSI_PARSER
            # ansi colors
            # show all ansi color-related codes
            col1 = ["%s%s{n" % (code, code.replace("{","{{")) for code, _ in ap.ext_ansi_map[:-1]]
            hi = "%ch"
            col2 = ["%s%s{n" % (code, code.replace("%", "%%")) for code, _ in ap.mux_ansi_map[3:-2]]
            col3 = ["%s%s{n" % (hi+code, (hi+code).replace("%", "%%")) for code, _ in ap.mux_ansi_map[3:-2]]
            table = utils.format_table([col1, col2, col3], extra_space=1)
            string = "ANSI colors:"
            for row in table:
                string += "\n" + "".join(row)
            #print string
            self.msg(string)
            self.msg("({{X and %%cx are black-on-black\n %%r - return, %%t - tab, %%b - space)")

        elif self.args.startswith("x"):
            # show xterm256 table
            table = [[],[],[],[],[],[],[],[],[],[],[],[]]
            for ir in range(6):
                for ig in range(6):
                    for ib in range(6):
                        # foreground table
                        table[ir].append("%%c%i%i%i%s{n" % (ir,ig,ib, "{{%i%i%i" % (ir,ig,ib)))
                        # background table
                        table[6+ir].append("%%cb%i%i%i%%c%i%i%i%s{n" % (ir,ig,ib,
                                                                        5-ir,5-ig,5-ib,
                                                                        "{{b%i%i%i" % (ir,ig,ib)))
            table = self.table_format(table)
            string = "Xterm256 colors (if not all hues show, your client might not report that it can handle xterm256):"
            for row in table:
                string += "\n" + "".join(row)
            self.msg(string)
            self.msg("(e.g. %%c123 and %%cb123 also work)")
        else:
            # malformed input
            self.msg("Usage: @color ansi|xterm256")
Exemplo n.º 12
0
 def func(self):
     "check inventory"
     items = self.caller.contents
     if not items:
         string = "You are not carrying anything."
     else:
         # format item list into nice collumns
         cols = [[],[]]
         for item in items:
             cols[0].append(item.name)
             desc = item.db.desc
             if not desc:
                 desc = ""
             cols[1].append(utils.crop(str(desc)))
         # auto-format the columns to make them evenly wide
         ftable = utils.format_table(cols)
         string = "You are carrying:"
         for row in ftable:
             string += "\n " + "{C%s{n - %s" % (row[0], row[1])
     self.caller.msg(string)
Exemplo n.º 13
0
    def func(self):
        "Show color tables"

        if self.args.startswith("a"):
            # show ansi 16-color table
            from src.utils import ansi
            ap = ansi.ANSI_PARSER
            # ansi colors
            # show all ansi color-related codes
            col1 = [
                "%s%s{n" % (code, code.replace("{", "{{"))
                for code, _ in ap.ext_ansi_map[6:14]
            ]
            col2 = [
                "%s%s{n" % (code, code.replace("{", "{{"))
                for code, _ in ap.ext_ansi_map[14:22]
            ]
            col3 = [
                "%s%s{n" % (code.replace("\\", ""), code.replace(
                    "{", "{{").replace("\\", ""))
                for code, _ in ap.ext_ansi_map[-8:]
            ]
            col2.extend(["" for i in range(len(col1) - len(col2))])
            #hi = "%ch"
            #col2 = ["%s%s{n" % (code, code.replace("%", "%%")) for code, _ in ap.mux_ansi_map[6:]]
            #col3 = ["%s%s{n" % (hi + code, (hi + code).replace("%", "%%")) for code, _ in ap.mux_ansi_map[3:-2]]
            table = utils.format_table([col1, col2, col3])
            string = "ANSI colors:"
            for row in table:
                string += "\n " + " ".join(row)
            #print string
            self.msg(string)
            self.msg(
                "{{X : black. {{\ : return, {{- : tab, {{_ : space, {{* : invert"
            )
            self.msg(
                "To combine background and foreground, add background marker last, e.g. {{r{{[b."
            )

        elif self.args.startswith("x"):
            # show xterm256 table
            table = [[], [], [], [], [], [], [], [], [], [], [], []]
            for ir in range(6):
                for ig in range(6):
                    for ib in range(6):
                        # foreground table
                        table[ir].append("{%i%i%i%s{n" %
                                         (ir, ig, ib, "{{%i%i%i" %
                                          (ir, ig, ib)))
                        # background table
                        table[6 + ir].append(
                            "{[%i%i%i{%i%i%i%s{n" %
                            (ir, ig, ib, 5 - ir, 5 - ig, 5 - ib, "{{[%i%i%i" %
                             (ir, ig, ib)))
            table = self.table_format(table)
            string = "Xterm256 colors (if not all hues show, your client might not report that it can handle xterm256):"
            for row in table:
                string += "\n" + "".join(row)
            self.msg(string)
            #self.msg("(e.g. %%123 and %%[123 also work)")
        else:
            # malformed input
            self.msg("Usage: @color ansi|xterm256")
Exemplo n.º 14
0
    def func(self):
        "Run the command"

        if not settings.IMC2_ENABLED:
            string = """IMC is not enabled. You need to activate it in game/settings.py."""
            self.caller.msg(string)
            return

        if "update" in self.switches:
            # update the lists
            import time
            from src.comms.imc2lib import imc2_packets as pck
            from src.comms.imc2 import IMC2_MUDLIST, IMC2_CHANLIST, IMC2_CLIENT
            # update connected muds
            IMC2_CLIENT.send_packet(pck.IMC2PacketKeepAliveRequest())
            # prune inactive muds
            for name, mudinfo in IMC2_MUDLIST.mud_list.items():
                if time.time() - mudinfo.last_updated > 3599:
                    del IMC2_MUDLIST.mud_list[name]
            # update channel list
            IMC2_CLIENT.send_packet(pck.IMC2PacketIceRefresh())
            self.caller.msg("IMC2 lists were re-synced.")

        elif "games" in self.switches or "muds" in self.switches or self.cmdstring == "@imclist":
            # list muds
            from src.comms.imc2 import IMC2_MUDLIST

            muds = IMC2_MUDLIST.get_mud_list()
            networks = set(mud.networkname for mud in muds)
            string = ""
            nmuds = 0
            for network in networks:
                string += "\n {GMuds registered on %s:{n" % network
                cols = [["Name"], ["Url"], ["Host"], ["Port"]]
                for mud in (mud for mud in muds if mud.networkname == network):
                    nmuds += 1
                    cols[0].append(mud.name)
                    cols[1].append(mud.url)
                    cols[2].append(mud.host)
                    cols[3].append(mud.port)
                ftable = utils.format_table(cols)
                for ir, row in enumerate(ftable):
                    if ir == 0:
                        string += "\n{w" + "".join(row) + "{n"
                    else:
                        string += "\n" + "".join(row)
            string += "\n %i Muds found." % nmuds
            self.caller.msg(string)

        elif "whois" in self.switches or self.cmdstring == "@imcwhois":
            # find out about a player
            if not self.args:
                self.caller.msg("Usage: @imcwhois <playername>")
                return
            from src.comms.imc2 import IMC2_CLIENT
            self.caller.msg("Sending IMC whois request. If you receive no response, no matches were found.")
            IMC2_CLIENT.msg_imc2(None, from_obj=self.caller, packet_type="imcwhois", data={"target":self.args})

        elif not self.switches or "channels" in self.switches or self.cmdstring == "@imcchanlist":
            # show channels
            from src.comms.imc2 import IMC2_CHANLIST, IMC2_CLIENT

            channels = IMC2_CHANLIST.get_channel_list()
            string = ""
            nchans = 0
            string += "\n {GChannels on %s:{n" % IMC2_CLIENT.factory.network
            cols = [["Full name"], ["Name"], ["Owner"], ["Perm"], ["Policy"]]
            for channel in channels:
                nchans += 1
                cols[0].append(channel.name)
                cols[1].append(channel.localname)
                cols[2].append(channel.owner)
                cols[3].append(channel.level)
                cols[4].append(channel.policy)
            ftable = utils.format_table(cols)
            for ir, row in enumerate(ftable):
                if ir == 0:
                    string += "\n{w" + "".join(row) + "{n"
                else:
                    string += "\n" + "".join(row)
            string += "\n %i Channels found." % nchans
            self.caller.msg(string)

        else:
            # no valid inputs
            string = "Usage: imcinfo|imcchanlist|imclist"
            self.caller.msg(string)
Exemplo n.º 15
0
    def func(self):
        "Setup the irc-channel mapping"

        if not settings.IRC_ENABLED:
            string = """IRC is not enabled. You need to activate it in game/settings.py."""
            self.caller.msg(string)
            return

        if 'list' in self.switches:
            # show all connections
            connections = ExternalChannelConnection.objects.filter(db_external_key__startswith='irc_')
            if connections:
                cols = [["Evennia channel"], ["IRC channel"]]
                for conn in connections:
                    cols[0].append(conn.channel.key)
                    cols[1].append(" ".join(conn.external_config.split('|')))
                ftable = utils.format_table(cols)
                string = ""
                for ir, row in enumerate(ftable):
                    if ir == 0:
                        string += "{w%s{n" % "".join(row)
                    else:
                        string += "\n" + "".join(row)
                self.caller.msg(string)
            else:
                self.caller.msg("No connections found.")
            return

        if not self.args or not self.rhs:
            string = "Usage: @irc2chan[/switches] <evennia_channel> = <ircnetwork> <port> <#irchannel> <botname>"
            self.caller.msg(string)
            return
        channel = self.lhs
        self.rhs = self.rhs.replace('#', ' ') # to avoid Python comment issues
        try:
            irc_network, irc_port, irc_channel, irc_botname = [part.strip() for part in self.rhs.split(None, 3)]
            irc_channel = "#%s" % irc_channel
        except Exception:
            string = "IRC bot definition '%s' is not valid." % self.rhs
            self.caller.msg(string)
            return

        if 'disconnect' in self.switches or 'remove' in self.switches or 'delete' in self.switches:
            chanmatch = find_channel(self.caller, channel, silent=True)
            if chanmatch:
                channel = chanmatch.key

            ok = irc.delete_connection(channel, irc_network, irc_port, irc_channel, irc_botname)
            if not ok:
                self.caller.msg("IRC connection/bot could not be removed, does it exist?")
            else:
                self.caller.msg("IRC connection destroyed.")
            return

        channel = find_channel(self.caller, channel)
        if not channel:
            return
        ok = irc.create_connection(channel, irc_network, irc_port, irc_channel, irc_botname)
        if not ok:
            self.caller.msg("This IRC connection already exists.")
            return
        self.caller.msg("Connection created. Starting IRC bot.")
Exemplo n.º 16
0
    def func(self):
        "Show list."

        caller = self.caller

        # display active processes

        if not utils.host_os_is('posix'):
            string = "Process listings are only available under Linux/Unix."
        else:
            global _resource, _idmapper
            if not _resource:
                import resource as _resource
            if not _idmapper:
                from src.utils.idmapper import base as _idmapper

            import resource
            loadavg = os.getloadavg()
            psize = _resource.getpagesize()
            pid = os.getpid()
            rmem = float(os.popen('ps -p %d -o %s | tail -1' % (pid, "rss")).read()) / 1024.0
            vmem = float(os.popen('ps -p %d -o %s | tail -1' % (pid, "vsz")).read()) / 1024.0

            rusage = resource.getrusage(resource.RUSAGE_SELF)
            table = [["Server load (1 min):",
                      "Process ID:",
                      "Bytes per page:",
                      "CPU time used:",
                      "Resident memory:",
                      "Virtual memory:",
                      "Page faults:",
                      "Disk I/O:",
                      "Network I/O:",
                      "Context switching:"
                      ],
                     ["%g" % loadavg[0],
                      "%10d" % pid,
                      "%10d " % psize,
                      "%s (%gs)" % (utils.time_format(rusage.ru_utime), rusage.ru_utime),
                      #"%10d shared" % rusage.ru_ixrss,
                      #"%10d pages" % rusage.ru_maxrss,
                      "%10.2f MB" % rmem,
                      "%10.2f MB" % vmem,
                      "%10d hard" % rusage.ru_majflt,
                      "%10d reads" % rusage.ru_inblock,
                      "%10d in" % rusage.ru_msgrcv,
                      "%10d vol" % rusage.ru_nvcsw
                    ],
                     ["", "", "",
                      "(user: %gs)" % rusage.ru_stime,
                      "", #"%10d private" % rusage.ru_idrss,
                      "", #"%10d bytes" % (rusage.ru_maxrss * psize),
                      "%10d soft" % rusage.ru_minflt,
                      "%10d writes" % rusage.ru_oublock,
                      "%10d out" % rusage.ru_msgsnd,
                      "%10d forced" % rusage.ru_nivcsw
                      ],
                     ["", "", "", "",
                      "", #"%10d stack" % rusage.ru_isrss,
                      "",
                      "%10d swapouts" % rusage.ru_nswap,
                      "", "",
                      "%10d sigs" % rusage.ru_nsignals
                    ]
                     ]
            stable = []
            for col in table:
                stable.append([str(val).strip() for val in col])
            ftable = utils.format_table(stable, 5)
            string = ""
            for row in ftable:
                string += "\n " + "{w%s{n" % row[0] + "".join(row[1:])

            # object cache size
            cachedict = _idmapper.cache_size()
            totcache = cachedict["_total"]
            string += "\n{w Database entity (idmapper) cache usage:{n %5.2f MB (%i items)" % (totcache[1], totcache[0])
            sorted_cache = sorted([(key, tup[0], tup[1]) for key, tup in cachedict.items() if key !="_total" and tup[0] > 0],
                                    key=lambda tup: tup[2], reverse=True)
            table = [[tup[0] for tup in sorted_cache],
                     ["%5.2f MB" % tup[2] for tup in sorted_cache],
                     ["%i item(s)" % tup[1] for tup in sorted_cache]]
            ftable = utils.format_table(table, 5)
            for row in ftable:
                string += "\n  " + row[0] + row[1] + row[2]
            # get sizes of other caches
            attr_cache_info, field_cache_info, prop_cache_info = get_cache_sizes()
            #size = sum([sum([getsizeof(obj) for obj in dic.values()]) for dic in _attribute_cache.values()])/1024.0
            #count = sum([len(dic) for dic in _attribute_cache.values()])
            string += "\n{w On-entity Attribute cache usage:{n %5.2f MB (%i attrs)" % (attr_cache_info[1], attr_cache_info[0])
            string += "\n{w On-entity Field cache usage:{n %5.2f MB (%i fields)" % (field_cache_info[1], field_cache_info[0])
            string += "\n{w On-entity Property cache usage:{n %5.2f MB (%i props)" % (prop_cache_info[1], prop_cache_info[0])
        caller.msg(string)
Exemplo n.º 17
0
    def __init__(self, key, text="", links=None, linktexts=None, 
                 keywords=None, cols=1, helptext=None, code=""):
        """
        key       - the unique identifier of this node.
        text      - is the text that will be displayed at top when viewing this node. 
        links     - a list of keys for unique menunodes this is connected to.
        linktexts - a list of texts to describe the links. If defined, need to match links list
        keywords  - a list of unique keys for choosing links. Must match links list. If not given, index numbers will be used.
        cols      - how many columns to use for displaying options.
        helptext  - if defined, this is shown when using the help command instead of the normal help index.
        code      - functional code. This will be executed just before this node is loaded (i.e. 
                    as soon after it's been selected from another node). self.caller is available
                    to call from this code block, as well as ObjectDB and PlayerDB. 
        """
        self.key = key
        self.cmdset = None
        self.links = links
        self.linktexts = linktexts
        self.keywords = keywords
        self.cols = cols
        self.code = code
                   
        # validate the input 
        if not self.links:
            self.links = []
        if not self.linktexts or (self.linktexts and len(self.linktexts) != len(self.links)):
            self.linktexts = []
        if not self.keywords or (self.keywords and len(self.keywords) != len(self.links)):
            self.keywords = []

        # Format default text for the menu-help command 
        if not helptext:            
            helptext = "Select one of the valid options"
            if self.keywords:
                helptext += " (" + ", ".join(self.keywords) + ")"
            elif self.links:
                helptext += " (" + ", ".join([str(i + 1) for i in range(len(self.links))]) + ")"
        self.helptext = helptext

        # Format text display 
        string = ""
        if text:
            string += "%s\n" % text

        # format the choices into as many collumns as specified
        choices = []
        for ilink, link in enumerate(self.links):
            if self.keywords:
                choice = "{g%s{n" % self.keywords[ilink]
            else:
                choice = "{g%i{n" % (ilink + 1) 
            if self.linktexts:
                choice += "-%s" % self.linktexts[ilink]
            choices.append(choice)
        cols = [[] for i in range(min(len(choices), cols))]
        while True:
            for i in range(len(cols)):
                if not choices:
                    cols[i].append("")
                else:
                    cols[i].append(choices.pop(0))
            if not choices:
                break 
        ftable = utils.format_table(cols)
        for row in ftable:
            string += "\n" + "".join(row)
        # store text 
        self.text = 78*"-" + "\n" + string.strip()