Support abbreviating portal names when moving
[mudpy.git] / mudpy / command.py
1 """User command functions for the mudpy engine."""
2
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.
6
7 import random
8 import re
9 import traceback
10 import unicodedata
11
12 import mudpy
13
14
15 def chat(actor, parameters):
16     """Toggle chat mode."""
17     mode = actor.get("mode")
18     if not mode:
19         actor.set("mode", "chat")
20         actor.send("Entering chat mode (use $(grn)!chat$(nrm) to exit).")
21     elif mode == "chat":
22         actor.remove_facet("mode")
23         actor.send("Exiting chat mode.")
24     else:
25         actor.send("Sorry, but you're already busy with something else!")
26
27
28 def create(actor, parameters):
29     """Create an element if it does not exist."""
30     if not parameters:
31         message = "You must at least specify an element to create."
32     elif not actor.owner:
33         message = ""
34     else:
35         arguments = parameters.split()
36         if len(arguments) == 1:
37             arguments.append("")
38         if len(arguments) == 2:
39             element, filename = arguments
40             if element in actor.universe.contents:
41                 message = 'The "' + element + '" element already exists.'
42             else:
43                 message = ('You create "' +
44                            element + '" within the universe.')
45                 logline = actor.owner.account.get(
46                     "name"
47                 ) + " created an element: " + element
48                 if filename:
49                     logline += " in file " + filename
50                     if filename not in actor.universe.files:
51                         message += (
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."
59     actor.send(message)
60
61
62 def delete(actor, parameters):
63     """Delete a facet from an element."""
64     if not parameters:
65         message = "You must specify an element and a facet."
66     else:
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."
73         else:
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
79                            + '" facet.')
80             else:
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.')
86     actor.send(message)
87
88
89 def destroy(actor, parameters):
90     """Destroy an element if it exists."""
91     if actor.owner:
92         if not parameters:
93             message = "You must specify an element to destroy."
94         else:
95             if parameters not in actor.universe.contents:
96                 message = 'The "' + parameters + '" element does not exist.'
97             else:
98                 actor.universe.contents[parameters].destroy()
99                 message = ('You destroy "' + parameters
100                            + '" within the universe.')
101                 mudpy.misc.log(
102                     actor.owner.account.get(
103                         "name"
104                     ) + " destroyed an element: " + parameters,
105                     6
106                 )
107         actor.send(message)
108
109
110 def error(actor, input_data):
111     """Generic error for an unrecognized command word."""
112
113     # 90% of the time use a generic error
114     if random.randrange(10):
115         message = '''I'm not sure what "''' + input_data + '''" means...'''
116
117     # 10% of the time use the classic diku error
118     else:
119         message = "Arglebargle, glop-glyf!?!"
120
121     # try to send the error message, and log if we can't
122     try:
123         actor.send(message)
124     except Exception:
125         mudpy.misc.log(
126             'Sending a command error to user %s raised exception...\n%s' % (
127                 actor.owner.account.get("name"), traceback.format_exc()))
128
129
130 def halt(actor, parameters):
131     """Halt the world."""
132     if actor.owner:
133
134         # see if there's a message or use a generic one
135         if parameters:
136             message = "Halting: " + parameters
137         else:
138             message = "User " + actor.owner.account.get(
139                 "name"
140             ) + " halted the world."
141
142         # let everyone know
143         mudpy.misc.broadcast(message, add_prompt=False)
144         mudpy.misc.log(message, 8)
145
146         # set a flag to terminate the world
147         actor.universe.terminate_flag = True
148
149
150 def help(actor, parameters):
151     """List available commands and provide help for commands."""
152
153     # did the user ask for help on a specific command word?
154     if parameters and actor.owner:
155
156         # is the command word one for which we have data?
157         command = mudpy.misc.find_command(parameters)
158
159         # only for allowed commands
160         if actor.can_run(command):
161
162             # add a description if provided
163             description = command.get("description")
164             if not description:
165                 description = "(no short description provided)"
166             if command.get("administrative"):
167                 output = "$(red)"
168             else:
169                 output = "$(grn)"
170             output = "%s%s$(nrm) - %s$(eol)$(eol)" % (
171                 output, command.subkey, description)
172
173             # add the help text if provided
174             help_text = command.get("help")
175             if not help_text:
176                 help_text = "No help is provided for this command."
177             output += help_text
178
179             # list related commands
180             see_also = command.get("see_also")
181             if see_also:
182                 really_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):
187                             if really_see_also:
188                                 really_see_also += ", "
189                             if command.get("administrative"):
190                                 really_see_also += "$(red)"
191                             else:
192                                 really_see_also += "$(grn)"
193                             really_see_also += item + "$(nrm)"
194                 if really_see_also:
195                     output += "$(eol)$(eol)See also: " + really_see_also
196
197         # no data for the requested command word
198         else:
199             output = "That is not an available command."
200
201     # no specific command word was indicated
202     else:
203
204         # preamble text
205         output = ("These are the commands available to you [brackets indicate "
206                   "optional portion]:$(eol)$(eol)")
207
208         # list command names in alphabetical order
209         for command_name, command in sorted(
210                 actor.universe.groups["command"].items()):
211
212             # skip over disallowed commands
213             if actor.can_run(command):
214
215                 # start incrementing substrings
216                 for position in range(1, len(command_name) + 1):
217
218                     # we've found our shortest possible abbreviation
219                     candidate = mudpy.misc.find_command(
220                             command_name[:position])
221                     try:
222                         if candidate.subkey == command_name:
223                             break
224                     except AttributeError:
225                         pass
226
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:])
231                 else:
232                     abbrev = command_name
233
234                 # supply a useful default if the short description is missing
235                 description = command.get(
236                     "description", "(no short description provided)")
237
238                 # administrative command names are in red, others in green
239                 if command.get("administrative"):
240                     color = "red"
241                 else:
242                     color = "grn"
243
244                 # format the entry for this command
245                 output = "%s   $(%s)%s$(nrm) - %s$(eol)" % (
246                     output, color, abbrev, description)
247
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)
251
252     # send the accumulated output to the user
253     actor.send(output)
254
255
256 def look(actor, parameters):
257     """Look around."""
258     if parameters:
259         actor.send("You can't look at or in anything yet.")
260     else:
261         actor.look_at(actor.get("location"))
262
263
264 def move(actor, parameters):
265     """Move the avatar in a given direction."""
266     for portal in sorted(
267             actor.universe.contents[actor.get("location")].portals()):
268         if portal.startswith(parameters):
269             actor.move_direction(portal)
270             return(portal)
271     actor.send("You cannot go that way.")
272
273
274 def preferences(actor, parameters):
275     """List, view and change actor preferences."""
276
277     # Escape replacement macros in preferences
278     parameters = mudpy.misc.escape_macros(parameters)
279
280     message = ""
281     arguments = parameters.split()
282     allowed_prefs = set()
283     user_config = actor.universe.contents.get("mudpy.user")
284     if user_config:
285         allowed_prefs.update(user_config.get("pref_allow", []))
286         if actor.owner.account.get("administrator"):
287             allowed_prefs.update(user_config.get("pref_admin", []))
288     if not arguments:
289         message += "These are your current preferences:"
290         for pref in allowed_prefs:
291             message += ("$(eol)   $(red)%s $(grn)%s$(nrm)"
292                         % (pref, actor.owner.account.get(pref)))
293     elif arguments[0] not in allowed_prefs:
294         message += (
295             'Preference "%s" does not exist. Try the `preferences` command by '
296             "itself for a list of valid preferences." % arguments[0])
297     elif len(arguments) == 1:
298         message += "%s" % actor.owner.account.get(arguments[0])
299     else:
300         pref = arguments[0]
301         value = " ".join(arguments[1:])
302         try:
303             actor.owner.account.set(pref, value)
304             message += 'Preference "%s" set to "%s".' % (pref, value)
305         except ValueError:
306             message = (
307                 'Preference "%s" cannot be set to type "%s".' % (
308                     pref, type(value)))
309     actor.send(message)
310
311
312 def quit(actor, parameters):
313     """Leave the world and go back to the main menu."""
314     if actor.owner:
315         actor.owner.state = "main_utility"
316         actor.owner.deactivate_avatar()
317
318
319 def reload(actor, parameters):
320     """Reload all code modules, configs and data."""
321     if actor.owner:
322
323         # let the user know and log
324         actor.send("Reloading all code modules, configs and data.")
325         mudpy.misc.log(
326             "User " +
327             actor.owner.account.get("name") + " reloaded the world.",
328             6
329         )
330
331         # set a flag to reload
332         actor.universe.reload_flag = True
333
334
335 def say(actor, parameters):
336     """Speak to others in the same area."""
337
338     # check for replacement macros and escape them
339     parameters = mudpy.misc.escape_macros(parameters)
340
341     # if the message is wrapped in quotes, remove them and leave contents
342     # intact
343     if parameters.startswith('"') and parameters.endswith('"'):
344         message = parameters[1:-1]
345         literal = True
346
347     # otherwise, get rid of stray quote marks on the ends of the message
348     else:
349         message = parameters.strip('''"'`''')
350         literal = False
351
352     # the user entered a message
353     if message:
354
355         # match the punctuation used, if any, to an action
356         if "mudpy.linguistic" in actor.universe.contents:
357             actions = actor.universe.contents[
358                 "mudpy.linguistic"].get("actions", {})
359             default_punctuation = (actor.universe.contents[
360                 "mudpy.linguistic"].get("default_punctuation", "."))
361         else:
362             actions = {}
363             default_punctuation = "."
364         action = ""
365
366         # reverse sort punctuation options so the longest match wins
367         for mark in sorted(actions.keys(), reverse=True):
368             if not literal and message.endswith(mark):
369                 action = actions[mark]
370                 break
371
372         # add punctuation if needed
373         if not action:
374             action = actions[default_punctuation]
375             if message and not (
376                literal or unicodedata.category(message[-1]) == "Po"
377                ):
378                 message += default_punctuation
379
380         # failsafe checks to avoid unwanted reformatting and null strings
381         if message and not literal:
382
383             # decapitalize the first letter to improve matching
384             message = message[0].lower() + message[1:]
385
386             # iterate over all words in message, replacing typos
387             if "mudpy.linguistic" in actor.universe.contents:
388                 typos = actor.universe.contents[
389                     "mudpy.linguistic"].get("typos", {})
390             else:
391                 typos = {}
392             words = message.split()
393             for index in range(len(words)):
394                 word = words[index]
395                 while unicodedata.category(word[0]) == "Po":
396                     word = word[1:]
397                 while unicodedata.category(word[-1]) == "Po":
398                     word = word[:-1]
399                 if word in typos.keys():
400                     words[index] = words[index].replace(word, typos[word])
401             message = " ".join(words)
402
403             # capitalize the first letter
404             message = message[0].upper() + message[1:]
405
406     # tell the area
407     if message:
408         actor.echo_to_location(
409             actor.get("name") + " " + action + 's, "' + message + '"'
410         )
411         actor.send("You " + action + ', "' + message + '"')
412
413     # there was no message
414     else:
415         actor.send("What do you want to say?")
416
417
418 def c_set(actor, parameters):
419     """Set a facet of an element."""
420     if not parameters:
421         message = "You must specify an element, a facet and a value."
422     else:
423         arguments = parameters.split(" ", 2)
424         if len(arguments) == 1:
425             message = ('What facet of element "' + arguments[0]
426                        + '" would you like to set?')
427         elif len(arguments) == 2:
428             message = ('What value would you like to set for the "' +
429                        arguments[1] + '" facet of the "' + arguments[0]
430                        + '" element?')
431         else:
432             element, facet, value = arguments
433             if element not in actor.universe.contents:
434                 message = 'The "' + element + '" element does not exist.'
435             else:
436                 try:
437                     actor.universe.contents[element].set(facet, value)
438                 except PermissionError:
439                     message = ('The "%s" element is kept in read-only file '
440                                '"%s" and cannot be altered.' %
441                                (element, actor.universe.contents[
442                                         element].origin.source))
443                 except ValueError:
444                     message = ('Value "%s" of type "%s" cannot be coerced '
445                                'to the correct datatype for facet "%s".' %
446                                (value, type(value), facet))
447                 else:
448                     message = ('You have successfully (re)set the "' + facet
449                                + '" facet of element "' + element
450                                + '". Try "show element ' +
451                                element + '" for verification.')
452     actor.send(message)
453
454
455 def show(actor, parameters):
456     """Show program data."""
457     message = ""
458     arguments = parameters.split()
459     if not parameters:
460         message = "What do you want to show?"
461     elif arguments[0] == "version":
462         message = repr(actor.universe.versions)
463     elif arguments[0] == "time":
464         message = "%s increments elapsed since the world was created." % (
465             str(actor.universe.groups["internal"]["counters"].get("elapsed")))
466     elif arguments[0] == "groups":
467         message = "These are the element groups:$(eol)"
468         groups = list(actor.universe.groups.keys())
469         groups.sort()
470         for group in groups:
471             message += "$(eol)   $(grn)" + group + "$(nrm)"
472     elif arguments[0] == "files":
473         message = "These are the current files containing the universe:$(eol)"
474         filenames = sorted(actor.universe.files)
475         for filename in filenames:
476             if actor.universe.files[filename].is_writeable():
477                 status = "rw"
478             else:
479                 status = "ro"
480             message += ("$(eol)   $(red)(%s) $(grn)%s$(nrm)" %
481                         (status, filename))
482             if actor.universe.files[filename].flags:
483                 message += (" $(yel)[%s]$(nrm)" %
484                             ",".join(actor.universe.files[filename].flags))
485     elif arguments[0] == "group":
486         if len(arguments) != 2:
487             message = "You must specify one group."
488         elif arguments[1] in actor.universe.groups:
489             message = ('These are the elements in the "' + arguments[1]
490                        + '" group:$(eol)')
491             elements = [
492                 (
493                     actor.universe.groups[arguments[1]][x].key
494                 ) for x in actor.universe.groups[arguments[1]].keys()
495             ]
496             elements.sort()
497             for element in elements:
498                 message += "$(eol)   $(grn)" + element + "$(nrm)"
499         else:
500             message = 'Group "' + arguments[1] + '" does not exist.'
501     elif arguments[0] == "file":
502         if len(arguments) != 2:
503             message = "You must specify one file."
504         elif arguments[1] in actor.universe.files:
505             message = ('These are the nodes in the "' + arguments[1]
506                        + '" file:$(eol)')
507             elements = sorted(actor.universe.files[arguments[1]].data)
508             for element in elements:
509                 message += "$(eol)   $(grn)" + element + "$(nrm)"
510         else:
511             message = 'File "%s" does not exist.' % arguments[1]
512     elif arguments[0] == "element":
513         if len(arguments) != 2:
514             message = "You must specify one element."
515         elif arguments[1].strip(".") in actor.universe.contents:
516             element = actor.universe.contents[arguments[1].strip(".")]
517             message = ('These are the properties of the "' + arguments[1]
518                        + '" element (in "' + element.origin.source
519                        + '"):$(eol)')
520             facets = element.facets()
521             for facet in sorted(facets):
522                 message += ("$(eol)   $(grn)%s: $(red)%s$(nrm)" %
523                             (facet, str(facets[facet])))
524         else:
525             message = 'Element "' + arguments[1] + '" does not exist.'
526     elif arguments[0] == "result":
527         if len(arguments) < 2:
528             message = "You need to specify an expression."
529         else:
530             try:
531                 message = repr(eval(" ".join(arguments[1:])))
532             except Exception as e:
533                 message = ("$(red)Your expression raised an exception...$(eol)"
534                            "$(eol)$(bld)%s$(nrm)" % e)
535     elif arguments[0] == "log":
536         if len(arguments) == 4:
537             if re.match(r"^\d+$", arguments[3]) and int(arguments[3]) >= 0:
538                 stop = int(arguments[3])
539             else:
540                 stop = -1
541         else:
542             stop = 0
543         if len(arguments) >= 3:
544             if re.match(r"^\d+$", arguments[2]) and int(arguments[2]) > 0:
545                 start = int(arguments[2])
546             else:
547                 start = -1
548         else:
549             start = 10
550         if len(arguments) >= 2:
551             if (re.match(r"^\d+$", arguments[1])
552                     and 0 <= int(arguments[1]) <= 9):
553                 level = int(arguments[1])
554             else:
555                 level = -1
556         elif 0 <= actor.owner.account.get("loglevel", 0) <= 9:
557             level = actor.owner.account.get("loglevel", 0)
558         else:
559             level = 1
560         if level > -1 and start > -1 and stop > -1:
561             message = mudpy.misc.get_loglines(level, start, stop)
562         else:
563             message = ("When specified, level must be 0-9 (default 1), "
564                        "start and stop must be >=1 (default 10 and 1).")
565     else:
566         message = '''I don't know what "''' + parameters + '" is.'
567     actor.send(message)