Finally caved in and created a command table. It's just going to get too messy with @-commands doing straight module lookups, plus the dict is probably a little faster. Feel free to start moving non-privved @-commands to commands_general and vice-versa since we now have the ability to do so.

This commit is contained in:
Greg Taylor 2007-05-11 15:23:27 +00:00
parent 2fc06adcfa
commit ac32ab05c1
7 changed files with 174 additions and 43 deletions

View file

@ -638,6 +638,47 @@ class CommChannel(models.Model):
class Admin: class Admin:
list_display = ('name', 'owner') list_display = ('name', 'owner')
def get_name(self):
"""
Returns a channel's name.
"""
return self.name
def get_header(self):
"""
Returns the channel's header text, or what is shown before each channel
message.
"""
return ansi.parse_ansi(self.header)
def get_owner(self):
"""
Returns a channels' owner.
"""
return self.owner
def set_name(self, new_name):
"""
Rename a channel
"""
self.name = ansi.parse_ansi(new_name, strip_ansi=True)
self.header = "[%s]" % (ansi.parse_ansi(new_name),)
self.save()
def set_header(self, new_header):
"""
Sets a channel's header text.
"""
self.header = ansi.parse_ansi(new_header)
self.save()
def set_owner(self, new_owner):
"""
Sets a channel's owner.
"""
self.owner = new_owner
self.save()
class CommChannelMessage(models.Model): class CommChannelMessage(models.Model):
""" """
A single logged channel message. A single logged channel message.

View file

