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