1138aa85370545c848e06bb7de5992fec495a13f
[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         if parameters in actor.universe.groups["command"]:
152             command = actor.universe.groups["command"][parameters]
153         else:
154             command = None
155
156         # only for allowed commands
157         if actor.can_run(command):
158
159             # add a description if provided
160             description = command.get("description")
161             if not description:
162                 description = "(no short description provided)"
163             if command.get("administrative"):
164                 output = "$(red)"
165             else:
166                 output = "$(grn)"
167             output += parameters + "$(nrm) - " + description + "$(eol)$(eol)"
168
169             # add the help text if provided
170             help_text = command.get("help")
171             if not help_text:
172                 help_text = "No help is provided for this command."
173             output += help_text
174
175             # list related commands
176             see_also = command.get("see_also")
177             if see_also:
178                 really_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):
183                             if really_see_also:
184                                 really_see_also += ", "
185                             if command.get("administrative"):
186                                 really_see_also += "$(red)"
187                             else:
188                                 really_see_also += "$(grn)"
189                             really_see_also += item + "$(nrm)"
190                 if really_see_also:
191                     output += "$(eol)$(eol)See also: " + really_see_also
192
193         # no data for the requested command word
194         else:
195             output = "That is not an available command."
196
197     # no specific command word was indicated
198     else:
199
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")
208                 if not description:
209                     description = "(no short description provided)"
210                 if command.get("administrative"):
211                     output += "   $(red)"
212                 else:
213                     output += "   $(grn)"
214                 output += item + "$(nrm) - " + description + "$(eol)"
215         output += ('$(eol)Enter "help COMMAND" for help on a command '
216                    'named "COMMAND".')
217
218     # send the accumulated output to the user
219     actor.send(output)
220
221
222 def look(actor, parameters):
223     """Look around."""
224     if parameters:
225         actor.send("You can't look at or in anything yet.")
226     else:
227         actor.look_at(actor.get("location"))
228
229
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)
234     else:
235         actor.send("You cannot go that way.")
236
237
238 def preferences(actor, parameters):
239     """List, view and change actor preferences."""
240
241     # Escape replacement macros in preferences
242     parameters = mudpy.misc.escape_macros(parameters)
243
244     message = ""
245     arguments = parameters.split()
246     allowed_prefs = set()
247     user_config = actor.universe.contents.get("mudpy.user")
248     if user_config:
249         allowed_prefs.update(user_config.get("pref_allow", []))
250         if actor.owner.account.get("administrator"):
251             allowed_prefs.update(user_config.get("pref_admin", []))
252     if not arguments:
253         message += "These are your current preferences:"
254         for pref in allowed_prefs:
255             message += ("$(eol)   $(red)%s $(grn)%s$(nrm)"
256                         % (pref, actor.owner.account.get(pref)))
257     elif arguments[0] not in allowed_prefs:
258         message += (
259             'Preference "%s" does not exist. Try the `preferences` command by '
260             "itself for a list of valid preferences." % arguments[0])
261     elif len(arguments) == 1:
262         message += "%s" % actor.owner.account.get(arguments[0])
263     else:
264         pref = arguments[0]
265         value = " ".join(arguments[1:])
266         try:
267             actor.owner.account.set(pref, value)
268             message += 'Preference "%s" set to "%s".' % (pref, value)
269         except ValueError:
270             message = (
271                 'Preference "%s" cannot be set to type "%s".' % (
272                     pref, type(value)))
273     actor.send(message)
274
275
276 def quit(actor):
277     """Leave the world and go back to the main menu."""
278     if actor.owner:
279         actor.owner.state = "main_utility"
280         actor.owner.deactivate_avatar()
281
282
283 def reload(actor):
284     """Reload all code modules, configs and data."""
285     if actor.owner:
286
287         # let the user know and log
288         actor.send("Reloading all code modules, configs and data.")
289         mudpy.misc.log(
290             "User " +
291             actor.owner.account.get("name") + " reloaded the world.",
292             6
293         )
294
295         # set a flag to reload
296         actor.universe.reload_flag = True
297
298
299 def say(actor, parameters):
300     """Speak to others in the same area."""
301
302     # check for replacement macros and escape them
303     parameters = mudpy.misc.escape_macros(parameters)
304
305     # if the message is wrapped in quotes, remove them and leave contents
306     # intact
307     if parameters.startswith('"') and parameters.endswith('"'):
308         message = parameters[1:-1]
309         literal = True
310
311     # otherwise, get rid of stray quote marks on the ends of the message
312     else:
313         message = parameters.strip('''"'`''')
314         literal = False
315
316     # the user entered a message
317     if message:
318
319         # match the punctuation used, if any, to an action
320         if "mudpy.linguistic" in actor.universe.contents:
321             actions = actor.universe.contents[
322                 "mudpy.linguistic"].get("actions", {})
323             default_punctuation = (actor.universe.contents[
324                 "mudpy.linguistic"].get("default_punctuation", "."))
325         else:
326             actions = {}
327             default_punctuation = "."
328         action = ""
329
330         # reverse sort punctuation options so the longest match wins
331         for mark in sorted(actions.keys(), reverse=True):
332             if not literal and message.endswith(mark):
333                 action = actions[mark]
334                 break
335
336         # add punctuation if needed
337         if not action:
338             action = actions[default_punctuation]
339             if message and not (
340                literal or unicodedata.category(message[-1]) == "Po"
341                ):
342                 message += default_punctuation
343
344         # failsafe checks to avoid unwanted reformatting and null strings
345         if message and not literal:
346
347             # decapitalize the first letter to improve matching
348             message = message[0].lower() + message[1:]
349
350             # iterate over all words in message, replacing typos
351             if "mudpy.linguistic" in actor.universe.contents:
352                 typos = actor.universe.contents[
353                     "mudpy.linguistic"].get("typos", {})
354             else:
355                 typos = {}
356             words = message.split()
357             for index in range(len(words)):
358                 word = words[index]
359                 while unicodedata.category(word[0]) == "Po":
360                     word = word[1:]
361                 while unicodedata.category(word[-1]) == "Po":
362                     word = word[:-1]
363                 if word in typos.keys():
364                     words[index] = words[index].replace(word, typos[word])
365             message = " ".join(words)
366
367             # capitalize the first letter
368             message = message[0].upper() + message[1:]
369
370     # tell the area
371     if message:
372         actor.echo_to_location(
373             actor.get("name") + " " + action + 's, "' + message + '"'
374         )
375         actor.send("You " + action + ', "' + message + '"')
376
377     # there was no message
378     else:
379         actor.send("What do you want to say?")
380
381
382 def c_set(actor, parameters):
383     """Set a facet of an element."""
384     if not parameters:
385         message = "You must specify an element, a facet and a value."
386     else:
387         arguments = parameters.split(" ", 2)
388         if len(arguments) == 1:
389             message = ('What facet of element "' + arguments[0]
390                        + '" would you like to set?')
391         elif len(arguments) == 2:
392             message = ('What value would you like to set for the "' +
393                        arguments[1] + '" facet of the "' + arguments[0]
394                        + '" element?')
395         else:
396             element, facet, value = arguments
397             if element not in actor.universe.contents:
398                 message = 'The "' + element + '" element does not exist.'
399             else:
400                 try:
401                     actor.universe.contents[element].set(facet, value)
402                 except PermissionError:
403                     message = ('The "%s" element is kept in read-only file '
404                                '"%s" and cannot be altered.' %
405                                (element, actor.universe.contents[
406                                         element].origin.source))
407                 except ValueError:
408                     message = ('Value "%s" of type "%s" cannot be coerced '
409                                'to the correct datatype for facet "%s".' %
410                                (value, type(value), facet))
411                 else:
412                     message = ('You have successfully (re)set the "' + facet
413                                + '" facet of element "' + element
414                                + '". Try "show element ' +
415                                element + '" for verification.')
416     actor.send(message)
417
418
419 def show(actor, parameters):
420     """Show program data."""
421     message = ""
422     arguments = parameters.split()
423     if not parameters:
424         message = "What do you want to show?"
425     elif arguments[0] == "version":
426         message = repr(actor.universe.versions)
427     elif arguments[0] == "time":
428         message = actor.universe.groups["internal"]["counters"].get(
429             "elapsed"
430         ) + " increments elapsed since the world was created."
431     elif arguments[0] == "groups":
432         message = "These are the element groups:$(eol)"
433         groups = list(actor.universe.groups.keys())
434         groups.sort()
435         for group in groups:
436             message += "$(eol)   $(grn)" + group + "$(nrm)"
437     elif arguments[0] == "files":
438         message = "These are the current files containing the universe:$(eol)"
439         filenames = sorted(actor.universe.files)
440         for filename in filenames:
441             if actor.universe.files[filename].is_writeable():
442                 status = "rw"
443             else:
444                 status = "ro"
445             message += ("$(eol)   $(red)(%s) $(grn)%s$(nrm)" %
446                         (status, filename))
447             if actor.universe.files[filename].flags:
448                 message += (" $(yel)[%s]$(nrm)" %
449                             ",".join(actor.universe.files[filename].flags))
450     elif arguments[0] == "group":
451         if len(arguments) != 2:
452             message = "You must specify one group."
453         elif arguments[1] in actor.universe.groups:
454             message = ('These are the elements in the "' + arguments[1]
455                        + '" group:$(eol)')
456             elements = [
457                 (
458                     actor.universe.groups[arguments[1]][x].key
459                 ) for x in actor.universe.groups[arguments[1]].keys()
460             ]
461             elements.sort()
462             for element in elements:
463                 message += "$(eol)   $(grn)" + element + "$(nrm)"
464         else:
465             message = 'Group "' + arguments[1] + '" does not exist.'
466     elif arguments[0] == "file":
467         if len(arguments) != 2:
468             message = "You must specify one file."
469         elif arguments[1] in actor.universe.files:
470             message = ('These are the nodes in the "' + arguments[1]
471                        + '" file:$(eol)')
472             elements = sorted(actor.universe.files[arguments[1]].data)
473             for element in elements:
474                 message += "$(eol)   $(grn)" + element + "$(nrm)"
475         else:
476             message = 'File "%s" does not exist.' % arguments[1]
477     elif arguments[0] == "element":
478         if len(arguments) != 2:
479             message = "You must specify one element."
480         elif arguments[1].strip(".") in actor.universe.contents:
481             element = actor.universe.contents[arguments[1].strip(".")]
482             message = ('These are the properties of the "' + arguments[1]
483                        + '" element (in "' + element.origin.source
484                        + '"):$(eol)')
485             facets = element.facets()
486             for facet in sorted(facets):
487                 message += ("$(eol)   $(grn)%s: $(red)%s$(nrm)" %
488                             (facet, str(facets[facet])))
489         else:
490             message = 'Element "' + arguments[1] + '" does not exist.'
491     elif arguments[0] == "result":
492         if len(arguments) < 2:
493             message = "You need to specify an expression."
494         else:
495             try:
496                 message = repr(eval(" ".join(arguments[1:])))
497             except Exception as e:
498                 message = ("$(red)Your expression raised an exception...$(eol)"
499                            "$(eol)$(bld)%s$(nrm)" % e)
500     elif arguments[0] == "log":
501         if len(arguments) == 4:
502             if re.match(r"^\d+$", arguments[3]) and int(arguments[3]) >= 0:
503                 stop = int(arguments[3])
504             else:
505                 stop = -1
506         else:
507             stop = 0
508         if len(arguments) >= 3:
509             if re.match(r"^\d+$", arguments[2]) and int(arguments[2]) > 0:
510                 start = int(arguments[2])
511             else:
512                 start = -1
513         else:
514             start = 10
515         if len(arguments) >= 2:
516             if (re.match(r"^\d+$", arguments[1])
517                     and 0 <= int(arguments[1]) <= 9):
518                 level = int(arguments[1])
519             else:
520                 level = -1
521         elif 0 <= actor.owner.account.get("loglevel", 0) <= 9:
522             level = actor.owner.account.get("loglevel", 0)
523         else:
524             level = 1
525         if level > -1 and start > -1 and stop > -1:
526             message = mudpy.misc.get_loglines(level, start, stop)
527         else:
528             message = ("When specified, level must be 0-9 (default 1), "
529                        "start and stop must be >=1 (default 10 and 1).")
530     else:
531         message = '''I don't know what "''' + parameters + '" is.'
532     actor.send(message)