1 """User command functions for the mudpy engine."""
3 # Copyright (c) 2004-2019 mudpy authors. Permission to use, copy,
4 # modify, and distribute this software is granted under terms
5 # provided in the LICENSE file distributed with this software.
15 def chat(actor, parameters):
16 """Toggle chat mode."""
17 mode = actor.get("mode")
19 actor.set("mode", "chat")
20 actor.send("Entering chat mode (use $(grn)!chat$(nrm) to exit).")
22 actor.remove_facet("mode")
23 actor.send("Exiting chat mode.")
25 actor.send("Sorry, but you're already busy with something else!")
28 def create(actor, parameters):
29 """Create an element if it does not exist."""
31 message = "You must at least specify an element to create."
35 arguments = parameters.split()
36 if len(arguments) == 1:
38 if len(arguments) == 2:
39 element, filename = arguments
40 if element in actor.universe.contents:
41 message = 'The "' + element + '" element already exists.'
43 message = ('You create "' +
44 element + '" within the universe.')
45 logline = actor.owner.account.get(
47 ) + " created an element: " + element
49 logline += " in file " + filename
50 if filename not in actor.universe.files:
52 ' Warning: "' + filename + '" is not yet '
53 "included in any other file and will not be read "
54 "on startup unless this is remedied.")
55 mudpy.misc.Element(element, actor.universe, filename)
56 mudpy.misc.log(logline, 6)
57 elif len(arguments) > 2:
58 message = "You can only specify an element and a filename."
62 def delete(actor, parameters):
63 """Delete a facet from an element."""
65 message = "You must specify an element and a facet."
67 arguments = parameters.split(" ")
68 if len(arguments) == 1:
69 message = ('What facet of element "' + arguments[0]
70 + '" would you like to delete?')
71 elif len(arguments) != 2:
72 message = "You may only specify an element and a facet."
74 element, facet = arguments
75 if element not in actor.universe.contents:
76 message = 'The "' + element + '" element does not exist.'
77 elif facet not in actor.universe.contents[element].facets():
78 message = ('The "' + element + '" element has no "' + facet
81 actor.universe.contents[element].remove_facet(facet)
82 message = ('You have successfully deleted the "' + facet
83 + '" facet of element "' + element
84 + '". Try "show element ' +
85 element + '" for verification.')
89 def destroy(actor, parameters):
90 """Destroy an element if it exists."""
93 message = "You must specify an element to destroy."
95 if parameters not in actor.universe.contents:
96 message = 'The "' + parameters + '" element does not exist.'
98 actor.universe.contents[parameters].destroy()
99 message = ('You destroy "' + parameters
100 + '" within the universe.')
102 actor.owner.account.get(
104 ) + " destroyed an element: " + parameters,
110 def error(actor, input_data):
111 """Generic error for an unrecognized command word."""
113 # 90% of the time use a generic error
114 if random.randrange(10):
115 message = '''I'm not sure what "''' + input_data + '''" means...'''
117 # 10% of the time use the classic diku error
119 message = "Arglebargle, glop-glyf!?!"
121 # try to send the error message, and log if we can't
126 'Sending a command error to user %s raised exception...\n%s' % (
127 actor.owner.account.get("name"), traceback.format_exc()))
130 def halt(actor, parameters):
131 """Halt the world."""
134 # see if there's a message or use a generic one
136 message = "Halting: " + parameters
138 message = "User " + actor.owner.account.get(
140 ) + " halted the world."
143 mudpy.misc.broadcast(message, add_prompt=False)
144 mudpy.misc.log(message, 8)
146 # set a flag to terminate the world
147 actor.universe.terminate_flag = True
150 def help(actor, parameters):
151 """List available commands and provide help for commands."""
153 # did the user ask for help on a specific command word?
154 if parameters and actor.owner:
156 # is the command word one for which we have data?
157 command = mudpy.misc.find_command(parameters)
159 # only for allowed commands
160 if actor.can_run(command):
162 # add a description if provided
163 description = command.get("description")
165 description = "(no short description provided)"
166 if command.get("administrative"):
170 output = "%s%s$(nrm) - %s$(eol)$(eol)" % (
171 output, command.subkey, description)
173 # add the help text if provided
174 help_text = command.get("help")
176 help_text = "No help is provided for this command."
179 # list related commands
180 see_also = command.get("see_also")
183 for item in see_also:
184 if item in actor.universe.groups["command"]:
185 command = actor.universe.groups["command"][item]
186 if actor.can_run(command):
188 really_see_also += ", "
189 if command.get("administrative"):
190 really_see_also += "$(red)"
192 really_see_also += "$(grn)"
193 really_see_also += item + "$(nrm)"
195 output += "$(eol)$(eol)See also: " + really_see_also
197 # no data for the requested command word
199 output = "That is not an available command."
201 # no specific command word was indicated
205 output = ("These are the commands available to you [brackets indicate "
206 "optional portion]:$(eol)$(eol)")
208 # list command names in alphabetical order
209 for command_name, command in sorted(
210 actor.universe.groups["command"].items()):
212 # skip over disallowed commands
213 if actor.can_run(command):
215 # start incrementing substrings
216 for position in range(1, len(command_name) + 1):
218 # we've found our shortest possible abbreviation
219 candidate = mudpy.misc.find_command(
220 command_name[:position])
222 if candidate.subkey == command_name:
224 except AttributeError:
227 # use square brackets to indicate optional part of command name
228 if position < len(command_name):
229 abbrev = "%s[%s]" % (
230 command_name[:position], command_name[position:])
232 abbrev = command_name
234 # supply a useful default if the short description is missing
235 description = command.get(
236 "description", "(no short description provided)")
238 # administrative command names are in red, others in green
239 if command.get("administrative"):
244 # format the entry for this command
245 output = "%s $(%s)%s$(nrm) - %s$(eol)" % (
246 output, color, abbrev, description)
248 # add a footer with instructions on getting additional information
249 output = ('%s $(eol)Enter "help COMMAND" for help on a command named '
250 '"COMMAND".' % output)
252 # send the accumulated output to the user
256 def look(actor, parameters):
259 actor.send("You can't look at or in anything yet.")
261 actor.look_at(actor.get("location"))
264 def move(actor, parameters):
265 """Move the avatar in a given direction."""
266 if parameters in actor.universe.contents[actor.get("location")].portals():
267 actor.move_direction(parameters)
269 actor.send("You cannot go that way.")
272 def preferences(actor, parameters):
273 """List, view and change actor preferences."""
275 # Escape replacement macros in preferences
276 parameters = mudpy.misc.escape_macros(parameters)
279 arguments = parameters.split()
280 allowed_prefs = set()
281 user_config = actor.universe.contents.get("mudpy.user")
283 allowed_prefs.update(user_config.get("pref_allow", []))
284 if actor.owner.account.get("administrator"):
285 allowed_prefs.update(user_config.get("pref_admin", []))
287 message += "These are your current preferences:"
288 for pref in allowed_prefs:
289 message += ("$(eol) $(red)%s $(grn)%s$(nrm)"
290 % (pref, actor.owner.account.get(pref)))
291 elif arguments[0] not in allowed_prefs:
293 'Preference "%s" does not exist. Try the `preferences` command by '
294 "itself for a list of valid preferences." % arguments[0])
295 elif len(arguments) == 1:
296 message += "%s" % actor.owner.account.get(arguments[0])
299 value = " ".join(arguments[1:])
301 actor.owner.account.set(pref, value)
302 message += 'Preference "%s" set to "%s".' % (pref, value)
305 'Preference "%s" cannot be set to type "%s".' % (
310 def quit(actor, parameters):
311 """Leave the world and go back to the main menu."""
313 actor.owner.state = "main_utility"
314 actor.owner.deactivate_avatar()
317 def reload(actor, parameters):
318 """Reload all code modules, configs and data."""
321 # let the user know and log
322 actor.send("Reloading all code modules, configs and data.")
325 actor.owner.account.get("name") + " reloaded the world.",
329 # set a flag to reload
330 actor.universe.reload_flag = True
333 def say(actor, parameters):
334 """Speak to others in the same area."""
336 # check for replacement macros and escape them
337 parameters = mudpy.misc.escape_macros(parameters)
339 # if the message is wrapped in quotes, remove them and leave contents
341 if parameters.startswith('"') and parameters.endswith('"'):
342 message = parameters[1:-1]
345 # otherwise, get rid of stray quote marks on the ends of the message
347 message = parameters.strip('''"'`''')
350 # the user entered a message
353 # match the punctuation used, if any, to an action
354 if "mudpy.linguistic" in actor.universe.contents:
355 actions = actor.universe.contents[
356 "mudpy.linguistic"].get("actions", {})
357 default_punctuation = (actor.universe.contents[
358 "mudpy.linguistic"].get("default_punctuation", "."))
361 default_punctuation = "."
364 # reverse sort punctuation options so the longest match wins
365 for mark in sorted(actions.keys(), reverse=True):
366 if not literal and message.endswith(mark):
367 action = actions[mark]
370 # add punctuation if needed
372 action = actions[default_punctuation]
374 literal or unicodedata.category(message[-1]) == "Po"
376 message += default_punctuation
378 # failsafe checks to avoid unwanted reformatting and null strings
379 if message and not literal:
381 # decapitalize the first letter to improve matching
382 message = message[0].lower() + message[1:]
384 # iterate over all words in message, replacing typos
385 if "mudpy.linguistic" in actor.universe.contents:
386 typos = actor.universe.contents[
387 "mudpy.linguistic"].get("typos", {})
390 words = message.split()
391 for index in range(len(words)):
393 while unicodedata.category(word[0]) == "Po":
395 while unicodedata.category(word[-1]) == "Po":
397 if word in typos.keys():
398 words[index] = words[index].replace(word, typos[word])
399 message = " ".join(words)
401 # capitalize the first letter
402 message = message[0].upper() + message[1:]
406 actor.echo_to_location(
407 actor.get("name") + " " + action + 's, "' + message + '"'
409 actor.send("You " + action + ', "' + message + '"')
411 # there was no message
413 actor.send("What do you want to say?")
416 def c_set(actor, parameters):
417 """Set a facet of an element."""
419 message = "You must specify an element, a facet and a value."
421 arguments = parameters.split(" ", 2)
422 if len(arguments) == 1:
423 message = ('What facet of element "' + arguments[0]
424 + '" would you like to set?')
425 elif len(arguments) == 2:
426 message = ('What value would you like to set for the "' +
427 arguments[1] + '" facet of the "' + arguments[0]
430 element, facet, value = arguments
431 if element not in actor.universe.contents:
432 message = 'The "' + element + '" element does not exist.'
435 actor.universe.contents[element].set(facet, value)
436 except PermissionError:
437 message = ('The "%s" element is kept in read-only file '
438 '"%s" and cannot be altered.' %
439 (element, actor.universe.contents[
440 element].origin.source))
442 message = ('Value "%s" of type "%s" cannot be coerced '
443 'to the correct datatype for facet "%s".' %
444 (value, type(value), facet))
446 message = ('You have successfully (re)set the "' + facet
447 + '" facet of element "' + element
448 + '". Try "show element ' +
449 element + '" for verification.')
453 def show(actor, parameters):
454 """Show program data."""
456 arguments = parameters.split()
458 message = "What do you want to show?"
459 elif arguments[0] == "version":
460 message = repr(actor.universe.versions)
461 elif arguments[0] == "time":
462 message = "%s increments elapsed since the world was created." % (
463 str(actor.universe.groups["internal"]["counters"].get("elapsed")))
464 elif arguments[0] == "groups":
465 message = "These are the element groups:$(eol)"
466 groups = list(actor.universe.groups.keys())
469 message += "$(eol) $(grn)" + group + "$(nrm)"
470 elif arguments[0] == "files":
471 message = "These are the current files containing the universe:$(eol)"
472 filenames = sorted(actor.universe.files)
473 for filename in filenames:
474 if actor.universe.files[filename].is_writeable():
478 message += ("$(eol) $(red)(%s) $(grn)%s$(nrm)" %
480 if actor.universe.files[filename].flags:
481 message += (" $(yel)[%s]$(nrm)" %
482 ",".join(actor.universe.files[filename].flags))
483 elif arguments[0] == "group":
484 if len(arguments) != 2:
485 message = "You must specify one group."
486 elif arguments[1] in actor.universe.groups:
487 message = ('These are the elements in the "' + arguments[1]
491 actor.universe.groups[arguments[1]][x].key
492 ) for x in actor.universe.groups[arguments[1]].keys()
495 for element in elements:
496 message += "$(eol) $(grn)" + element + "$(nrm)"
498 message = 'Group "' + arguments[1] + '" does not exist.'
499 elif arguments[0] == "file":
500 if len(arguments) != 2:
501 message = "You must specify one file."
502 elif arguments[1] in actor.universe.files:
503 message = ('These are the nodes in the "' + arguments[1]
505 elements = sorted(actor.universe.files[arguments[1]].data)
506 for element in elements:
507 message += "$(eol) $(grn)" + element + "$(nrm)"
509 message = 'File "%s" does not exist.' % arguments[1]
510 elif arguments[0] == "element":
511 if len(arguments) != 2:
512 message = "You must specify one element."
513 elif arguments[1].strip(".") in actor.universe.contents:
514 element = actor.universe.contents[arguments[1].strip(".")]
515 message = ('These are the properties of the "' + arguments[1]
516 + '" element (in "' + element.origin.source
518 facets = element.facets()
519 for facet in sorted(facets):
520 message += ("$(eol) $(grn)%s: $(red)%s$(nrm)" %
521 (facet, str(facets[facet])))
523 message = 'Element "' + arguments[1] + '" does not exist.'
524 elif arguments[0] == "result":
525 if len(arguments) < 2:
526 message = "You need to specify an expression."
529 message = repr(eval(" ".join(arguments[1:])))
530 except Exception as e:
531 message = ("$(red)Your expression raised an exception...$(eol)"
532 "$(eol)$(bld)%s$(nrm)" % e)
533 elif arguments[0] == "log":
534 if len(arguments) == 4:
535 if re.match(r"^\d+$", arguments[3]) and int(arguments[3]) >= 0:
536 stop = int(arguments[3])
541 if len(arguments) >= 3:
542 if re.match(r"^\d+$", arguments[2]) and int(arguments[2]) > 0:
543 start = int(arguments[2])
548 if len(arguments) >= 2:
549 if (re.match(r"^\d+$", arguments[1])
550 and 0 <= int(arguments[1]) <= 9):
551 level = int(arguments[1])
554 elif 0 <= actor.owner.account.get("loglevel", 0) <= 9:
555 level = actor.owner.account.get("loglevel", 0)
558 if level > -1 and start > -1 and stop > -1:
559 message = mudpy.misc.get_loglines(level, start, stop)
561 message = ("When specified, level must be 0-9 (default 1), "
562 "start and stop must be >=1 (default 10 and 1).")
564 message = '''I don't know what "''' + parameters + '" is.'