1 """User command functions for the mudpy engine."""
3 # Copyright (c) 2004-2018 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 """Toggle chat mode."""
16 mode = actor.get("mode")
18 actor.set("mode", "chat")
19 actor.send("Entering chat mode (use $(grn)!chat$(nrm) to exit).")
21 actor.remove_facet("mode")
22 actor.send("Exiting chat mode.")
24 actor.send("Sorry, but you're already busy with something else!")
27 def create(actor, parameters):
28 """Create an element if it does not exist."""
30 message = "You must at least specify an element to create."
34 arguments = parameters.split()
35 if len(arguments) == 1:
37 if len(arguments) == 2:
38 element, filename = arguments
39 if element in actor.universe.contents:
40 message = 'The "' + element + '" element already exists.'
42 message = ('You create "' +
43 element + '" within the universe.')
44 logline = actor.owner.account.get(
46 ) + " created an element: " + element
48 logline += " in file " + filename
49 if filename not in actor.universe.files:
51 ' Warning: "' + filename + '" is not yet '
52 "included in any other file and will not be read "
53 "on startup unless this is remedied.")
54 mudpy.misc.Element(element, actor.universe, filename)
55 mudpy.misc.log(logline, 6)
56 elif len(arguments) > 2:
57 message = "You can only specify an element and a filename."
61 def delete(actor, parameters):
62 """Delete a facet from an element."""
64 message = "You must specify an element and a facet."
66 arguments = parameters.split(" ")
67 if len(arguments) == 1:
68 message = ('What facet of element "' + arguments[0]
69 + '" would you like to delete?')
70 elif len(arguments) != 2:
71 message = "You may only specify an element and a facet."
73 element, facet = arguments
74 if element not in actor.universe.contents:
75 message = 'The "' + element + '" element does not exist.'
76 elif facet not in actor.universe.contents[element].facets():
77 message = ('The "' + element + '" element has no "' + facet
80 actor.universe.contents[element].remove_facet(facet)
81 message = ('You have successfully deleted the "' + facet
82 + '" facet of element "' + element
83 + '". Try "show element ' +
84 element + '" for verification.')
88 def destroy(actor, parameters):
89 """Destroy an element if it exists."""
92 message = "You must specify an element to destroy."
94 if parameters not in actor.universe.contents:
95 message = 'The "' + parameters + '" element does not exist.'
97 actor.universe.contents[parameters].destroy()
98 message = ('You destroy "' + parameters
99 + '" within the universe.')
101 actor.owner.account.get(
103 ) + " destroyed an element: " + parameters,
109 def error(actor, input_data):
110 """Generic error for an unrecognized command word."""
112 # 90% of the time use a generic error
113 if random.randrange(10):
114 message = '''I'm not sure what "''' + input_data + '''" means...'''
116 # 10% of the time use the classic diku error
118 message = "Arglebargle, glop-glyf!?!"
120 # send the error message
124 def halt(actor, parameters):
125 """Halt the world."""
128 # see if there's a message or use a generic one
130 message = "Halting: " + parameters
132 message = "User " + actor.owner.account.get(
134 ) + " halted the world."
137 mudpy.misc.broadcast(message, add_prompt=False)
138 mudpy.misc.log(message, 8)
140 # set a flag to terminate the world
141 actor.universe.terminate_flag = True
144 def help(actor, parameters):
145 """List available commands and provide help for commands."""
147 # did the user ask for help on a specific command word?
148 if parameters and actor.owner:
150 # is the command word one for which we have data?
151 if parameters in actor.universe.groups["command"]:
152 command = actor.universe.groups["command"][parameters]
156 # only for allowed commands
157 if actor.can_run(command):
159 # add a description if provided
160 description = command.get("description")
162 description = "(no short description provided)"
163 if command.get("administrative"):
167 output += parameters + "$(nrm) - " + description + "$(eol)$(eol)"
169 # add the help text if provided
170 help_text = command.get("help")
172 help_text = "No help is provided for this command."
175 # list related commands
176 see_also = command.get("see_also")
179 for item in see_also:
180 if item in actor.universe.groups["command"]:
181 command = actor.universe.groups["command"][item]
182 if actor.can_run(command):
184 really_see_also += ", "
185 if command.get("administrative"):
186 really_see_also += "$(red)"
188 really_see_also += "$(grn)"
189 really_see_also += item + "$(nrm)"
191 output += "$(eol)$(eol)See also: " + really_see_also
193 # no data for the requested command word
195 output = "That is not an available command."
197 # no specific command word was indicated
200 # give a sorted list of commands with descriptions if provided
201 output = "These are the commands available to you:$(eol)$(eol)"
202 sorted_commands = list(actor.universe.groups["command"].keys())
203 sorted_commands.sort()
204 for item in sorted_commands:
205 command = actor.universe.groups["command"][item]
206 if actor.can_run(command):
207 description = command.get("description")
209 description = "(no short description provided)"
210 if command.get("administrative"):
214 output += item + "$(nrm) - " + description + "$(eol)"
215 output += ('$(eol)Enter "help COMMAND" for help on a command '
218 # send the accumulated output to the user
222 def look(actor, parameters):
225 actor.send("You can't look at or in anything yet.")
227 actor.look_at(actor.get("location"))
230 def move(actor, parameters):
231 """Move the avatar in a given direction."""
232 if parameters in actor.universe.contents[actor.get("location")].portals():
233 actor.move_direction(parameters)
235 actor.send("You cannot go that way.")
239 """Leave the world and go back to the main menu."""
241 actor.owner.state = "main_utility"
242 actor.owner.deactivate_avatar()
246 """Reload all code modules, configs and data."""
249 # let the user know and log
250 actor.send("Reloading all code modules, configs and data.")
253 actor.owner.account.get("name") + " reloaded the world.",
257 # set a flag to reload
258 actor.universe.reload_flag = True
261 def say(actor, parameters):
262 """Speak to others in the same area."""
264 # check for replacement macros and escape them
265 parameters = mudpy.misc.escape_macros(parameters)
267 # if the message is wrapped in quotes, remove them and leave contents
269 if parameters.startswith('"') and parameters.endswith('"'):
270 message = parameters[1:-1]
273 # otherwise, get rid of stray quote marks on the ends of the message
275 message = parameters.strip('''"'`''')
278 # the user entered a message
281 # match the punctuation used, if any, to an action
282 if "mudpy.linguistic" in actor.universe.contents:
283 actions = actor.universe.contents[
284 "mudpy.linguistic"].get("actions", {})
285 default_punctuation = (actor.universe.contents[
286 "mudpy.linguistic"].get("default_punctuation", "."))
289 default_punctuation = "."
292 # reverse sort punctuation options so the longest match wins
293 for mark in sorted(actions.keys(), reverse=True):
294 if not literal and message.endswith(mark):
295 action = actions[mark]
298 # add punctuation if needed
300 action = actions[default_punctuation]
302 literal or unicodedata.category(message[-1]) == "Po"
304 message += default_punctuation
306 # failsafe checks to avoid unwanted reformatting and null strings
307 if message and not literal:
309 # decapitalize the first letter to improve matching
310 message = message[0].lower() + message[1:]
312 # iterate over all words in message, replacing typos
313 if "mudpy.linguistic" in actor.universe.contents:
314 typos = actor.universe.contents[
315 "mudpy.linguistic"].get("typos", {})
318 words = message.split()
319 for index in range(len(words)):
321 while unicodedata.category(word[0]) == "Po":
323 while unicodedata.category(word[-1]) == "Po":
325 if word in typos.keys():
326 words[index] = words[index].replace(word, typos[word])
327 message = " ".join(words)
329 # capitalize the first letter
330 message = message[0].upper() + message[1:]
334 actor.echo_to_location(
335 actor.get("name") + " " + action + 's, "' + message + '"'
337 actor.send("You " + action + ', "' + message + '"')
339 # there was no message
341 actor.send("What do you want to say?")
344 def set(actor, parameters):
345 """Set a facet of an element."""
347 message = "You must specify an element, a facet and a value."
349 arguments = parameters.split(" ", 2)
350 if len(arguments) == 1:
351 message = ('What facet of element "' + arguments[0]
352 + '" would you like to set?')
353 elif len(arguments) == 2:
354 message = ('What value would you like to set for the "' +
355 arguments[1] + '" facet of the "' + arguments[0]
358 element, facet, value = arguments
359 if element not in actor.universe.contents:
360 message = 'The "' + element + '" element does not exist.'
363 actor.universe.contents[element].set(facet, value)
364 except PermissionError:
365 message = ('The "%s" element is kept in read-only file '
366 '"%s" and cannot be altered.' %
367 (element, actor.universe.contents[
368 element].origin.source))
370 message = ('Value "%s" of type "%s" cannot be coerced '
371 'to the correct datatype for facet "%s".' %
372 (value, type(value), facet))
374 message = ('You have successfully (re)set the "' + facet
375 + '" facet of element "' + element
376 + '". Try "show element ' +
377 element + '" for verification.')
381 def show(actor, parameters):
382 """Show program data."""
384 arguments = parameters.split()
386 message = "What do you want to show?"
387 elif arguments[0] == "version":
388 message = repr(actor.universe.versions)
389 elif arguments[0] == "time":
390 message = actor.universe.groups["internal"]["counters"].get(
392 ) + " increments elapsed since the world was created."
393 elif arguments[0] == "groups":
394 message = "These are the element groups:$(eol)"
395 groups = list(actor.universe.groups.keys())
398 message += "$(eol) $(grn)" + group + "$(nrm)"
399 elif arguments[0] == "files":
400 message = "These are the current files containing the universe:$(eol)"
401 filenames = sorted(actor.universe.files)
402 for filename in filenames:
403 if actor.universe.files[filename].is_writeable():
407 message += ("$(eol) $(red)(%s) $(grn)%s$(nrm)" %
409 if actor.universe.files[filename].flags:
410 message += (" $(yel)[%s]$(nrm)" %
411 ",".join(actor.universe.files[filename].flags))
412 elif arguments[0] == "group":
413 if len(arguments) != 2:
414 message = "You must specify one group."
415 elif arguments[1] in actor.universe.groups:
416 message = ('These are the elements in the "' + arguments[1]
420 actor.universe.groups[arguments[1]][x].key
421 ) for x in actor.universe.groups[arguments[1]].keys()
424 for element in elements:
425 message += "$(eol) $(grn)" + element + "$(nrm)"
427 message = 'Group "' + arguments[1] + '" does not exist.'
428 elif arguments[0] == "file":
429 if len(arguments) != 2:
430 message = "You must specify one file."
431 elif arguments[1] in actor.universe.files:
432 message = ('These are the nodes in the "' + arguments[1]
434 elements = sorted(actor.universe.files[arguments[1]].data)
435 for element in elements:
436 message += "$(eol) $(grn)" + element + "$(nrm)"
438 message = 'File "%s" does not exist.' % arguments[1]
439 elif arguments[0] == "element":
440 if len(arguments) != 2:
441 message = "You must specify one element."
442 elif arguments[1].strip(".") in actor.universe.contents:
443 element = actor.universe.contents[arguments[1].strip(".")]
444 message = ('These are the properties of the "' + arguments[1]
445 + '" element (in "' + element.origin.source
447 facets = element.facets()
448 for facet in sorted(facets):
449 message += ("$(eol) $(grn)%s: $(red)%s$(nrm)" %
450 (facet, str(facets[facet])))
452 message = 'Element "' + arguments[1] + '" does not exist.'
453 elif arguments[0] == "result":
454 if len(arguments) < 2:
455 message = "You need to specify an expression."
458 message = repr(eval(" ".join(arguments[1:])))
459 except Exception as e:
460 message = ("$(red)Your expression raised an exception...$(eol)"
461 "$(eol)$(bld)%s$(nrm)" % e)
462 elif arguments[0] == "log":
463 if len(arguments) == 4:
464 if re.match(r"^\d+$", arguments[3]) and int(arguments[3]) >= 0:
465 stop = int(arguments[3])
470 if len(arguments) >= 3:
471 if re.match(r"^\d+$", arguments[2]) and int(arguments[2]) > 0:
472 start = int(arguments[2])
477 if len(arguments) >= 2:
478 if (re.match(r"^\d+$", arguments[1])
479 and 0 <= int(arguments[1]) <= 9):
480 level = int(arguments[1])
483 elif 0 <= actor.owner.account.get("loglevel", 0) <= 9:
484 level = actor.owner.account.get("loglevel", 0)
487 if level > -1 and start > -1 and stop > -1:
488 message = mudpy.misc.get_loglines(level, start, stop)
490 message = ("When specified, level must be 0-9 (default 1), "
491 "start and stop must be >=1 (default 10 and 1).")
493 message = '''I don't know what "''' + parameters + '" is.'