1 """User command functions for the mudpy engine."""
3 # Copyright (c) 2004-2020 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 # Allow 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 evaluate(actor, parameters):
138 """Evaluate a Python expression."""
141 message = "You need to supply a Python expression."
142 elif "__" in parameters:
143 message = "Double-underscores (__) are not allowed in expressions."
144 elif "lambda" in parameters:
145 message = "Lambda functions are not allowed in expressions."
147 # Strictly limit the allowed builtins and modules
148 eval_globals = {"__builtins__": dict()}
149 for allowed in ("dir", "globals", "len", "locals"):
150 eval_globals["__builtins__"][allowed] = __builtins__[allowed]
151 eval_globals["mudpy"] = mudpy
152 eval_globals["universe"] = actor.universe
154 # there is no other option than to use eval() for this, since
155 # its purpose is to evaluate arbitrary expressions, so do what
156 # we can to secure it and allow it for bandit analysis
157 message = repr(eval(parameters, eval_globals)) # nosec
158 except Exception as e:
159 message = ("$(red)Your expression raised an exception...$(eol)"
160 "$(eol)$(bld)%s$(nrm)" % e)
165 def halt(actor, parameters):
166 """Halt the world."""
169 # see if there's a message or use a generic one
171 message = "Halting: " + parameters
173 message = "User " + actor.owner.account.get(
175 ) + " halted the world."
178 mudpy.misc.broadcast(message, add_prompt=False)
179 mudpy.misc.log(message, 8)
181 # set a flag to terminate the world
182 actor.universe.terminate_flag = True
186 def help(actor, parameters):
187 """List available commands and provide help for commands."""
189 # did the user ask for help on a specific command word?
190 if parameters and actor.owner:
192 # is the command word one for which we have data?
193 command = mudpy.misc.find_command(parameters)
195 # only for allowed commands
196 if actor.can_run(command):
198 # add a description if provided
199 description = command.get("description")
201 description = "(no short description provided)"
202 if command.is_restricted():
206 output = "%s%s$(nrm) - %s$(eol)$(eol)" % (
207 output, command.subkey, description)
209 # add the help text if provided
210 help_text = command.get("help")
212 help_text = "No help is provided for this command."
215 # list related commands
216 see_also = command.get("see_also")
219 for item in see_also:
220 if item in actor.universe.groups["command"]:
221 command = actor.universe.groups["command"][item]
222 if actor.can_run(command):
224 really_see_also += ", "
225 if command.is_restricted():
226 really_see_also += "$(red)"
228 really_see_also += "$(grn)"
229 really_see_also += item + "$(nrm)"
231 output += "$(eol)$(eol)See also: " + really_see_also
233 # no data for the requested command word
235 output = "That is not an available command."
237 # no specific command word was indicated
241 output = ("These are the commands available to you [brackets indicate "
242 "optional portion]:$(eol)$(eol)")
244 # list command names in alphabetical order
245 for command_name, command in sorted(
246 actor.universe.groups["command"].items()):
248 # skip over disallowed commands
249 if actor.can_run(command):
251 # start incrementing substrings
252 for position in range(1, len(command_name) + 1):
254 # we've found our shortest possible abbreviation
255 candidate = mudpy.misc.find_command(
256 command_name[:position])
258 if candidate.subkey == command_name:
260 except AttributeError:
263 # use square brackets to indicate optional part of command name
264 if position < len(command_name):
265 abbrev = "%s[%s]" % (
266 command_name[:position], command_name[position:])
268 abbrev = command_name
270 # supply a useful default if the short description is missing
271 description = command.get(
272 "description", "(no short description provided)")
274 # administrative command names are in red, others in green
275 if command.is_restricted():
280 # format the entry for this command
281 output = "%s $(%s)%s$(nrm) - %s$(eol)" % (
282 output, color, abbrev, description)
284 # add a footer with instructions on getting additional information
285 output = ('%s $(eol)Enter "help COMMAND" for help on a command named '
286 '"COMMAND".' % output)
288 # send the accumulated output to the user
293 def look(actor, parameters):
296 actor.send("You can't look at or in anything yet.")
298 actor.look_at(actor.get("location"))
302 def move(actor, parameters):
303 """Move the avatar in a given direction."""
304 for portal in sorted(
305 actor.universe.contents[actor.get("location")].portals()):
306 if portal.startswith(parameters):
307 actor.move_direction(portal)
309 actor.send("You cannot go that way.")
313 def preferences(actor, parameters):
314 """List, view and change actor preferences."""
316 # Escape replacement macros in preferences
317 parameters = mudpy.misc.escape_macros(parameters)
320 arguments = parameters.split()
321 allowed_prefs = set()
323 user_config = actor.universe.contents.get("mudpy.user")
325 base_prefs = user_config.get("pref_allow", [])
326 allowed_prefs.update(base_prefs)
327 if actor.owner.account.get("administrator"):
328 allowed_prefs.update(user_config.get("pref_admin", []))
330 message += "These are your current preferences:"
332 # color-code base and admin prefs
333 for pref in sorted(allowed_prefs):
334 if pref in base_prefs:
338 message += ("$(eol) $(%s)%s$(nrm) - %s" % (
339 color, pref, actor.owner.account.get(pref, "<not set>")))
341 elif arguments[0] not in allowed_prefs:
343 'Preference "%s" does not exist. Try the `preferences` command by '
344 "itself for a list of valid preferences." % arguments[0])
345 elif len(arguments) == 1:
346 message += "%s" % actor.owner.account.get(arguments[0], "<not set>")
349 value = " ".join(arguments[1:])
351 actor.owner.account.set(pref, value)
352 message += 'Preference "%s" set to "%s".' % (pref, value)
355 'Preference "%s" cannot be set to type "%s".' % (
361 def quit(actor, parameters):
362 """Leave the world and go back to the main menu."""
364 actor.owner.state = "main_utility"
365 actor.owner.deactivate_avatar()
369 def reload(actor, parameters):
370 """Reload all code modules, configs and data."""
373 # let the user know and log
374 actor.send("Reloading all code modules, configs and data.")
377 actor.owner.account.get("name") + " reloaded the world.",
381 # set a flag to reload
382 actor.universe.reload_flag = True
386 def say(actor, parameters):
387 """Speak to others in the same area."""
389 # check for replacement macros and escape them
390 parameters = mudpy.misc.escape_macros(parameters)
392 # if the message is wrapped in quotes, remove them and leave contents
394 if parameters.startswith('"') and parameters.endswith('"'):
395 message = parameters[1:-1]
398 # otherwise, get rid of stray quote marks on the ends of the message
400 message = parameters.strip('''"'`''')
403 # the user entered a message
406 # match the punctuation used, if any, to an action
407 if "mudpy.linguistic" in actor.universe.contents:
408 actions = actor.universe.contents[
409 "mudpy.linguistic"].get("actions", {})
410 default_punctuation = (actor.universe.contents[
411 "mudpy.linguistic"].get("default_punctuation", "."))
414 default_punctuation = "."
417 # reverse sort punctuation options so the longest match wins
418 for mark in sorted(actions.keys(), reverse=True):
419 if not literal and message.endswith(mark):
420 action = actions[mark]
423 # add punctuation if needed
425 action = actions[default_punctuation]
427 literal or unicodedata.category(message[-1]) == "Po"
429 message += default_punctuation
431 # failsafe checks to avoid unwanted reformatting and null strings
432 if message and not literal:
434 # decapitalize the first letter to improve matching
435 message = message[0].lower() + message[1:]
437 # iterate over all words in message, replacing typos
438 if "mudpy.linguistic" in actor.universe.contents:
439 typos = actor.universe.contents[
440 "mudpy.linguistic"].get("typos", {})
443 words = message.split()
444 for index in range(len(words)):
446 while unicodedata.category(word[0]) == "Po":
448 while unicodedata.category(word[-1]) == "Po":
450 if word in typos.keys():
451 words[index] = words[index].replace(word, typos[word])
452 message = " ".join(words)
454 # capitalize the first letter
455 message = message[0].upper() + message[1:]
459 actor.echo_to_location(
460 actor.get("name") + " " + action + 's, "' + message + '"'
462 actor.send("You " + action + ', "' + message + '"')
464 # there was no message
466 actor.send("What do you want to say?")
470 def c_set(actor, parameters):
471 """Set a facet of an element."""
473 message = "You must specify an element, a facet and a value."
475 arguments = parameters.split(" ", 2)
476 if len(arguments) == 1:
477 message = ('What facet of element "' + arguments[0]
478 + '" would you like to set?')
479 elif len(arguments) == 2:
480 message = ('What value would you like to set for the "' +
481 arguments[1] + '" facet of the "' + arguments[0]
484 element, facet, value = arguments
485 if element not in actor.universe.contents:
486 message = 'The "' + element + '" element does not exist.'
489 actor.universe.contents[element].set(facet, value)
490 except PermissionError:
491 message = ('The "%s" element is kept in read-only file '
492 '"%s" and cannot be altered.' %
493 (element, actor.universe.contents[
494 element].origin.source))
496 message = ('Value "%s" of type "%s" cannot be coerced '
497 'to the correct datatype for facet "%s".' %
498 (value, type(value), facet))
500 message = ('You have successfully (re)set the "' + facet
501 + '" facet of element "' + element
502 + '". Try "show element ' +
503 element + '" for verification.')
508 def show(actor, parameters):
509 """Show program data."""
511 arguments = parameters.split()
513 message = "What do you want to show?"
514 elif arguments[0] == "version":
515 message = repr(actor.universe.versions)
516 elif arguments[0] == "time":
517 message = "%s increments elapsed since the world was created." % (
518 str(actor.universe.groups["internal"]["counters"].get("elapsed")))
519 elif arguments[0] == "groups":
520 message = "These are the element groups:$(eol)"
521 groups = list(actor.universe.groups.keys())
524 message += "$(eol) $(grn)" + group + "$(nrm)"
525 elif arguments[0] == "files":
526 message = "These are the current files containing the universe:$(eol)"
527 filenames = sorted(actor.universe.files)
528 for filename in filenames:
529 if actor.universe.files[filename].is_writeable():
533 message += ("$(eol) $(red)(%s) $(grn)%s$(nrm)" %
535 if actor.universe.files[filename].flags:
536 message += (" $(yel)[%s]$(nrm)" %
537 ",".join(actor.universe.files[filename].flags))
538 elif arguments[0] == "group":
539 if len(arguments) != 2:
540 message = "You must specify one group."
541 elif arguments[1] in actor.universe.groups:
542 message = ('These are the elements in the "' + arguments[1]
546 actor.universe.groups[arguments[1]][x].key
547 ) for x in actor.universe.groups[arguments[1]].keys()
550 for element in elements:
551 message += "$(eol) $(grn)" + element + "$(nrm)"
553 message = 'Group "' + arguments[1] + '" does not exist.'
554 elif arguments[0] == "file":
555 if len(arguments) != 2:
556 message = "You must specify one file."
557 elif arguments[1] in actor.universe.files:
558 message = ('These are the nodes in the "' + arguments[1]
560 elements = sorted(actor.universe.files[arguments[1]].data)
561 for element in elements:
562 message += "$(eol) $(grn)" + element + "$(nrm)"
564 message = 'File "%s" does not exist.' % arguments[1]
565 elif arguments[0] == "element":
566 if len(arguments) != 2:
567 message = "You must specify one element."
568 elif arguments[1].strip(".") in actor.universe.contents:
569 element = actor.universe.contents[arguments[1].strip(".")]
570 message = ('These are the properties of the "' + arguments[1]
571 + '" element (in "' + element.origin.source
573 facets = element.facets()
574 for facet in sorted(facets):
575 message += ("$(eol) $(grn)%s: $(red)%s$(nrm)" %
576 (facet, str(facets[facet])))
578 message = 'Element "' + arguments[1] + '" does not exist.'
579 elif arguments[0] == "log":
580 if len(arguments) == 4:
581 if re.match(r"^\d+$", arguments[3]) and int(arguments[3]) >= 0:
582 stop = int(arguments[3])
587 if len(arguments) >= 3:
588 if re.match(r"^\d+$", arguments[2]) and int(arguments[2]) > 0:
589 start = int(arguments[2])
594 if len(arguments) >= 2:
595 if (re.match(r"^\d+$", arguments[1])
596 and 0 <= int(arguments[1]) <= 9):
597 level = int(arguments[1])
600 elif 0 <= actor.owner.account.get("loglevel", 0) <= 9:
601 level = actor.owner.account.get("loglevel", 0)
604 if level > -1 and start > -1 and stop > -1:
605 message = mudpy.misc.get_loglines(level, start, stop)
607 message = ("When specified, level must be 0-9 (default 1), "
608 "start and stop must be >=1 (default 10 and 1).")
610 message = '''I don't know what "''' + parameters + '" is.'