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!")
29 def create(actor, parameters):
30 """Create an element if it does not exist."""
32 message = "You must at least specify an element to create."
36 arguments = parameters.split()
37 if len(arguments) == 1:
39 if len(arguments) == 2:
40 element, filename = arguments
41 if element in actor.universe.contents:
42 message = 'The "' + element + '" element already exists.'
44 message = ('You create "' +
45 element + '" within the universe.')
46 logline = actor.owner.account.get(
48 ) + " created an element: " + element
50 logline += " in file " + filename
51 if filename not in actor.universe.files:
53 ' Warning: "' + filename + '" is not yet '
54 "included in any other file and will not be read "
55 "on startup unless this is remedied.")
56 mudpy.misc.Element(element, actor.universe, filename)
57 mudpy.misc.log(logline, 6)
58 elif len(arguments) > 2:
59 message = "You can only specify an element and a filename."
64 def delete(actor, parameters):
65 """Delete a facet from an element."""
67 message = "You must specify an element and a facet."
69 arguments = parameters.split(" ")
70 if len(arguments) == 1:
71 message = ('What facet of element "' + arguments[0]
72 + '" would you like to delete?')
73 elif len(arguments) != 2:
74 message = "You may only specify an element and a facet."
76 element, facet = arguments
77 if element not in actor.universe.contents:
78 message = 'The "' + element + '" element does not exist.'
79 elif facet not in actor.universe.contents[element].facets():
80 message = ('The "' + element + '" element has no "' + facet
83 actor.universe.contents[element].remove_facet(facet)
84 message = ('You have successfully deleted the "' + facet
85 + '" facet of element "' + element
86 + '". Try "show element ' +
87 element + '" for verification.')
92 def destroy(actor, parameters):
93 """Destroy an element if it exists."""
96 message = "You must specify an element to destroy."
98 if parameters not in actor.universe.contents:
99 message = 'The "' + parameters + '" element does not exist.'
101 actor.universe.contents[parameters].destroy()
102 message = ('You destroy "' + parameters
103 + '" within the universe.')
105 actor.owner.account.get(
107 ) + " destroyed an element: " + parameters,
114 def error(actor, input_data):
115 """Generic error for an unrecognized command word."""
117 # 90% of the time use a generic error
118 # Whitelist the random.randrange() call in bandit since it's not used for
119 # security/cryptographic purposes
120 if random.randrange(10): # nosec
121 message = '''I'm not sure what "''' + input_data + '''" means...'''
123 # 10% of the time use the classic diku error
125 message = "Arglebargle, glop-glyf!?!"
127 # try to send the error message, and log if we can't
132 'Sending a command error to user %s raised exception...\n%s' % (
133 actor.owner.account.get("name"), traceback.format_exc()))
137 def halt(actor, parameters):
138 """Halt the world."""
141 # see if there's a message or use a generic one
143 message = "Halting: " + parameters
145 message = "User " + actor.owner.account.get(
147 ) + " halted the world."
150 mudpy.misc.broadcast(message, add_prompt=False)
151 mudpy.misc.log(message, 8)
153 # set a flag to terminate the world
154 actor.universe.terminate_flag = True
158 def help(actor, parameters):
159 """List available commands and provide help for commands."""
161 # did the user ask for help on a specific command word?
162 if parameters and actor.owner:
164 # is the command word one for which we have data?
165 command = mudpy.misc.find_command(parameters)
167 # only for allowed commands
168 if actor.can_run(command):
170 # add a description if provided
171 description = command.get("description")
173 description = "(no short description provided)"
174 if command.get("administrative"):
178 output = "%s%s$(nrm) - %s$(eol)$(eol)" % (
179 output, command.subkey, description)
181 # add the help text if provided
182 help_text = command.get("help")
184 help_text = "No help is provided for this command."
187 # list related commands
188 see_also = command.get("see_also")
191 for item in see_also:
192 if item in actor.universe.groups["command"]:
193 command = actor.universe.groups["command"][item]
194 if actor.can_run(command):
196 really_see_also += ", "
197 if command.get("administrative"):
198 really_see_also += "$(red)"
200 really_see_also += "$(grn)"
201 really_see_also += item + "$(nrm)"
203 output += "$(eol)$(eol)See also: " + really_see_also
205 # no data for the requested command word
207 output = "That is not an available command."
209 # no specific command word was indicated
213 output = ("These are the commands available to you [brackets indicate "
214 "optional portion]:$(eol)$(eol)")
216 # list command names in alphabetical order
217 for command_name, command in sorted(
218 actor.universe.groups["command"].items()):
220 # skip over disallowed commands
221 if actor.can_run(command):
223 # start incrementing substrings
224 for position in range(1, len(command_name) + 1):
226 # we've found our shortest possible abbreviation
227 candidate = mudpy.misc.find_command(
228 command_name[:position])
230 if candidate.subkey == command_name:
232 except AttributeError:
235 # use square brackets to indicate optional part of command name
236 if position < len(command_name):
237 abbrev = "%s[%s]" % (
238 command_name[:position], command_name[position:])
240 abbrev = command_name
242 # supply a useful default if the short description is missing
243 description = command.get(
244 "description", "(no short description provided)")
246 # administrative command names are in red, others in green
247 if command.get("administrative"):
252 # format the entry for this command
253 output = "%s $(%s)%s$(nrm) - %s$(eol)" % (
254 output, color, abbrev, description)
256 # add a footer with instructions on getting additional information
257 output = ('%s $(eol)Enter "help COMMAND" for help on a command named '
258 '"COMMAND".' % output)
260 # send the accumulated output to the user
265 def look(actor, parameters):
268 actor.send("You can't look at or in anything yet.")
270 actor.look_at(actor.get("location"))
274 def move(actor, parameters):
275 """Move the avatar in a given direction."""
276 for portal in sorted(
277 actor.universe.contents[actor.get("location")].portals()):
278 if portal.startswith(parameters):
279 actor.move_direction(portal)
281 actor.send("You cannot go that way.")
285 def preferences(actor, parameters):
286 """List, view and change actor preferences."""
288 # Escape replacement macros in preferences
289 parameters = mudpy.misc.escape_macros(parameters)
292 arguments = parameters.split()
293 allowed_prefs = set()
295 user_config = actor.universe.contents.get("mudpy.user")
297 base_prefs = user_config.get("pref_allow", [])
298 allowed_prefs.update(base_prefs)
299 if actor.owner.account.get("administrator"):
300 allowed_prefs.update(user_config.get("pref_admin", []))
302 message += "These are your current preferences:"
304 # color-code base and admin prefs
305 for pref in sorted(allowed_prefs):
306 if pref in base_prefs:
310 message += ("$(eol) $(%s)%s$(nrm) - %s" % (
311 color, pref, actor.owner.account.get(pref, "<not set>")))
313 elif arguments[0] not in allowed_prefs:
315 'Preference "%s" does not exist. Try the `preferences` command by '
316 "itself for a list of valid preferences." % arguments[0])
317 elif len(arguments) == 1:
318 message += "%s" % actor.owner.account.get(arguments[0], "<not set>")
321 value = " ".join(arguments[1:])
323 actor.owner.account.set(pref, value)
324 message += 'Preference "%s" set to "%s".' % (pref, value)
327 'Preference "%s" cannot be set to type "%s".' % (
333 def quit(actor, parameters):
334 """Leave the world and go back to the main menu."""
336 actor.owner.state = "main_utility"
337 actor.owner.deactivate_avatar()
341 def reload(actor, parameters):
342 """Reload all code modules, configs and data."""
345 # let the user know and log
346 actor.send("Reloading all code modules, configs and data.")
349 actor.owner.account.get("name") + " reloaded the world.",
353 # set a flag to reload
354 actor.universe.reload_flag = True
358 def say(actor, parameters):
359 """Speak to others in the same area."""
361 # check for replacement macros and escape them
362 parameters = mudpy.misc.escape_macros(parameters)
364 # if the message is wrapped in quotes, remove them and leave contents
366 if parameters.startswith('"') and parameters.endswith('"'):
367 message = parameters[1:-1]
370 # otherwise, get rid of stray quote marks on the ends of the message
372 message = parameters.strip('''"'`''')
375 # the user entered a message
378 # match the punctuation used, if any, to an action
379 if "mudpy.linguistic" in actor.universe.contents:
380 actions = actor.universe.contents[
381 "mudpy.linguistic"].get("actions", {})
382 default_punctuation = (actor.universe.contents[
383 "mudpy.linguistic"].get("default_punctuation", "."))
386 default_punctuation = "."
389 # reverse sort punctuation options so the longest match wins
390 for mark in sorted(actions.keys(), reverse=True):
391 if not literal and message.endswith(mark):
392 action = actions[mark]
395 # add punctuation if needed
397 action = actions[default_punctuation]
399 literal or unicodedata.category(message[-1]) == "Po"
401 message += default_punctuation
403 # failsafe checks to avoid unwanted reformatting and null strings
404 if message and not literal:
406 # decapitalize the first letter to improve matching
407 message = message[0].lower() + message[1:]
409 # iterate over all words in message, replacing typos
410 if "mudpy.linguistic" in actor.universe.contents:
411 typos = actor.universe.contents[
412 "mudpy.linguistic"].get("typos", {})
415 words = message.split()
416 for index in range(len(words)):
418 while unicodedata.category(word[0]) == "Po":
420 while unicodedata.category(word[-1]) == "Po":
422 if word in typos.keys():
423 words[index] = words[index].replace(word, typos[word])
424 message = " ".join(words)
426 # capitalize the first letter
427 message = message[0].upper() + message[1:]
431 actor.echo_to_location(
432 actor.get("name") + " " + action + 's, "' + message + '"'
434 actor.send("You " + action + ', "' + message + '"')
436 # there was no message
438 actor.send("What do you want to say?")
442 def c_set(actor, parameters):
443 """Set a facet of an element."""
445 message = "You must specify an element, a facet and a value."
447 arguments = parameters.split(" ", 2)
448 if len(arguments) == 1:
449 message = ('What facet of element "' + arguments[0]
450 + '" would you like to set?')
451 elif len(arguments) == 2:
452 message = ('What value would you like to set for the "' +
453 arguments[1] + '" facet of the "' + arguments[0]
456 element, facet, value = arguments
457 if element not in actor.universe.contents:
458 message = 'The "' + element + '" element does not exist.'
461 actor.universe.contents[element].set(facet, value)
462 except PermissionError:
463 message = ('The "%s" element is kept in read-only file '
464 '"%s" and cannot be altered.' %
465 (element, actor.universe.contents[
466 element].origin.source))
468 message = ('Value "%s" of type "%s" cannot be coerced '
469 'to the correct datatype for facet "%s".' %
470 (value, type(value), facet))
472 message = ('You have successfully (re)set the "' + facet
473 + '" facet of element "' + element
474 + '". Try "show element ' +
475 element + '" for verification.')
480 def show(actor, parameters):
481 """Show program data."""
483 arguments = parameters.split()
485 message = "What do you want to show?"
486 elif arguments[0] == "version":
487 message = repr(actor.universe.versions)
488 elif arguments[0] == "time":
489 message = "%s increments elapsed since the world was created." % (
490 str(actor.universe.groups["internal"]["counters"].get("elapsed")))
491 elif arguments[0] == "groups":
492 message = "These are the element groups:$(eol)"
493 groups = list(actor.universe.groups.keys())
496 message += "$(eol) $(grn)" + group + "$(nrm)"
497 elif arguments[0] == "files":
498 message = "These are the current files containing the universe:$(eol)"
499 filenames = sorted(actor.universe.files)
500 for filename in filenames:
501 if actor.universe.files[filename].is_writeable():
505 message += ("$(eol) $(red)(%s) $(grn)%s$(nrm)" %
507 if actor.universe.files[filename].flags:
508 message += (" $(yel)[%s]$(nrm)" %
509 ",".join(actor.universe.files[filename].flags))
510 elif arguments[0] == "group":
511 if len(arguments) != 2:
512 message = "You must specify one group."
513 elif arguments[1] in actor.universe.groups:
514 message = ('These are the elements in the "' + arguments[1]
518 actor.universe.groups[arguments[1]][x].key
519 ) for x in actor.universe.groups[arguments[1]].keys()
522 for element in elements:
523 message += "$(eol) $(grn)" + element + "$(nrm)"
525 message = 'Group "' + arguments[1] + '" does not exist.'
526 elif arguments[0] == "file":
527 if len(arguments) != 2:
528 message = "You must specify one file."
529 elif arguments[1] in actor.universe.files:
530 message = ('These are the nodes in the "' + arguments[1]
532 elements = sorted(actor.universe.files[arguments[1]].data)
533 for element in elements:
534 message += "$(eol) $(grn)" + element + "$(nrm)"
536 message = 'File "%s" does not exist.' % arguments[1]
537 elif arguments[0] == "element":
538 if len(arguments) != 2:
539 message = "You must specify one element."
540 elif arguments[1].strip(".") in actor.universe.contents:
541 element = actor.universe.contents[arguments[1].strip(".")]
542 message = ('These are the properties of the "' + arguments[1]
543 + '" element (in "' + element.origin.source
545 facets = element.facets()
546 for facet in sorted(facets):
547 message += ("$(eol) $(grn)%s: $(red)%s$(nrm)" %
548 (facet, str(facets[facet])))
550 message = 'Element "' + arguments[1] + '" does not exist.'
551 elif arguments[0] == "result":
552 if len(arguments) < 2:
553 message = "You need to specify an expression."
556 # there is no other option than to use eval() for this, since
557 # its purpose is to evaluate arbitrary expressions, so do what
558 # we can to secure it and whitelist it for bandit analysis
559 message = repr(eval( # nosec
560 " ".join(arguments[1:]),
561 {"mudpy": mudpy, "universe": actor.universe}))
562 except Exception as e:
563 message = ("$(red)Your expression raised an exception...$(eol)"
564 "$(eol)$(bld)%s$(nrm)" % e)
565 elif arguments[0] == "log":
566 if len(arguments) == 4:
567 if re.match(r"^\d+$", arguments[3]) and int(arguments[3]) >= 0:
568 stop = int(arguments[3])
573 if len(arguments) >= 3:
574 if re.match(r"^\d+$", arguments[2]) and int(arguments[2]) > 0:
575 start = int(arguments[2])
580 if len(arguments) >= 2:
581 if (re.match(r"^\d+$", arguments[1])
582 and 0 <= int(arguments[1]) <= 9):
583 level = int(arguments[1])
586 elif 0 <= actor.owner.account.get("loglevel", 0) <= 9:
587 level = actor.owner.account.get("loglevel", 0)
590 if level > -1 and start > -1 and stop > -1:
591 message = mudpy.misc.get_loglines(level, start, stop)
593 message = ("When specified, level must be 0-9 (default 1), "
594 "start and stop must be >=1 (default 10 and 1).")
596 message = '''I don't know what "''' + parameters + '" is.'