@ -2,7 +2,9 @@ from traceback import format_exc
import time import time
import commands_privileged import commands_privileged
import commands_general import commands_general
import commands_comsys
import commands_unloggedin import commands_unloggedin
import cmdtable
import functions_db import functions_db
import functions_general import functions_general
@ -40,17 +42,17 @@ def handle(cdat):
# TODO: Protect against non-standard characters. # TODO: Protect against non-standard characters.
if cdat['uinput'] == '': if cdat['uinput'] == '':
raise UnknownCommand raise UnknownCommand
uinput = cdat['uinput'].split() uinput = cdat['uinput'].split()
parsed_input = {} parsed_input = {}
# First we split the input up by spaces. # First we split the input up by spaces.
parsed_input['splitted'] = uinput parsed_input['splitted'] = uinput
# Now we find the root command chunk (with switches attached). # Now we find the root command chunk (with switches attached).
parsed_input['root_chunk'] = parsed_input['splitted'][0].split('/') parsed_input['root_chunk'] = parsed_input['splitted'][0].split('/')
# And now for the actual root command. It's the first entry in root_chunk. # And now for the actual root command. It's the first entry in root_chunk.
parsed_input['root_cmd'] = parsed_input['root_chunk'][0].lower() parsed_input['root_cmd'] = parsed_input['root_chunk'][0].lower()
# Now we'll see if the user is using an alias. We do a dictionary lookup, # Now we'll see if the user is using an alias. We do a dictionary lookup,
# if the key (the player's root command) doesn't exist on the dict, we # if the key (the player's root command) doesn't exist on the dict, we
# don't replace the existing root_cmd. If the key exists, its value # don't replace the existing root_cmd. If the key exists, its value
@ -61,7 +63,7 @@ def handle(cdat):
if session.logged_in: if session.logged_in:
# Store the timestamp of the user's last command. # Store the timestamp of the user's last command.
session.cmd_last = time.time() session.cmd_last = time.time()
# Lets the users get around badly configured NAT timeouts. # Lets the users get around badly configured NAT timeouts.
if parsed_input['root_cmd'] == 'idle': if parsed_input['root_cmd'] == 'idle':
return return
@ -70,36 +72,34 @@ def handle(cdat):
session.cmd_total += 1 session.cmd_total += 1
# Player-visible idle time, not used in idle timeout calcs. # Player-visible idle time, not used in idle timeout calcs.
session.cmd_last_visible = time.time() session.cmd_last_visible = time.time()
# If it's prefixed by an '@', it's a staff command. # Shortened say alias.
if parsed_input['root_cmd'][0] != '@': if parsed_input['root_cmd'][0] == '"':
# Shortened say alias. parsed_input['splitted'].insert(0, "say")
if parsed_input['root_cmd'][0] == '"': parsed_input['splitted'][1] = parsed_input['splitted'][1][1:]
parsed_input['splitted'].insert(0, "say") parsed_input['root_cmd'] = 'say'
parsed_input['splitted'][1] = parsed_input['splitted'][1][1:] # Shortened pose alias.
parsed_input['root_cmd'] = 'say' elif parsed_input['root_cmd'][0] == ':':
# Shortened pose alias. parsed_input['splitted'].insert(0, "pose")
elif parsed_input['root_cmd'][0] == ':': parsed_input['splitted'][1] = parsed_input['splitted'][1][1:]
parsed_input['splitted'].insert(0, "pose") parsed_input['root_cmd'] = 'pose'
parsed_input['splitted'][1] = parsed_input['splitted'][1][1:] # Pose without space alias.
parsed_input['root_cmd'] = 'pose' elif parsed_input['root_cmd'][0] == ';':
# Pose without space alias. parsed_input['splitted'].insert(0, "pose/nospace")
elif parsed_input['root_cmd'][0] == ';': parsed_input['root_chunk'] = ['pose', 'nospace']
parsed_input['splitted'].insert(0, "pose/nospace") parsed_input['splitted'][1] = parsed_input['splitted'][1][1:]
parsed_input['root_chunk'] = ['pose', 'nospace'] parsed_input['root_cmd'] = 'pose'
parsed_input['splitted'][1] = parsed_input['splitted'][1][1:]
parsed_input['root_cmd'] = 'pose' # Get the command's function reference (Or False)
cmd = getattr(commands_general, 'cmd_%s' % (parsed_input['root_cmd'],), None ) cmd = cmdtable.return_cfunc(parsed_input['root_cmd'])
else:
parsed_input['root_cmd'] = parsed_input['root_cmd'][1:]
cmd = getattr(commands_privileged, 'cmd_%s' % (parsed_input['root_cmd'],), None )
else: else:
cmd = getattr(commands_unloggedin, 'cmd_%s' % (parsed_input['root_cmd'],), None ) # Not logged in, look through the unlogged-in command table.
cmd = cmdtable.return_cfunc(parsed_input['root_cmd'], unlogged_cmd=True)
# Debugging stuff. # Debugging stuff.
#session.msg("ROOT : %s" % (parsed_input['root_cmd'],)) #session.msg("ROOT : %s" % (parsed_input['root_cmd'],))
#session.msg("SPLIT: %s" % (parsed_input['splitted'],)) #session.msg("SPLIT: %s" % (parsed_input['splitted'],))
if callable(cmd): if callable(cmd):
cdat['uinput'] = parsed_input cdat['uinput'] = parsed_input
try: try:
@ -109,7 +109,7 @@ def handle(cdat):
functions_general.log_errmsg("Untrapped error, evoker %s: %s" % functions_general.log_errmsg("Untrapped error, evoker %s: %s" %
(session, format_exc())) (session, format_exc()))
return return
if session.logged_in: if session.logged_in:
# If we're not logged in, don't check exits. # If we're not logged in, don't check exits.
pobject = session.get_pobject() pobject = session.get_pobject()
@ -123,10 +123,10 @@ def handle(cdat):
else: else:
session.msg("That exit leads to nowhere.") session.msg("That exit leads to nowhere.")
return return
# If we reach this point, we haven't matched anything. # If we reach this point, we haven't matched anything.
raise UnknownCommand raise UnknownCommand
except UnknownCommand: except UnknownCommand:
session.msg("Huh? (Type \"help\" for help.)") session.msg("Huh? (Type \"help\" for help.)")

61
cmdtable.py Normal file
View file

@ -0,0 +1,61 @@
import commands_unloggedin
import commands_general
import commands_privileged
import commands_comsys
# Unlogged-in Command Table
uncon_ctable = {
"connect": commands_unloggedin.cmd_connect,
"create": commands_unloggedin.cmd_create,
"quit": commands_unloggedin.cmd_quit,
}
# Command Table
ctable = {
"drop": commands_general.cmd_drop,
"examine": commands_general.cmd_examine,
"get": commands_general.cmd_get,
"help": commands_general.cmd_help,
"idle": commands_general.cmd_idle,
"inventory": commands_general.cmd_inventory,
"look": commands_general.cmd_look,
"page": commands_general.cmd_page,
"pose": commands_general.cmd_pose,
"quit": commands_general.cmd_quit,
"say": commands_general.cmd_say,
"time": commands_general.cmd_time,
"uptime": commands_general.cmd_uptime,
"version": commands_general.cmd_version,
"who": commands_general.cmd_who,
"@ccreate": commands_privileged.cmd_ccreate,
"@create": commands_privileged.cmd_create,
"@description": commands_privileged.cmd_description,
"@destroy": commands_privileged.cmd_destroy,
"@dig": commands_privileged.cmd_dig,
"@emit": commands_privileged.cmd_emit,
"@find": commands_privileged.cmd_find,
"@link": commands_privileged.cmd_link,
"@list": commands_privileged.cmd_list,
"@name": commands_privileged.cmd_name,
"@nextfree": commands_privileged.cmd_nextfree,
"@newpassword": commands_privileged.cmd_newpassword,
"@open": commands_privileged.cmd_open,
"@password": commands_privileged.cmd_password,
"@reload": commands_privileged.cmd_reload,
"@set": commands_privileged.cmd_set,
"@shutdown": commands_privileged.cmd_shutdown,
"@teleport": commands_privileged.cmd_teleport,
"@unlink": commands_privileged.cmd_unlink,
"@wall": commands_privileged.cmd_wall,
}
def return_cfunc(func_name, unlogged_cmd=False):
"""
Returns a reerence to the command's function. If there are no matches,
returns false.
"""
if not unlogged_cmd:
return ctable.get(func_name, False)
else:
return uncon_ctable.get(func_name, False)

View file

@ -10,7 +10,8 @@ import os
""" """
Comsys command module. Pretty much every comsys command should go here for Comsys command module. Pretty much every comsys command should go here for
now. now.
""" """
def cmd_addcom(cdat): def cmd_addcom(cdat):
""" """
addcom addcom
@ -54,14 +55,6 @@ def cmd_clist(cdat):
""" """
pass pass
def cmd_ccreate(cdat):
"""
@ccreate
Creates a channel.
"""
pass
def cmd_cdestroy(cdat): def cmd_cdestroy(cdat):
""" """
@cdestroy @cdestroy

View file

@ -3,6 +3,7 @@ import resource
import functions_db import functions_db
import functions_general import functions_general
import functions_comsys
import commands_general import commands_general
import commands_unloggedin import commands_unloggedin
import cmdhandler import cmdhandler
@ -270,6 +271,24 @@ def cmd_emit(cdat):
session.msg("Emit what?") session.msg("Emit what?")
else: else:
pobject.get_location().emit_to_contents(message) pobject.get_location().emit_to_contents(message)
def cmd_ccreate(cdat):
"""
Creates a new channel.
"""
session = cdat['session']
pobject = session.get_pobject()
uinput= cdat['uinput']['splitted']
cname = ' '.join(uinput[1:])
if cname == '':
session.msg("You must supply a name!")
else:
# Create and set the object up.
cdat = {"name": cname, "owner": pobject}
new_chan = functions_comsys.create_channel(cdat)
session.msg("Channel %s created." % (new_chan.get_name(),))
def cmd_create(cdat): def cmd_create(cdat):
""" """

View file

@ -1,8 +1,10 @@
from apps.objects.models import CommChannel
import session_mgr import session_mgr
import commands_privileged import commands_privileged
import commands_general import commands_general
import commands_comsys import commands_comsys
import commands_unloggedin import commands_unloggedin
import ansi
""" """
Comsys functions. Comsys functions.
""" """
@ -21,3 +23,17 @@ def get_com_who(channel, muted=False, disconnected=False):
def get_user_channels(player): def get_user_channels(player):
pass pass
def create_channel(cdat):
"""
Create a new channel. cdat is a dictionary that contains the following keys.
REQUIRED KEYS:
* name: The name of the new channel.
* owner: The creator of the channel.
"""
new_chan = CommChannel()
new_chan.name = ansi.parse_ansi(cdat["name"], strip_ansi=True)
new_chan.header = "[%s]" % (ansi.parse_ansi(cdat["name"]),)
new_chan.set_owner(cdat["owner"])
new_chan.save()
return new_chan

View file

@ -102,7 +102,8 @@ class Server(dispatcher):
'commands_privileged', 'commands_unloggedin', 'defines_global', 'commands_privileged', 'commands_unloggedin', 'defines_global',
'events', 'functions_db', 'functions_general', 'functions_help', 'events', 'functions_db', 'functions_general', 'functions_help',
'gameconf', 'session', 'apps.objects.models', 'gameconf', 'session', 'apps.objects.models',
'apps.helpsys.models', 'apps.config.models'] 'apps.helpsys.models', 'apps.config.models', 'functions_comsys',
'commands_comsys']
for mod in reload_list: for mod in reload_list:
reload(sys.modules[mod]) reload(sys.modules[mod])