X-Git-Url: https://mudpy.org/gitweb?a=blobdiff_plain;f=mudpy.py;h=b25340cf3c617a7b40fec1a7b4bf502fc8841b71;hb=5016c3731daf450cc0f3defce0c3e66854270356;hp=1e0d2d644e357429ff215088a2fe2ac277dc64d6;hpb=4967d5001507be48abcf0f6d8bb77a8163797e09;p=mudpy.git diff --git a/mudpy.py b/mudpy.py index 1e0d2d6..b25340c 100644 --- a/mudpy.py +++ b/mudpy.py @@ -4,23 +4,15 @@ # Licensed per terms in the LICENSE file distributed with this software. # import some things we need -from ConfigParser import SafeConfigParser +from ConfigParser import RawConfigParser from md5 import new as new_md5 -from os import F_OK, R_OK, access, getcwd, makedirs, sep +from os import R_OK, access, chmod, makedirs, stat +from os.path import abspath, dirname, exists, isabs, join as path_join from random import choice, randrange from socket import AF_INET, SO_REUSEADDR, SOCK_STREAM, SOL_SOCKET, socket +from stat import S_IMODE, ST_MODE from time import asctime, sleep -# a dict of replacement macros -macros = { - "$(eol)": "\r\n", - "$(bld)": chr(27) + "[1m", - "$(nrm)": chr(27) + "[0m", - "$(blk)": chr(27) + "[30m", - "$(grn)": chr(27) + "[32m", - "$(red)": chr(27) + "[31m" - } - class Element: """An element of the universe.""" def __init__(self, key, universe, origin=""): @@ -35,78 +27,106 @@ class Element: universe.categories[self.category][self.subkey] = self self.origin = origin if not self.origin: self.origin = universe.default_origins[self.category] - if not self.origin.startswith(sep): - self.origin = getcwd() + sep + self.origin + if not isabs(self.origin): + self.origin = abspath(self.origin) universe.contents[self.key] = self if not self.origin in universe.files: DataFile(self.origin, universe) if not universe.files[self.origin].data.has_section(self.key): universe.files[self.origin].data.add_section(self.key) - def delete(self): - log("Deleting: " + self.key + ".") + def destroy(self): + """Remove an element from the universe and destroy it.""" + log("Destroying: " + self.key + ".") universe.files[self.origin].data.remove_section(self.key) del universe.categories[self.category][self.subkey] del universe.contents[self.key] del self + def delete(self, facet): + """Delete a facet from the element.""" + if universe.files[self.origin].data.has_option(self.key, facet): + universe.files[self.origin].data.remove_option(self.key, facet) def facets(self): """Return a list of facets for this element.""" return universe.files[self.origin].data.options(self.key) - def get(self, facet): + def get(self, facet, default=None): """Retrieve values.""" + if default is None: default = "" if universe.files[self.origin].data.has_option(self.key, facet): return universe.files[self.origin].data.get(self.key, facet) - else: - return "" - def getboolean(self, facet, default=False): + else: return default + def getboolean(self, facet, default=None): """Retrieve values as boolean type.""" + if default is None: default=False if universe.files[self.origin].data.has_option(self.key, facet): return universe.files[self.origin].data.getboolean(self.key, facet) - else: - return default - def getint(self, facet): - """Convenience method to coerce return values as type int.""" + else: return default + def getint(self, facet, default=None): + """Return values as int/long type.""" + if default is None: default = 0 + if universe.files[self.origin].data.has_option(self.key, facet): + return universe.files[self.origin].data.getint(self.key, facet) + else: return default + def getfloat(self, facet, default=None): + """Return values as float type.""" + if default is None: default = 0.0 + if universe.files[self.origin].data.has_option(self.key, facet): + return universe.files[self.origin].data.getfloat(self.key, facet) + else: return default + def getlist(self, facet, default=None): + """Return values as list type.""" + if default is None: default = [] value = self.get(facet) - if not value: value = 0 - elif type(value) is str: value = value.rstrip("L") - return int(value) - def getfloat(self, facet): - """Convenience method to coerce return values as type float.""" + if value: return makelist(value) + else: return default + def getdict(self, facet, default=None): + """Return values as dict type.""" + if default is None: default = {} value = self.get(facet) - if not value: value = 0 - elif type(value) is str: value = value.rstrip("L") - return float(value) + if value: return makedict(value) + else: return default def set(self, facet, value): """Set values.""" - if not type(value) is str: value = repr(value) + if type(value) is long: value = str(value) + elif not type(value) is str: value = repr(value) universe.files[self.origin].data.set(self.key, facet, value) class DataFile: """A file containing universe elements.""" def __init__(self, filename, universe): - filedir = sep.join(filename.split(sep)[:-1]) - self.data = SafeConfigParser() + self.data = RawConfigParser() if access(filename, R_OK): self.data.read(filename) self.filename = filename universe.files[filename] = self - if "categories" in self.data.sections(): - for option in self.data.options("categories"): - universe.default_origins[option] = self.data.get("categories", option) - if not option in universe.categories: - universe.categories[option] = {} + if self.data.has_option("control", "include_files"): + includes = makelist(self.data.get("control", "include_files")) + else: includes = [] + if self.data.has_option("control", "default_files"): + origins = makedict(self.data.get("control", "default_files")) + for key in origins.keys(): + if not key in includes: includes.append(key) + universe.default_origins[key] = origins[key] + if not key in universe.categories: + universe.categories[key] = {} + if self.data.has_option("control", "private_files"): + for item in makelist(self.data.get("control", "private_files")): + if not item in includes: includes.append(item) + if not item in universe.private_files: + if not isabs(item): + item = path_join(dirname(filename), item) + universe.private_files.append(item) for section in self.data.sections(): - if section == "categories" or section == "include": - for option in self.data.options(section): - includefile = self.data.get(section, option) - if not includefile.startswith(sep): - includefile = filedir + sep + includefile - DataFile(includefile, universe) - elif section != "control": + if section != "control": Element(section, universe, filename) + for include_file in includes: + if not isabs(include_file): + include_file = path_join(dirname(filename), include_file) + DataFile(include_file, universe) def save(self): - if self.data.sections() and not ( "control" in self.data.sections() and self.data.getboolean("control", "read_only") ): - basedir = sep.join(self.filename.split(sep)[:-1]) - if not access(basedir, F_OK): makedirs(basedir) + if ( self.data.sections() or exists(self.filename) ) and not ( self.data.has_option("control", "read_only") and self.data.getboolean("control", "read_only") ): + if not exists(dirname(self.filename)): makedirs(dirname(self.filename)) file_descriptor = file(self.filename, "w") + if self.filename in universe.private_files and oct(S_IMODE(stat(self.filename)[ST_MODE])) != 0600: + chmod(self.filename, 0600) self.data.write(file_descriptor) file_descriptor.flush() file_descriptor.close() @@ -119,6 +139,7 @@ class Universe: self.contents = {} self.default_origins = {} self.files = {} + self.private_files = [] self.userlist = [] self.terminate_world = False self.reload_modules = False @@ -136,8 +157,8 @@ class Universe: ] for filename in possible_filenames: if access(filename, R_OK): break - if not filename.startswith(sep): - filename = getcwd() + sep + filename + if not isabs(filename): + filename = abspath(filename) DataFile(filename, self) def save(self): """Save the universe to persistent storage.""" @@ -176,7 +197,7 @@ class User: self.last_address = "" self.connection = None self.authenticated = False - self.password_tries = 1 + self.password_tries = 0 self.state = "entering_account_name" self.menu_seen = False self.error = "" @@ -189,7 +210,8 @@ class User: def quit(self): """Log, close the connection and remove.""" - name = self.account.get("name") + if self.account: name = self.account.get("name") + else: name = "" if name: message = "User " + name else: message = "An unnamed user" message += " logged out." @@ -387,26 +409,60 @@ class User: # put on the end of the queue self.input_queue.append(line) + def can_run(self, command): + """Check if the user can run this command object.""" + + # has to be in the commands category + if command not in universe.categories["command"].values(): result = False + + # administrators can run any command + elif self.account.getboolean("administrator"): result = True + + # everyone can run non-administrative commands + elif not command.getboolean("administrative"): result = True + + # otherwise the command cannot be run by this user + else: result = False + + # pass back the result + return result + def new_avatar(self): """Instantiate a new, unconfigured avatar for this user.""" - counter = universe.categories["internal"]["counters"].getint("next_avatar") - while "avatar:" + repr(counter + 1) in universe.categories["actor"].keys(): counter += 1 - universe.categories["internal"]["counters"].set("next_avatar", counter + 1) - self.avatar = Element("actor:avatar:" + repr(counter), universe) - avatars = self.account.get("avatars").split() + counter = 0 + while "avatar:" + self.account.get("name") + ":" + str(counter) in universe.categories["actor"].keys(): counter += 1 + self.avatar = Element("actor:avatar:" + self.account.get("name") + ":" + str(counter), universe) + avatars = self.account.getlist("avatars") avatars.append(self.avatar.key) - self.account.set("avatars", " ".join(avatars)) + self.account.set("avatars", avatars) + + def delete_avatar(self, avatar): + """Remove an avatar from the world and from the user's list.""" + if self.avatar is universe.contents[avatar]: self.avatar = None + universe.contents[avatar].destroy() + avatars = self.account.getlist("avatars") + avatars.remove(avatar) + self.account.set("avatars", avatars) + + def destroy(self): + """Destroy the user and associated avatars.""" + for avatar in self.account.getlist("avatars"): self.delete_avatar(avatar) + self.account.destroy() def list_avatar_names(self): - """A test function to list names of assigned avatars.""" - try: - avatars = self.account.get("avatars").split() - except: - avatars = [] - avatar_names = [] - for avatar in avatars: - avatar_names.append(universe.contents[avatar].get("name")) - return avatar_names + """List names of assigned avatars.""" + return [ universe.contents[avatar].get("name") for avatar in self.account.getlist("avatars") ] + +def makelist(value): + """Turn string into list type.""" + if value[0] + value[-1] == "[]": return eval(value) + else: return [ value ] + +def makedict(value): + """Turn string into dict type.""" + if value[0] + value[-1] == "{}": return eval(value) + elif value.find(":") > 0: return eval("{" + value + "}") + else: return { value: None } def broadcast(message): """Send a message to all connected users.""" @@ -531,7 +587,40 @@ def random_name(): def replace_macros(user, text, is_input=False): """Replaces macros in text output.""" + + # loop until broken while True: + + # third person pronouns + pronouns = { + "female": { "obj": "her", "pos": "hers", "sub": "she" }, + "male": { "obj": "him", "pos": "his", "sub": "he" }, + "neuter": { "obj": "it", "pos": "its", "sub": "it" } + } + + # a dict of replacement macros + macros = { + "$(eol)": "\r\n", + "$(bld)": chr(27) + "[1m", + "$(nrm)": chr(27) + "[0m", + "$(blk)": chr(27) + "[30m", + "$(grn)": chr(27) + "[32m", + "$(red)": chr(27) + "[31m", + } + + # add dynamic macros where possible + if user.account: + account_name = user.account.get("name") + if account_name: + macros["$(account)"] = account_name + if user.avatar: + avatar_gender = user.avatar.get("gender") + if avatar_gender: + macros["$(tpop)"] = pronouns[avatar_gender]["obj"] + macros["$(tppp)"] = pronouns[avatar_gender]["pos"] + macros["$(tpsp)"] = pronouns[avatar_gender]["sub"] + + # find and replace per the macros dict macro_start = text.find("$(") if macro_start == -1: break macro_end = text.find(")", macro_start) + 1 @@ -539,37 +628,6 @@ def replace_macros(user, text, is_input=False): if macro in macros.keys(): text = text.replace(macro, macros[macro]) - # the user's account name - elif macro == "$(account)": - text = text.replace(macro, user.account.get("name")) - - # third person subjective pronoun - elif macro == "$(tpsp)": - if user.avatar.get("gender") == "male": - text = text.replace(macro, "he") - elif user.avatar.get("gender") == "female": - text = text.replace(macro, "she") - else: - text = text.replace(macro, "it") - - # third person objective pronoun - elif macro == "$(tpop)": - if user.avatar.get("gender") == "male": - text = text.replace(macro, "him") - elif user.avatar.get("gender") == "female": - text = text.replace(macro, "her") - else: - text = text.replace(macro, "it") - - # third person possessive pronoun - elif macro == "$(tppp)": - if user.avatar.get("gender") == "male": - text = text.replace(macro, "his") - elif user.avatar.get("gender") == "female": - text = text.replace(macro, "hers") - else: - text = text.replace(macro, "its") - # if we get here, log and replace it with null else: text = text.replace(macro, "") @@ -581,6 +639,10 @@ def replace_macros(user, text, is_input=False): return text +def escape_macros(text): + """Escapes replacement macros in text.""" + return text.replace("$(", "$_(") + def check_time(frequency): """Check for a factor of the current increment count.""" if type(frequency) is str: @@ -605,7 +667,7 @@ def on_pulse(): # update the log every now and then if check_time("frequency_log"): - log(repr(len(universe.userlist)) + " connection(s)") + log(str(len(universe.userlist)) + " connection(s)") # periodically save everything if check_time("frequency_save"): @@ -701,8 +763,8 @@ def get_default_menu_choice(state): def get_formatted_default_menu_choice(state): """Default menu choice foratted for inclusion in a prompt string.""" - default = get_default_menu_choice(state) - if default: return "[$(red)" + default + "$(nrm)] " + default_choice = get_default_menu_choice(state) + if default_choice: return "[$(red)" + default_choice + "$(nrm)] " else: return "" def get_menu_description(state, error): @@ -735,12 +797,26 @@ def get_menu_prompt(state): def get_menu_choices(user): """Return a dict of choice:meaning.""" - choices = {} - for facet in universe.categories["menu"][user.state].facets(): - if facet.startswith("choice_"): - choices[facet.split("_", 2)[1]] = universe.categories["menu"][user.state].get(facet) + menu = universe.categories["menu"][user.state] + create_choices = menu.get("create") + if create_choices: choices = eval(create_choices) + else: choices = {} + ignores = [] + options = {} + creates = {} + for facet in menu.facets(): + if facet.startswith("demand_") and not eval(universe.categories["menu"][user.state].get(facet)): + ignores.append(facet.split("_", 2)[1]) elif facet.startswith("create_"): - choices[facet.split("_", 2)[1]] = eval(universe.categories["menu"][user.state].get(facet)) + creates[facet] = facet.split("_", 2)[1] + elif facet.startswith("choice_"): + options[facet] = facet.split("_", 2)[1] + for facet in creates.keys(): + if not creates[facet] in ignores: + choices[creates[facet]] = eval(menu.get(facet)) + for facet in options.keys(): + if not options[facet] in ignores: + choices[options[facet]] = menu.get(facet) return choices def get_formatted_menu_choices(state, choices): @@ -768,7 +844,6 @@ def get_default_branch(state): def get_choice_branch(user, choice): """Returns the new state matching the given choice.""" branches = get_menu_branches(user.state) - if not choice: choice = get_default_menu_choice(user.state) if choice in branches.keys(): return branches[choice] elif choice in user.menu_choices.keys(): return get_default_branch(user.state) else: return "" @@ -788,7 +863,6 @@ def get_default_action(state): def get_choice_action(user, choice): """Run any indicated script for the given choice.""" actions = get_menu_actions(user.state) - if not choice: choice = get_default_menu_choice(user.state) if choice in actions.keys(): return actions[choice] elif choice in user.menu_choices.keys(): return get_default_action(user.state) else: return "" @@ -816,13 +890,11 @@ def generic_menu_handler(user): choice = user.input_queue.pop(0) if choice: choice = choice.lower() else: choice = "" - - # run any script related to this choice - exec(get_choice_action(user, choice)) - - # move on to the next state or return an error - new_state = get_choice_branch(user, choice) - if new_state: user.state = new_state + if not choice: choice = get_default_menu_choice(user.state) + if choice in user.menu_choices: + exec(get_choice_action(user, choice)) + new_state = get_choice_branch(user, choice) + if new_state: user.state = new_state else: user.error = "default" def handler_entering_account_name(user): @@ -872,7 +944,7 @@ def handler_checking_password(user): user.state = "main_utility" # if at first your hashes don't match, try, try again - elif user.password_tries < universe.categories["internal"]["general"].getint("password_tries"): + elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1: user.password_tries += 1 user.error = "incorrect" @@ -881,38 +953,6 @@ def handler_checking_password(user): user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)") user.state = "disconnecting" -def handler_checking_new_account_name(user): - """Handle input for the new user menu.""" - - # get the next waiting line of input - input_data = user.input_queue.pop(0) - - # if there's input, take the first character and lowercase it - if input_data: - choice = input_data.lower()[0] - - # if there's no input, use the default - else: - choice = get_default_menu_choice(user.state) - - # user selected to disconnect - if choice == "d": - user.account.delete() - user.state = "disconnecting" - - # go back to the login screen - elif choice == "g": - user.account.delete() - user.state = "entering_account_name" - - # new user, so ask for a password - elif choice == "n": - user.state = "entering_new_password" - - # user entered a non-existent option - else: - user.error = "default" - def handler_entering_new_password(user): """Handle a new password entry.""" @@ -928,14 +968,14 @@ def handler_entering_new_password(user): user.state = "verifying_new_password" # the password was weak, try again if you haven't tried too many times - elif user.password_tries < universe.categories["internal"]["general"].getint("password_tries"): + elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1: user.password_tries += 1 user.error = "weak" # too many tries, so adios else: user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)") - user.account.delete() + user.account.destroy() user.state = "disconnecting" def handler_verifying_new_password(user): @@ -953,7 +993,7 @@ def handler_verifying_new_password(user): # go back to entering the new password as long as you haven't tried # too many times - elif user.password_tries < universe.categories["internal"]["general"].getint("password_tries"): + elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1: user.password_tries += 1 user.error = "differs" user.state = "entering_new_password" @@ -961,7 +1001,7 @@ def handler_verifying_new_password(user): # otherwise, sayonara else: user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)") - user.account.delete() + user.account.destroy() user.state = "disconnecting" def handler_active(user): @@ -972,22 +1012,26 @@ def handler_active(user): # split out the command (first word) and parameters (everything else) if input_data.find(" ") > 0: - command, parameters = input_data.split(" ", 1) + command_name, parameters = input_data.split(" ", 1) else: - command = input_data + command_name = input_data parameters = "" # lowercase the command - command = command.lower() + command_name = command_name.lower() # the command matches a command word for which we have data - if command in universe.categories["command"]: - exec(universe.categories["command"][command].get("action")) + if command_name in universe.categories["command"]: + command = universe.categories["command"][command_name] + else: command = None + + # if it's allowed, do it + if user.can_run(command): exec(command.get("action")) - # no data matching the entered command word - elif command: command_error(user, command, parameters) + # otherwise, give an error + elif command_name: command_error(user, input_data) -def command_halt(user, command="", parameters=""): +def command_halt(user, parameters): """Halt the world.""" # see if there's a message or use a generic one @@ -1001,7 +1045,7 @@ def command_halt(user, command="", parameters=""): # set a flag to terminate the world universe.terminate_world = True -def command_reload(user, command="", parameters=""): +def command_reload(user): """Reload all code modules, configs and data.""" # let the user know and log @@ -1011,11 +1055,7 @@ def command_reload(user, command="", parameters=""): # set a flag to reload universe.reload_modules = True -def command_quit(user, command="", parameters=""): - """Quit the world.""" - user.state = "disconnecting" - -def command_help(user, command="", parameters=""): +def command_help(user, parameters): """List available commands and provide help for commands.""" # did the user ask for help on a specific command word? @@ -1023,15 +1063,22 @@ def command_help(user, command="", parameters=""): # is the command word one for which we have data? if parameters in universe.categories["command"]: + command = universe.categories["command"][parameters] + else: command = None + + # only for allowed commands + if user.can_run(command): # add a description if provided - description = universe.categories["command"][parameters].get("description") + description = command.get("description") if not description: description = "(no short description provided)" - output = "$(grn)" + parameters + "$(nrm) - " + description + "$(eol)$(eol)" + if command.getboolean("administrative"): output = "$(red)" + else: output = "$(grn)" + output += parameters + "$(nrm) - " + description + "$(eol)$(eol)" # add the help text if provided - help_text = universe.categories["command"][parameters].get("help") + help_text = command.get("help") if not help_text: help_text = "No help is provided for this command." output += help_text @@ -1048,16 +1095,20 @@ def command_help(user, command="", parameters=""): sorted_commands = universe.categories["command"].keys() sorted_commands.sort() for item in sorted_commands: - description = universe.categories["command"][item].get("description") - if not description: - description = "(no short description provided)" - output += " $(grn)" + item + "$(nrm) - " + description + "$(eol)" + command = universe.categories["command"][item] + if user.can_run(command): + description = command.get("description") + if not description: + description = "(no short description provided)" + if command.getboolean("administrative"): output += " $(red)" + else: output += " $(grn)" + output += item + "$(nrm) - " + description + "$(eol)" output += "$(eol)Enter \"help COMMAND\" for help on a command named \"COMMAND\"." # send the accumulated output to the user user.send(output) -def command_say(user, command="", parameters=""): +def command_say(user, parameters): """Speak to others in the same room.""" # check for replacement macros @@ -1076,7 +1127,7 @@ def command_say(user, command="", parameters=""): for facet in universe.categories["internal"]["language"].facets(): if facet.startswith("punctuation_"): action = facet.split("_")[1] - for mark in universe.categories["internal"]["language"].get(facet).split(): + for mark in universe.categories["internal"]["language"].getlist(facet): actions[mark] = action # match the punctuation used, if any, to an action @@ -1092,50 +1143,126 @@ def command_say(user, command="", parameters=""): message += default_punctuation # capitalize a list of words within the message - capitalize = universe.categories["internal"]["language"].get("capitalize").split() - for word in capitalize: + capitalize_words = universe.categories["internal"]["language"].getlist("capitalize_words") + for word in capitalize_words: message = message.replace(" " + word + " ", " " + word.capitalize() + " ") # tell the room # TODO: we won't be using broadcast once there are actual rooms - broadcast(user.account.get("name") + " " + action + "s, \"" + message + "\"") + broadcast(user.avatar.get("name") + " " + action + "s, \"" + message + "\"") # there was no message else: user.send("What do you want to say?") -def command_show(user, command="", parameters=""): +def command_show(user, parameters): """Show program data.""" - if parameters == "avatars": - message = "These are the avatars managed by your account:$(eol)" - avatars = user.list_avatar_names() - avatars.sort() - for avatar in avatars: message += "$(eol) $(grn)" + avatar + "$(nrm)" - elif parameters == "files": - message = "These are the current files containing the universe:$(eol)" - keys = universe.files.keys() - keys.sort() - for key in keys: message += "$(eol) $(grn)" + key + "$(nrm)" - elif parameters == "universe": - message = "These are the current elements in the universe:$(eol)" - keys = universe.contents.keys() - keys.sort() - for key in keys: message += "$(eol) $(grn)" + key + "$(nrm)" - elif parameters == "time": - message = universe.categories["internal"]["counters"].get("elapsed") + " increments elapsed since the world was created." - elif parameters: message = "I don't know what \"" + parameters + "\" is." - else: message = "What do you want to show?" + message = "" + if parameters.find(" ") < 1: + if parameters == "time": + message = universe.categories["internal"]["counters"].get("elapsed") + " increments elapsed since the world was created." + elif parameters == "categories": + message = "These are the element categories:$(eol)" + categories = universe.categories.keys() + categories.sort() + for category in categories: message += "$(eol) $(grn)" + category + "$(nrm)" + elif parameters == "files": + message = "These are the current files containing the universe:$(eol)" + filenames = universe.files.keys() + filenames.sort() + for filename in filenames: message += "$(eol) $(grn)" + filename + "$(nrm)" + else: message = "" + else: + arguments = parameters.split() + if arguments[0] == "category": + if arguments[1] in universe.categories: + message = "These are the elements in the \"" + arguments[1] + "\" category:$(eol)" + elements = universe.categories[arguments[1]].keys() + elements.sort() + for element in elements: + message += "$(eol) $(grn)" + universe.categories[arguments[1]][element].key + "$(nrm)" + elif arguments[0] == "element": + if arguments[1] in universe.contents: + message = "These are the properties of the \"" + arguments[1] + "\" element:$(eol)" + element = universe.contents[arguments[1]] + facets = element.facets() + facets.sort() + for facet in facets: + message += "$(eol) $(grn)" + facet + ": $(red)" + escape_macros(element.get(facet)) + "$(nrm)" + if not message: + if parameters: message = "I don't know what \"" + parameters + "\" is." + else: message = "What do you want to show?" + user.send(message) + +def command_create(user, parameters): + """Create an element if it does not exist.""" + if not parameters: message = "You must at least specify an element to create." + else: + arguments = parameters.split() + if len(arguments) == 1: arguments.append("") + if len(arguments) == 2: + element, filename = arguments + if element in universe.contents: message = "The \"" + element + "\" element already exists." + else: + message = "You create \"" + element + "\" within the universe." + logline = user.account.get("name") + " created an element: " + element + if filename: + logline += " in file " + filename + if filename not in universe.files: + message += " Warning: \"" + filename + "\" is not yet included in any other file and will not be read on startup unless this is remedied." + Element(element, universe, filename) + log(logline) + elif len(arguments) > 2: message = "You can only specify an element and a filename." + user.send(message) + +def command_destroy(user, parameters): + """Destroy an element if it exists.""" + if not parameters: message = "You must specify an element to destroy." + else: + if parameters not in universe.contents: message = "The \"" + parameters + "\" element does not exist." + else: + universe.contents[parameters].destroy() + message = "You destroy \"" + parameters + "\" within the universe." + log(user.account.get("name") + " destroyed an element: " + parameters) + user.send(message) + +def command_set(user, parameters): + """Set a facet of an element.""" + if not parameters: message = "You must specify an element, a facet and a value." + else: + arguments = parameters.split(" ", 2) + if len(arguments) == 1: message = "What facet of element \"" + arguments[0] + "\" would you like to set?" + elif len(arguments) == 2: message = "What value would you like to set for the \"" + arguments[1] + "\" facet of the \"" + arguments[0] + "\" element?" + else: + element, facet, value = arguments + if element not in universe.contents: message = "The \"" + element + "\" element does not exist." + else: + universe.contents[element].set(facet, value) + message = "You have successfully (re)set the \"" + facet + "\" facet of element \"" + element + "\". Try \"show element " + element + "\" for verification." + user.send(message) + +def command_delete(user, parameters): + """Delete a facet from an element.""" + if not parameters: message = "You must specify an element and a facet." + else: + arguments = parameters.split(" ") + if len(arguments) == 1: message = "What facet of element \"" + arguments[0] + "\" would you like to delete?" + elif len(arguments) != 2: message = "You may only specify an element and a facet." + else: + element, facet = arguments + if element not in universe.contents: message = "The \"" + element + "\" element does not exist." + elif facet not in universe.contents[element].facets(): message = "The \"" + element + "\" element has no \"" + facet + "\" facet." + else: + universe.contents[element].delete(facet) + message = "You have successfully deleted the \"" + facet + "\" facet of element \"" + element + "\". Try \"show element " + element + "\" for verification." user.send(message) -def command_error(user, command="", parameters=""): +def command_error(user, input_data): """Generic error for an unrecognized command word.""" # 90% of the time use a generic error if randrange(10): - message = "I'm not sure what \"" + command - if parameters: - message += " " + parameters - message += "\" means..." + message = "I'm not sure what \"" + input_data + "\" means..." # 10% of the time use the classic diku error else: