1 """Command objects for the MUFF Engine"""
3 # Copyright (c) 2005 mudpy, Jeremy Stanley <fungi@yuggoth.org>, all rights reserved.
4 # Licensed per terms in the LICENSE file distributed with this software.
6 # command data like descriptions, help text, limits, et cetera, are stored in
7 # ini-style configuration files supported by the ConfigParser module
10 # md5 hashing is used for verification of account passwords
13 # the os module is used to we can get a directory listing and build lists of
14 # multiple config files in one directory
17 # the random module is useful for creating random conditional output
20 # string.split is used extensively to tokenize user input (break up command
21 # names and parameters)
24 # bit of a hack to load all modules in the muff package
26 for module in muff.__all__:
27 exec("import " + module)
29 # does the files:commands setting exist yet?
31 if muffconf.get("files", "commands"): pass
33 # if not, reload the muffconf module
34 except AttributeError:
37 # now we can safely nab the command path setting and build a list of data files
38 command_path = muffconf.get("files", "commands")
39 command_files_index = ConfigParser.SafeConfigParser()
40 command_files_index.read(command_path + "/index")
42 for each_file in command_files_index.get("index", "files").split():
43 command_files.append(command_path + "/" + each_file)
45 # read the command data files
46 command_data = ConfigParser.SafeConfigParser()
47 command_data.read(command_files)
49 # this creates a list of commands mentioned in the data files
50 command_list = command_data.sections()
52 def handle_user_input(user):
53 """The main handler, branches to a state-specific handler."""
55 # check to make sure the state is expected, then call that handler
56 exec("handler_" + user.state.replace(" ", "_") + "(user)")
58 # since we got input, flag that the menu/prompt needs to be redisplayed
59 user.menu_seen = False
61 def handler_entering_account_name(user):
62 """Handle the login account name."""
64 # get the next waiting line of input
65 input_data = user.input_queue.pop(0)
67 # did the user enter anything?
70 # keep only the first word and convert to lower-case
71 user.proposed_name = string.split(input_data)[0].lower()
73 # if we have a password hash, time to request a password
74 if user.get_passhash():
75 user.state = "checking password"
77 # otherwise, this could be a brand new user
79 user.name = user.proposed_name
80 user.proposed_name = None
82 muffmisc.log("New user: " + user.name)
83 user.state = "checking new account name"
85 # if the user entered nothing for a name, then buhbye
87 user.state = "disconnecting"
89 def handler_checking_password(user):
90 """Handle the login account password."""
92 # get the next waiting line of input
93 input_data = user.input_queue.pop(0)
95 # does the hashed input equal the stored hash?
96 if md5.new(user.proposed_name + input_data).hexdigest() == user.passhash:
98 # if so, set the username and load from cold storage
99 # TODO: branch to character creation and selection menus
100 user.name = user.proposed_name
101 del(user.proposed_name)
102 if not user.replace_old_connections():
105 user.state = "active"
107 # if at first your hashes don't match, try, try again
108 elif user.password_tries < muffconf.getint("general", "password_tries"):
109 user.password_tries += 1
110 user.error = "incorrect"
112 # we've exceeded the maximum number of password failures, so disconnect
114 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
115 user.state = "disconnecting"
117 def handler_disconnecting(user):
118 """Waiting for the user's connection to close."""
121 def handler_disconnecting_duplicates(user):
122 """Waiting for duplicate connections to close."""
125 def handler_checking_new_account_name(user):
126 """Handle input for the new user menu."""
128 # get the next waiting line of input
129 input_data = user.input_queue.pop(0)
131 # if there's input, take the first character and lowercase it
133 choice = input_data.lower()[0]
135 # if there's no input, use the default
137 choice = muffmenu.get_default(user)
139 # user selected to disconnect
141 user.state = "disconnecting"
143 # go back to the login screen
145 user.state = "entering account name"
147 # new user, so ask for a password
149 user.state = "entering new password"
151 # user entered a non-existent option
153 user.error = "default"
155 def handler_entering_new_password(user):
156 """Handle a new password entry."""
158 # get the next waiting line of input
159 input_data = user.input_queue.pop(0)
161 # make sure the password is strong--at least one upper, one lower and
162 # one digit, seven or more characters in length
163 if len(input_data) > 6 and len(filter(lambda x: x>="0" and x<="9", input_data)) and len(filter(lambda x: x>="A" and x<="Z", input_data)) and len(filter(lambda x: x>="a" and x<="z", input_data)):
165 # hash and store it, then move on to verification
166 user.passhash = md5.new(user.name + input_data).hexdigest()
167 user.state = "verifying new password"
169 # the password was weak, try again if you haven't tried too many times
170 elif user.password_tries < muffconf.getint("general", "password_tries"):
171 user.password_tries += 1
174 # too many tries, so adios
176 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
177 user.state = "disconnecting"
179 def handler_verifying_new_password(user):
180 """Handle the re-entered new password for verification."""
182 # get the next waiting line of input
183 input_data = user.input_queue.pop(0)
185 # hash the input and match it to storage
186 if md5.new(user.name + input_data).hexdigest() == user.passhash:
190 # the hashes matched, so go active
191 # TODO: branch to character creation and selection menus
192 if not user.replace_old_connections(): user.state = "active"
194 # go back to entering the new password as long as you haven't tried
196 elif user.password_tries < muffconf.getint("general", "password_tries"):
197 user.password_tries += 1
198 user.error = "differs"
199 user.state = "entering new password"
201 # otherwise, sayonara
203 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
204 user.state = "disconnecting"
206 def handler_active(user):
207 """Handle input for active users."""
209 # get the next waiting line of input
210 input_data = user.input_queue.pop(0)
212 # split out the command (first word) and parameters (everything else)
214 inputlist = string.split(input_data, None, 1)
215 command = inputlist[0]
219 parameters = inputlist[1]
224 # lowercase the command
225 command = command.lower()
227 # the command matches a command word for which we have data
228 if command in command_list: exec("command_" + command + "(user, command, parameters)")
230 # no data matching the entered command word
231 elif command: command_error(user, command, parameters)
233 def command_halt(user, command="", parameters=""):
234 """Halt the world."""
236 # see if there's a message or use a generic one
237 if parameters: message = "Halting: " + parameters
238 else: message = "User " + user.name + " halted the world."
241 muffmisc.broadcast(message)
242 muffmisc.log(message)
244 # set a flag to terminate the world
245 muffvars.terminate_world = True
247 def command_reload(user, command="", parameters=""):
248 """Reload all code modules, configs and data."""
250 # let the user know and log
251 user.send("Reloading all code modules, configs and data.")
252 muffmisc.log("User " + user.name + " reloaded the world.")
254 # set a flag to reload
255 muffvars.reload_modules = True
257 def command_quit(user, command="", parameters=""):
258 """Quit the world."""
259 user.state = "disconnecting"
261 def command_time(user, command="", parameters=""):
262 """Show the current world time in elapsed increments."""
263 user.send(muffmisc.repr_long(muffmisc.getlong(muffvars.variable_data,
264 "time", "elapsed")) + " increments elapsed since the world was created.")
266 def command_help(user, command="", parameters=""):
267 """List available commands and provide help for commands."""
269 # did the user ask for help on a specific command word?
272 # is the command word one for which we have data?
273 if parameters in command_list:
275 # add a description if provided
277 description = command_data.get(parameters, "description")
279 description = "(no short description provided)"
280 output = "$(grn)" + parameters + "$(nrm) - " + command_data.get(parameters, "description") + "$(eol)$(eol)"
282 # add the help text if provided
284 help_text = command_data.get(parameters, "help")
286 help_text = "No help is provided for this command."
289 # no data for the requested command word
291 output = "That is not an available command."
293 # no specific command word was indicated
296 # give a sorted list of commands with descriptions if provided
297 output = "These are the commands available to you:$(eol)$(eol)"
298 sorted_commands = command_list
299 sorted_commands.sort()
300 for item in sorted_commands:
302 description = command_data.get(item, "description")
304 description = "(no short description provided)"
305 output += " $(grn)" + item + "$(nrm) - " + command_data.get(item, "description") + "$(eol)"
306 output += "$(eol)Enter \"help COMMAND\" for help on a command named \"COMMAND\"."
308 # send the accumulated output to the user
311 def command_say(user, command="", parameters=""):
312 """Speak to others in the same room."""
314 # check for replacement macros
315 if muffmisc.replace_macros(user, parameters, True) != parameters:
316 user.send("You cannot speak $_(replacement macros).")
318 # the user entered a message
321 # get rid of quote marks on the ends of the message and
322 # capitalize the first letter
323 message = parameters.strip("\"'`").capitalize()
325 # a dictionary of punctuation:action pairs
327 for option in muffconf.config_data.options("language"):
328 if option.startswith("punctuation_"):
329 action = option.split("_")[1]
330 for mark in muffconf.config_data.get("language", option).split():
331 actions[mark] = action
333 # set the default action
334 action = actions[muffconf.config_data.get("language", "default_punctuation")]
336 # match the punctuation used, if any, to an action
337 default_punctuation = muffconf.config_data.get("language", "default_punctuation")
338 for mark in actions.keys():
339 if message.endswith(mark) and mark != default_punctuation:
340 action = actions[mark]
343 # if the action is default and there is no mark, add one
344 if action == actions[default_punctuation] and not message.endswith(default_punctuation):
345 message += default_punctuation
347 # capitalize a list of words within the message
348 capitalize = muffconf.get("language", "capitalize").split()
349 for word in capitalize:
350 message = message.replace(" " + word + " ", " " + word.capitalize() + " ")
353 # TODO: we won't be using broadcast once there are actual rooms
354 muffmisc.broadcast(user.name + " " + action + "s, \"" + message + "\"")
356 # there was no message
358 user.send("What do you want to say?")
360 def command_error(user, command="", parameters=""):
361 """Generic error for an unrecognized command word."""
363 # 90% of the time use a generic error
364 if random.randrange(10):
365 message = "I'm not sure what \"" + command
367 message += " " + parameters
368 message += "\" means..."
370 # 10% of the time use the classic diku error
372 message = "Arglebargle, glop-glyf!?!"
374 # send the error message