1 """Core objects for the mudpy engine."""
3 # Copyright (c) 2005 mudpy, Jeremy Stanley <fungi@yuggoth.org>, all rights reserved.
4 # Licensed per terms in the LICENSE file distributed with this software.
6 # import some things we need
7 from ConfigParser import RawConfigParser
8 from md5 import new as new_md5
9 from os import R_OK, access, chmod, makedirs, stat
10 from os.path import abspath, dirname, exists, isabs, join as path_join
11 from random import choice, randrange
13 from socket import AF_INET, SO_REUSEADDR, SOCK_STREAM, SOL_SOCKET, socket
14 from stat import S_IMODE, ST_MODE
15 from sys import stderr
16 from syslog import LOG_PID, LOG_INFO, LOG_DAEMON, closelog, openlog, syslog
17 from telnetlib import DO, DONT, ECHO, EOR, GA, IAC, LINEMODE, SB, SE, SGA, WILL, WONT
18 from time import asctime, sleep
19 from traceback import format_exception
21 def excepthook(excepttype, value, traceback):
22 """Handle uncaught exceptions."""
24 # assemble the list of errors into a single string
25 message = "".join(format_exception(excepttype, value, traceback))
27 # try to log it, if possible
31 # try to write it to stderr, if possible
32 try: stderr.write(message)
35 # redefine sys.excepthook with ours
37 sys.excepthook = excepthook
40 """An element of the universe."""
41 def __init__(self, key, universe, filename=None):
42 """Set up a new element."""
44 # not owned by a user by default (used for avatars)
47 # no contents in here by default
50 # an event queue for the element
53 # keep track of our key name
56 # parse out appropriate category and subkey names, add to list
57 if self.key.find(":") > 0:
58 self.category, self.subkey = self.key.split(":", 1)
60 self.category = "other"
61 self.subkey = self.key
62 if not self.category in universe.categories: self.category = "other"
63 universe.categories[self.category][self.subkey] = self
65 # get an appropriate filename for the origin
66 if not filename: filename = universe.default_origins[self.category]
67 if not isabs(filename): filename = abspath(filename)
69 # add the file if it doesn't exist yet
70 if not filename in universe.files: DataFile(filename, universe)
72 # record a pointer to the origin file
73 self.origin = universe.files[filename]
75 # add a data section to the origin if necessary
76 if not self.origin.data.has_section(self.key):
77 self.origin.data.add_section(self.key)
79 # add this element to the universe contents
80 universe.contents[self.key] = self
83 """Remove an element from the universe and destroy it."""
84 self.origin.data.remove_section(self.key)
85 del universe.categories[self.category][self.subkey]
86 del universe.contents[self.key]
89 """Return a list of non-inherited facets for this element."""
90 if self.key in self.origin.data.sections():
91 return self.origin.data.options(self.key)
93 def has_facet(self, facet):
94 """Return whether the non-inherited facet exists."""
95 return facet in self.facets()
96 def remove_facet(self, facet):
97 """Remove a facet from the element."""
98 if self.has_facet(facet):
99 self.origin.data.remove_option(self.key, facet)
100 self.origin.modified = True
102 """Return a list of the element's inheritance lineage."""
103 if self.has_facet("inherit"):
104 ancestry = self.getlist("inherit")
105 for parent in ancestry[:]:
106 ancestors = universe.contents[parent].ancestry()
107 for ancestor in ancestors:
108 if ancestor not in ancestry: ancestry.append(ancestor)
111 def get(self, facet, default=None):
112 """Retrieve values."""
113 if default is None: default = ""
114 if self.origin.data.has_option(self.key, facet):
115 return self.origin.data.get(self.key, facet)
116 elif self.has_facet("inherit"):
117 for ancestor in self.ancestry():
118 if universe.contents[ancestor].has_facet(facet):
119 return universe.contents[ancestor].get(facet)
121 def getboolean(self, facet, default=None):
122 """Retrieve values as boolean type."""
123 if default is None: default=False
124 if self.origin.data.has_option(self.key, facet):
125 return self.origin.data.getboolean(self.key, facet)
126 elif self.has_facet("inherit"):
127 for ancestor in self.ancestry():
128 if universe.contents[ancestor].has_facet(facet):
129 return universe.contents[ancestor].getboolean(facet)
131 def getint(self, facet, default=None):
132 """Return values as int/long type."""
133 if default is None: default = 0
134 if self.origin.data.has_option(self.key, facet):
135 return self.origin.data.getint(self.key, facet)
136 elif self.has_facet("inherit"):
137 for ancestor in self.ancestry():
138 if universe.contents[ancestor].has_facet(facet):
139 return universe.contents[ancestor].getint(facet)
141 def getfloat(self, facet, default=None):
142 """Return values as float type."""
143 if default is None: default = 0.0
144 if self.origin.data.has_option(self.key, facet):
145 return self.origin.data.getfloat(self.key, facet)
146 elif self.has_facet("inherit"):
147 for ancestor in self.ancestry():
148 if universe.contents[ancestor].has_facet(facet):
149 return universe.contents[ancestor].getfloat(facet)
151 def getlist(self, facet, default=None):
152 """Return values as list type."""
153 if default is None: default = []
154 value = self.get(facet)
155 if value: return makelist(value)
157 def getdict(self, facet, default=None):
158 """Return values as dict type."""
159 if default is None: default = {}
160 value = self.get(facet)
161 if value: return makedict(value)
163 def set(self, facet, value):
165 if not self.has_facet(facet) or not self.get(facet) == value:
166 if type(value) is long: value = str(value)
167 elif not type(value) is str: value = repr(value)
168 self.origin.data.set(self.key, facet, value)
169 self.origin.modified = True
170 def append(self, facet, value):
171 """Append value tp a list."""
172 if type(value) is long: value = str(value)
173 elif not type(value) is str: value = repr(value)
174 newlist = self.getlist(facet)
175 newlist.append(value)
176 self.set(facet, newlist)
178 def new_event(self, action, when=None):
179 """Create, attach and enqueue an event element."""
181 # if when isn't specified, that means now
182 if not when: when = universe.get_time()
184 # events are elements themselves
185 event = Element("event:" + self.key + ":" + counter)
187 def send(self, message, eol="$(eol)"):
188 """Convenience method to pass messages to an owner."""
189 if self.owner: self.owner.send(message, eol)
191 def can_run(self, command):
192 """Check if the user can run this command object."""
194 # has to be in the commands category
195 if command not in universe.categories["command"].values(): result = False
197 # avatars of administrators can run any command
198 elif self.owner and self.owner.account.getboolean("administrator"): result = True
200 # everyone can run non-administrative commands
201 elif not command.getboolean("administrative"): result = True
203 # otherwise the command cannot be run by this actor
206 # pass back the result
209 def go_to(self, location):
210 """Relocate the element to a specific location."""
211 current = self.get("location")
212 if current and self.key in universe.contents[current].contents:
213 del universe.contents[current].contents[self.key]
214 if location in universe.contents: self.set("location", location)
215 universe.contents[location].contents[self.key] = self
216 self.look_at(location)
218 """Relocate the element to its default location."""
219 self.go_to(self.get("default_location"))
220 self.echo_to_location("You suddenly realize that " + self.get("name") + " is here.")
221 def move_direction(self, direction):
222 """Relocate the element in a specified direction."""
223 self.echo_to_location(self.get("name") + " exits " + universe.categories["internal"]["directions"].getdict(direction)["exit"] + ".")
224 self.send("You exit " + universe.categories["internal"]["directions"].getdict(direction)["exit"] + ".")
225 self.go_to(universe.contents[self.get("location")].link_neighbor(direction))
226 self.echo_to_location(self.get("name") + " arrives from " + universe.categories["internal"]["directions"].getdict(direction)["enter"] + ".")
227 def look_at(self, key):
228 """Show an element to another element."""
230 element = universe.contents[key]
232 name = element.get("name")
233 if name: message += "$(cyn)" + name + "$(nrm)$(eol)"
234 description = element.get("description")
235 if description: message += description + "$(eol)"
236 portal_list = element.portals().keys()
239 message += "$(cyn)[ Exits: " + ", ".join(portal_list) + " ]$(nrm)$(eol)"
240 for element in universe.contents[self.get("location")].contents.values():
241 if element.getboolean("is_actor") and element is not self:
242 message += "$(yel)" + element.get("name") + " is here.$(nrm)$(eol)"
245 """Map the portal directions for a room to neighbors."""
247 if match("""^location:-?\d+,-?\d+,-?\d+$""", self.key):
248 coordinates = [(int(x)) for x in self.key.split(":")[1].split(",")]
249 directions = universe.categories["internal"]["directions"]
250 offsets = dict([(x, directions.getdict(x)["vector"]) for x in directions.facets()])
251 for portal in self.getlist("gridlinks"):
252 adjacent = map(lambda c,o: c+o, coordinates, offsets[portal])
253 neighbor = "location:" + ",".join([(str(x)) for x in adjacent])
254 if neighbor in universe.contents: portals[portal] = neighbor
255 for facet in self.facets():
256 if facet.startswith("link_"):
257 neighbor = self.get(facet)
258 if neighbor in universe.contents:
259 portal = facet.split("_")[1]
260 portals[portal] = neighbor
262 def link_neighbor(self, direction):
263 """Return the element linked in a given direction."""
264 portals = self.portals()
265 if direction in portals: return portals[direction]
266 def echo_to_location(self, message):
267 """Show a message to other elements in the current location."""
268 for element in universe.contents[self.get("location")].contents.values():
269 if element is not self: element.send(message)
272 """A file containing universe elements."""
273 def __init__(self, filename, universe):
274 self.modified = False
275 self.data = RawConfigParser()
276 if access(filename, R_OK): self.data.read(filename)
277 self.filename = filename
278 universe.files[filename] = self
279 if self.data.has_option("__control__", "include_files"):
280 includes = makelist(self.data.get("__control__", "include_files"))
282 if self.data.has_option("__control__", "default_files"):
283 origins = makedict(self.data.get("__control__", "default_files"))
284 for key in origins.keys():
285 if not key in includes: includes.append(key)
286 universe.default_origins[key] = origins[key]
287 if not key in universe.categories:
288 universe.categories[key] = {}
289 if self.data.has_option("__control__", "private_files"):
290 for item in makelist(self.data.get("__control__", "private_files")):
291 if not item in includes: includes.append(item)
292 if not item in universe.private_files:
294 item = path_join(dirname(filename), item)
295 universe.private_files.append(item)
296 for section in self.data.sections():
297 if section != "__control__":
298 Element(section, universe, filename)
299 for include_file in includes:
300 if not isabs(include_file):
301 include_file = path_join(dirname(filename), include_file)
302 DataFile(include_file, universe)
303 def is_writeable(self):
304 """Returns True if the __control__ read_only is False."""
305 return not self.data.has_option("__control__", "read_only") or not self.data.getboolean("__control__", "read_only")
307 """Write the data, if necessary."""
309 # when modified, writeable and has content or the file exists
310 if self.modified and self.is_writeable() and ( self.data.sections() or exists(self.filename) ):
312 # make parent directories if necessary
313 if not exists(dirname(self.filename)):
314 makedirs(dirname(self.filename))
317 file_descriptor = file(self.filename, "w")
319 # if it's marked private, chmod it appropriately
320 if self.filename in universe.private_files and oct(S_IMODE(stat(self.filename)[ST_MODE])) != 0600:
321 chmod(self.filename, 0600)
323 # write it back sorted, instead of using ConfigParser
324 sections = self.data.sections()
326 for section in sections:
327 file_descriptor.write("[" + section + "]\n")
328 options = self.data.options(section)
330 for option in options:
331 file_descriptor.write(option + " = " + self.data.get(section, option) + "\n")
332 file_descriptor.write("\n")
334 # flush and close the file
335 file_descriptor.flush()
336 file_descriptor.close()
338 # unset the modified flag
339 self.modified = False
343 def __init__(self, filename=""):
344 """Initialize the universe."""
347 self.default_origins = {}
349 self.private_files = []
351 self.pending_events_long = {}
352 self.pending_events_short = {}
354 self.terminate_world = False
355 self.reload_modules = False
357 possible_filenames = [
363 "/usr/local/mudpy/mudpy.conf",
364 "/usr/local/mudpy/etc/mudpy.conf",
365 "/etc/mudpy/mudpy.conf",
368 for filename in possible_filenames:
369 if access(filename, R_OK): break
370 if not isabs(filename):
371 filename = abspath(filename)
372 DataFile(filename, self)
374 """Save the universe to persistent storage."""
375 for key in self.files: self.files[key].save()
377 def initialize_server_socket(self):
378 """Create and open the listening socket."""
380 # create a new ipv4 stream-type socket object
381 self.listening_socket = socket(AF_INET, SOCK_STREAM)
383 # set the socket options to allow existing open ones to be
384 # reused (fixes a bug where the server can't bind for a minute
385 # when restarting on linux systems)
386 self.listening_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
388 # bind the socket to to our desired server ipa and port
389 self.listening_socket.bind((self.categories["internal"]["network"].get("host"), self.categories["internal"]["network"].getint("port")))
391 # disable blocking so we can proceed whether or not we can
393 self.listening_socket.setblocking(0)
395 # start listening on the socket
396 self.listening_socket.listen(1)
398 # note that we're now ready for user connections
399 log("Waiting for connection(s)...")
402 """Convenience method to get the elapsed time counter."""
403 return self.categories["internal"]["counters"].getint("elapsed")
406 """This is a connected user."""
409 """Default values for the in-memory user variables."""
411 self.last_address = ""
412 self.connection = None
413 self.authenticated = False
414 self.password_tries = 0
415 self.state = "initial"
416 self.menu_seen = False
418 self.input_queue = []
419 self.output_queue = []
420 self.partial_input = ""
422 self.received_newline = True
423 self.terminator = IAC+GA
424 self.negotiation_pause = 0
429 """Log, close the connection and remove."""
430 if self.account: name = self.account.get("name")
432 if name: message = "User " + name
433 else: message = "An unnamed user"
434 message += " logged out."
436 self.deactivate_avatar()
437 self.connection.close()
441 """Save, load a new user and relocate the connection."""
443 # get out of the list
446 # create a new user object
449 # set everything else equivalent
469 exec("new_user." + attribute + " = self." + attribute)
472 universe.userlist.append(new_user)
474 # get rid of the old user object
477 def replace_old_connections(self):
478 """Disconnect active users with the same name."""
480 # the default return value
483 # iterate over each user in the list
484 for old_user in universe.userlist:
486 # the name is the same but it's not us
487 if old_user.account.get("name") == self.account.get("name") and old_user is not self:
490 log("User " + self.account.get("name") + " reconnected--closing old connection to " + old_user.address + ".", 2)
491 old_user.send("$(eol)$(red)New connection from " + self.address + ". Terminating old connection...$(nrm)$(eol)", flush=True, add_prompt=False)
493 # close the old connection
494 old_user.connection.close()
496 # replace the old connection with this one
497 old_user.send("$(eol)$(red)Taking over old connection from " + old_user.address + ".$(nrm)")
498 old_user.connection = self.connection
499 old_user.last_address = old_user.address
500 old_user.address = self.address
501 old_user.echoing = self.echoing
503 # take this one out of the list and delete
509 # true if an old connection was replaced, false if not
512 def authenticate(self):
513 """Flag the user as authenticated and disconnect duplicates."""
514 if not self.state is "authenticated":
515 log("User " + self.account.get("name") + " logged in.", 2)
516 self.authenticated = True
517 if self.account.subkey in universe.categories["internal"]["limits"].getlist("default_admins"):
518 self.account.set("administrator", "True")
521 """Send the user their current menu."""
522 if not self.menu_seen:
523 self.menu_choices = get_menu_choices(self)
524 self.send(get_menu(self.state, self.error, self.echoing, self.terminator, self.menu_choices), "")
525 self.menu_seen = True
527 self.adjust_echoing()
529 def adjust_echoing(self):
530 """Adjust echoing to match state menu requirements."""
531 if self.echoing and not menu_echo_on(self.state): self.echoing = False
532 elif not self.echoing and menu_echo_on(self.state): self.echoing = True
535 """Remove a user from the list of connected users."""
536 universe.userlist.remove(self)
538 def send(self, output, eol="$(eol)", raw=False, flush=False, add_prompt=True, just_prompt=False):
539 """Send arbitrary text to a connected user."""
541 # unless raw mode is on, clean it up all nice and pretty
544 # strip extra $(eol) off if present
545 while output.startswith("$(eol)"): output = output[6:]
546 while output.endswith("$(eol)"): output = output[:-6]
548 # we'll take out GA or EOR and add them back on the end
549 if output.endswith(IAC+GA) or output.endswith(IAC+EOR):
552 else: terminate = False
554 # start with a newline, append the message, then end
555 # with the optional eol string passed to this function
556 # and the ansi escape to return to normal text
557 if not just_prompt: output = "$(eol)$(eol)" + output
558 output += eol + chr(27) + "[0m"
560 # tack on a prompt if active
561 if self.state == "active":
562 if not just_prompt: output += "$(eol)"
563 if add_prompt: output += "> "
565 # find and replace macros in the output
566 output = replace_macros(self, output)
568 # wrap the text at 80 characters
569 output = wrap_ansi_text(output, 80)
571 # tack the terminator back on
572 if terminate: output += self.terminator
574 # drop the output into the user's output queue
575 self.output_queue.append(output)
577 # if this is urgent, flush all pending output
578 if flush: self.flush()
581 """All the things to do to the user per increment."""
583 # if the world is terminating, disconnect
584 if universe.terminate_world:
585 self.state = "disconnecting"
586 self.menu_seen = False
588 # if output is paused, decrement the counter
589 if self.state == "initial":
590 if self.negotiation_pause: self.negotiation_pause -= 1
591 else: self.state = "entering_account_name"
593 # show the user a menu as needed
594 elif not self.state == "active": self.show_menu()
596 # flush any pending output in teh queue
599 # disconnect users with the appropriate state
600 if self.state == "disconnecting": self.quit()
602 # check for input and add it to the queue
605 # there is input waiting in the queue
606 if self.input_queue: handle_user_input(self)
609 """Try to send the last item in the queue and remove it."""
610 if self.output_queue:
611 if self.received_newline:
612 self.received_newline = False
613 if self.output_queue[0].startswith("\r\n"):
614 self.output_queue[0] = self.output_queue[0][2:]
616 self.connection.send(self.output_queue[0])
617 del self.output_queue[0]
622 def enqueue_input(self):
623 """Process and enqueue any new input."""
625 # check for some input
627 input_data = self.connection.recv(1024)
634 # tack this on to any previous partial
635 self.partial_input += input_data
637 # reply to and remove any IAC negotiation codes
638 self.negotiate_telnet_options()
640 # separate multiple input lines
641 new_input_lines = self.partial_input.split("\n")
643 # if input doesn't end in a newline, replace the
644 # held partial input with the last line of it
645 if not self.partial_input.endswith("\n"):
646 self.partial_input = new_input_lines.pop()
648 # otherwise, chop off the extra null input and reset
649 # the held partial input
651 new_input_lines.pop()
652 self.partial_input = ""
654 # iterate over the remaining lines
655 for line in new_input_lines:
657 # remove a trailing carriage return
658 if line.endswith("\r"): line = line.rstrip("\r")
660 # log non-printable characters remaining
661 removed = filter(lambda x: (x < " " or x > "~"), line)
663 logline = "Non-printable characters from "
664 if self.account and self.account.get("name"): logline += self.account.get("name") + ": "
665 else: logline += "unknown user: "
666 logline += repr(removed)
669 # filter out non-printables
670 line = filter(lambda x: " " <= x <= "~", line)
672 # strip off extra whitespace
675 # put on the end of the queue
676 self.input_queue.append(line)
678 def negotiate_telnet_options(self):
679 """Reply to/remove partial_input telnet negotiation options."""
681 # start at the begining of the input
684 # make a local copy to play with
685 text = self.partial_input
687 # as long as we haven't checked it all
688 while position < len(text):
690 # jump to the first IAC you find
691 position = text.find(IAC, position)
693 # if there wasn't an IAC in the input, skip to the end
694 if position < 0: position = len(text)
696 # replace a double (literal) IAC if there's an LF later
697 elif len(text) > position+1 and text[position+1] == IAC:
698 if text.find("\n", position) > 0: text = text.replace(IAC+IAC, IAC)
702 # this must be an option negotiation
703 elif len(text) > position+2 and text[position+1] in (DO, DONT, WILL, WONT):
705 negotiation = text[position+1:position+3]
707 # if we turned echo off, ignore the confirmation
708 if not self.echoing and negotiation == DO+ECHO: pass
711 elif negotiation == WILL+LINEMODE: self.send(IAC+DO+LINEMODE, raw=True)
713 # if the client likes EOR instead of GA, make a note of it
714 elif negotiation == DO+EOR: self.terminator = IAC+EOR
715 elif negotiation == DONT+EOR and self.terminator == IAC+EOR:
716 self.terminator = IAC+GA
718 # if the client doesn't want GA, oblige
719 elif negotiation == DO+SGA and self.terminator == IAC+GA:
721 self.send(IAC+WILL+SGA, raw=True)
723 # we don't want to allow anything else
724 elif text[position+1] == DO: self.send(IAC+WONT+text[position+2], raw=True)
725 elif text[position+1] == WILL: self.send(IAC+DONT+text[position+2], raw=True)
727 # strip the negotiation from the input
728 text = text.replace(text[position:position+3], "")
730 # get rid of IAC SB .* IAC SE
731 elif len(text) > position+4 and text[position:position+2] == IAC+SB:
732 end_subnegotiation = text.find(IAC+SE, position)
733 if end_subnegotiation > 0: text = text[:position] + text[end_subnegotiation+2:]
736 # otherwise, strip out a two-byte IAC command
737 elif len(text) > position+2: text = text.replace(text[position:position+2], "")
739 # and this means we got the begining of an IAC
742 # replace the input with our cleaned-up text
743 self.partial_input = text
745 def new_avatar(self):
746 """Instantiate a new, unconfigured avatar for this user."""
748 while "avatar:" + self.account.get("name") + ":" + str(counter) in universe.categories["actor"].keys(): counter += 1
749 self.avatar = Element("actor:avatar:" + self.account.get("name") + ":" + str(counter), universe)
750 self.avatar.append("inherit", "archetype:avatar")
751 self.account.append("avatars", self.avatar.key)
753 def delete_avatar(self, avatar):
754 """Remove an avatar from the world and from the user's list."""
755 if self.avatar is universe.contents[avatar]: self.avatar = None
756 universe.contents[avatar].destroy()
757 avatars = self.account.getlist("avatars")
758 avatars.remove(avatar)
759 self.account.set("avatars", avatars)
761 def activate_avatar_by_index(self, index):
762 """Enter the world with a particular indexed avatar."""
763 self.avatar = universe.contents[self.account.getlist("avatars")[index]]
764 self.avatar.owner = self
765 self.state = "active"
766 self.avatar.go_home()
768 def deactivate_avatar(self):
769 """Have the active avatar leave the world."""
771 current = self.avatar.get("location")
772 self.avatar.set("default_location", current)
773 self.avatar.echo_to_location("You suddenly wonder where " + self.avatar.get("name") + " went.")
774 del universe.contents[current].contents[self.avatar.key]
775 self.avatar.remove_facet("location")
776 self.avatar.owner = None
780 """Destroy the user and associated avatars."""
781 for avatar in self.account.getlist("avatars"): self.delete_avatar(avatar)
782 self.account.destroy()
784 def list_avatar_names(self):
785 """List names of assigned avatars."""
786 return [ universe.contents[avatar].get("name") for avatar in self.account.getlist("avatars") ]
789 """Turn string into list type."""
790 if value[0] + value[-1] == "[]": return eval(value)
791 else: return [ value ]
794 """Turn string into dict type."""
795 if value[0] + value[-1] == "{}": return eval(value)
796 elif value.find(":") > 0: return eval("{" + value + "}")
797 else: return { value: None }
799 def broadcast(message, add_prompt=True):
800 """Send a message to all connected users."""
801 for each_user in universe.userlist: each_user.send("$(eol)" + message, add_prompt=add_prompt)
803 def log(message, level=0):
806 # a couple references we need
807 file_name = universe.categories["internal"]["logging"].get("file")
808 max_log_lines = universe.categories["internal"]["logging"].getint("max_log_lines")
809 syslog_name = universe.categories["internal"]["logging"].get("syslog")
810 timestamp = asctime()[4:19]
812 # turn the message into a list of lines
813 lines = filter(lambda x: x!="", [(x.rstrip()) for x in message.split("\n")])
815 # send the timestamp and line to a file
817 file_descriptor = file(file_name, "a")
818 for line in lines: file_descriptor.write(timestamp + " " + line + "\n")
819 file_descriptor.flush()
820 file_descriptor.close()
822 # send the timestamp and line to standard output
823 if universe.categories["internal"]["logging"].getboolean("stdout"):
824 for line in lines: print(timestamp + " " + line)
826 # send the line to the system log
828 openlog(syslog_name, LOG_PID, LOG_INFO | LOG_DAEMON)
829 for line in lines: syslog(line)
832 # display to connected administrators
833 for user in universe.userlist:
834 if user.state == "active" and user.account.getboolean("administrator") and user.account.getint("loglevel") <= level:
835 # iterate over every line in the message
838 full_message += "$(bld)$(red)" + timestamp + " " + line + "$(nrm)$(eol)"
839 user.send(full_message, flush=True)
841 # add to the recent log list
843 while 0 < len(universe.loglines) >= max_log_lines: del universe.loglines[0]
844 universe.loglines.append((level, timestamp + " " + line))
846 def get_loglines(level, start, stop=0):
847 """Return a specific range of loglines filtered by level."""
849 # begin with a blank message
852 # filter the log lines
853 loglines = filter(lambda x,y: x>=level, universe.loglines)
855 # we need this in several places
856 count = len(loglines)
858 # don't proceed if there are no lines
861 # can't start before the begining or at the end
862 if start > count: start = count
863 if start < 1: start = 1
865 # can't stop before we start
866 if stop >= start: stop = start - 1
869 message += "There are " + str(len(universe.loglist))
870 message += " log lines in memory and " + str(count)
871 message += " at or above level " + str(level) + "."
872 message += " The lines from " + str(stop)
873 message += " to " + str(start) + " are:$(eol)$(eol)"
875 # add the text from the selected lines
876 for line in loglines[-start:-stop]:
877 message += " " + line[1] + "$(eol)"
882 def wrap_ansi_text(text, width):
883 """Wrap text with arbitrary width while ignoring ANSI colors."""
885 # the current position in the entire text string, including all
886 # characters, printable or otherwise
887 absolute_position = 0
889 # the current text position relative to the begining of the line,
890 # ignoring color escape sequences
891 relative_position = 0
893 # whether the current character is part of a color escape sequence
896 # iterate over each character from the begining of the text
897 for each_character in text:
899 # the current character is the escape character
900 if each_character == chr(27):
903 # the current character is within an escape sequence
906 # the current character is m, which terminates the
907 # current escape sequence
908 if each_character == "m":
911 # the current character is a newline, so reset the relative
912 # position (start a new line)
913 elif each_character == "\n":
914 relative_position = 0
916 # the current character meets the requested maximum line width,
917 # so we need to backtrack and find a space at which to wrap
918 elif relative_position == width:
920 # distance of the current character examined from the
924 # count backwards until we find a space
925 while text[absolute_position - wrap_offset] != " ":
928 # insert an eol in place of the space
929 text = text[:absolute_position - wrap_offset] + "\r\n" + text[absolute_position - wrap_offset + 1:]
931 # increase the absolute position because an eol is two
932 # characters but the space it replaced was only one
933 absolute_position += 1
935 # now we're at the begining of a new line, plus the
936 # number of characters wrapped from the previous line
937 relative_position = wrap_offset
939 # as long as the character is not a carriage return and the
940 # other above conditions haven't been met, count it as a
941 # printable character
942 elif each_character != "\r":
943 relative_position += 1
945 # increase the absolute position for every character
946 absolute_position += 1
948 # return the newly-wrapped text
951 def weighted_choice(data):
952 """Takes a dict weighted by value and returns a random key."""
954 # this will hold our expanded list of keys from the data
957 # create thee expanded list of keys
958 for key in data.keys():
959 for count in range(data[key]):
962 # return one at random
963 return choice(expanded)
966 """Returns a random character name."""
968 # the vowels and consonants needed to create romaji syllables
969 vowels = [ "a", "i", "u", "e", "o" ]
970 consonants = ["'", "k", "z", "s", "sh", "z", "j", "t", "ch", "ts", "d", "n", "h", "f", "m", "y", "r", "w" ]
972 # this dict will hold our weighted list of syllables
975 # generate the list with an even weighting
976 for consonant in consonants:
978 syllables[consonant + vowel] = 1
980 # we'll build the name into this string
983 # create a name of random length from the syllables
984 for syllable in range(randrange(2, 6)):
985 name += weighted_choice(syllables)
987 # strip any leading quotemark, capitalize and return the name
988 return name.strip("'").capitalize()
990 def replace_macros(user, text, is_input=False):
991 """Replaces macros in text output."""
996 # third person pronouns
998 "female": { "obj": "her", "pos": "hers", "sub": "she" },
999 "male": { "obj": "him", "pos": "his", "sub": "he" },
1000 "neuter": { "obj": "it", "pos": "its", "sub": "it" }
1003 # a dict of replacement macros
1006 "$(bld)": chr(27) + "[1m",
1007 "$(nrm)": chr(27) + "[0m",
1008 "$(blk)": chr(27) + "[30m",
1009 "$(blu)": chr(27) + "[34m",
1010 "$(cyn)": chr(27) + "[36m",
1011 "$(grn)": chr(27) + "[32m",
1012 "$(mgt)": chr(27) + "[35m",
1013 "$(red)": chr(27) + "[31m",
1014 "$(yel)": chr(27) + "[33m",
1017 # add dynamic macros where possible
1019 account_name = user.account.get("name")
1021 macros["$(account)"] = account_name
1023 avatar_gender = user.avatar.get("gender")
1025 macros["$(tpop)"] = pronouns[avatar_gender]["obj"]
1026 macros["$(tppp)"] = pronouns[avatar_gender]["pos"]
1027 macros["$(tpsp)"] = pronouns[avatar_gender]["sub"]
1029 # find and replace per the macros dict
1030 macro_start = text.find("$(")
1031 if macro_start == -1: break
1032 macro_end = text.find(")", macro_start) + 1
1033 macro = text[macro_start:macro_end]
1034 if macro in macros.keys():
1035 text = text.replace(macro, macros[macro])
1037 # if we get here, log and replace it with null
1039 text = text.replace(macro, "")
1041 log("Unexpected replacement macro " + macro + " encountered.", 6)
1043 # replace the look-like-a-macro sequence
1044 text = text.replace("$_(", "$(")
1048 def escape_macros(text):
1049 """Escapes replacement macros in text."""
1050 return text.replace("$(", "$_(")
1052 def check_time(frequency):
1053 """Check for a factor of the current increment count."""
1054 if type(frequency) is str:
1055 frequency = universe.categories["internal"]["time"].getint(frequency)
1056 if not "counters" in universe.categories["internal"]:
1057 Element("internal:counters", universe)
1058 return not universe.categories["internal"]["counters"].getint("elapsed") % frequency
1061 """The things which should happen on each pulse, aside from reloads."""
1063 # open the listening socket if it hasn't been already
1064 if not hasattr(universe, "listening_socket"):
1065 universe.initialize_server_socket()
1067 # assign a user if a new connection is waiting
1068 user = check_for_connection(universe.listening_socket)
1069 if user: universe.userlist.append(user)
1071 # iterate over the connected users
1072 for user in universe.userlist: user.pulse()
1074 # update the log every now and then
1075 if check_time("frequency_log"):
1076 log(str(len(universe.userlist)) + " connection(s)")
1078 # periodically save everything
1079 if check_time("frequency_save"):
1082 # pause for a configurable amount of time (decimal seconds)
1083 sleep(universe.categories["internal"]["time"].getfloat("increment"))
1085 # increment the elapsed increment counter
1086 universe.categories["internal"]["counters"].set("elapsed", universe.categories["internal"]["counters"].getint("elapsed") + 1)
1089 """Reload data into new persistent objects."""
1090 for user in universe.userlist[:]: user.reload()
1092 def check_for_connection(listening_socket):
1093 """Check for a waiting connection and return a new user object."""
1095 # try to accept a new connection
1097 connection, address = listening_socket.accept()
1101 # note that we got one
1102 log("Connection from " + address[0], 2)
1104 # disable blocking so we can proceed whether or not we can send/receive
1105 connection.setblocking(0)
1107 # create a new user object
1110 # associate this connection with it
1111 user.connection = connection
1113 # set the user's ipa from the connection's ipa
1114 user.address = address[0]
1116 # let the client know we WILL EOR
1117 user.send(IAC+WILL+EOR, raw=True)
1118 user.negotiation_pause = 2
1120 # return the new user object
1123 def get_menu(state, error=None, echoing=True, terminator="", choices=None):
1124 """Show the correct menu text to a user."""
1126 # make sure we don't reuse a mutable sequence by default
1127 if choices is None: choices = {}
1129 # begin with a telnet echo command sequence if needed
1130 message = get_echo_sequence(state, echoing)
1132 # get the description or error text
1133 message += get_menu_description(state, error)
1135 # get menu choices for the current state
1136 message += get_formatted_menu_choices(state, choices)
1138 # try to get a prompt, if it was defined
1139 message += get_menu_prompt(state)
1141 # throw in the default choice, if it exists
1142 message += get_formatted_default_menu_choice(state)
1144 # display a message indicating if echo is off
1145 message += get_echo_message(state)
1147 # tack on EOR or GA to indicate the prompt will not be followed by CRLF
1148 message += terminator
1150 # return the assembly of various strings defined above
1153 def menu_echo_on(state):
1154 """True if echo is on, false if it is off."""
1155 return universe.categories["menu"][state].getboolean("echo", True)
1157 def get_echo_sequence(state, echoing):
1158 """Build the appropriate IAC WILL/WONT ECHO sequence as needed."""
1160 # if the user has echo on and the menu specifies it should be turned
1161 # off, send: iac + will + echo + null
1162 if echoing and not menu_echo_on(state): return IAC+WILL+ECHO
1164 # if echo is not set to off in the menu and the user curently has echo
1165 # off, send: iac + wont + echo + null
1166 elif not echoing and menu_echo_on(state): return IAC+WONT+ECHO
1168 # default is not to send an echo control sequence at all
1171 def get_echo_message(state):
1172 """Return a message indicating that echo is off."""
1173 if menu_echo_on(state): return ""
1174 else: return "(won't echo) "
1176 def get_default_menu_choice(state):
1177 """Return the default choice for a menu."""
1178 return universe.categories["menu"][state].get("default")
1180 def get_formatted_default_menu_choice(state):
1181 """Default menu choice foratted for inclusion in a prompt string."""
1182 default_choice = get_default_menu_choice(state)
1183 if default_choice: return "[$(red)" + default_choice + "$(nrm)] "
1186 def get_menu_description(state, error):
1187 """Get the description or error text."""
1189 # an error condition was raised by the handler
1192 # try to get an error message matching the condition
1194 description = universe.categories["menu"][state].get("error_" + error)
1195 if not description: description = "That is not a valid choice..."
1196 description = "$(red)" + description + "$(nrm)"
1198 # there was no error condition
1201 # try to get a menu description for the current state
1202 description = universe.categories["menu"][state].get("description")
1204 # return the description or error message
1205 if description: description += "$(eol)$(eol)"
1208 def get_menu_prompt(state):
1209 """Try to get a prompt, if it was defined."""
1210 prompt = universe.categories["menu"][state].get("prompt")
1211 if prompt: prompt += " "
1214 def get_menu_choices(user):
1215 """Return a dict of choice:meaning."""
1216 menu = universe.categories["menu"][user.state]
1217 create_choices = menu.get("create")
1218 if create_choices: choices = eval(create_choices)
1223 for facet in menu.facets():
1224 if facet.startswith("demand_") and not eval(universe.categories["menu"][user.state].get(facet)):
1225 ignores.append(facet.split("_", 2)[1])
1226 elif facet.startswith("create_"):
1227 creates[facet] = facet.split("_", 2)[1]
1228 elif facet.startswith("choice_"):
1229 options[facet] = facet.split("_", 2)[1]
1230 for facet in creates.keys():
1231 if not creates[facet] in ignores:
1232 choices[creates[facet]] = eval(menu.get(facet))
1233 for facet in options.keys():
1234 if not options[facet] in ignores:
1235 choices[options[facet]] = menu.get(facet)
1238 def get_formatted_menu_choices(state, choices):
1239 """Returns a formatted string of menu choices."""
1241 choice_keys = choices.keys()
1243 for choice in choice_keys:
1244 choice_output += " [$(red)" + choice + "$(nrm)] " + choices[choice] + "$(eol)"
1245 if choice_output: choice_output += "$(eol)"
1246 return choice_output
1248 def get_menu_branches(state):
1249 """Return a dict of choice:branch."""
1251 for facet in universe.categories["menu"][state].facets():
1252 if facet.startswith("branch_"):
1253 branches[facet.split("_", 2)[1]] = universe.categories["menu"][state].get(facet)
1256 def get_default_branch(state):
1257 """Return the default branch."""
1258 return universe.categories["menu"][state].get("branch")
1260 def get_choice_branch(user, choice):
1261 """Returns the new state matching the given choice."""
1262 branches = get_menu_branches(user.state)
1263 if choice in branches.keys(): return branches[choice]
1264 elif choice in user.menu_choices.keys(): return get_default_branch(user.state)
1267 def get_menu_actions(state):
1268 """Return a dict of choice:branch."""
1270 for facet in universe.categories["menu"][state].facets():
1271 if facet.startswith("action_"):
1272 actions[facet.split("_", 2)[1]] = universe.categories["menu"][state].get(facet)
1275 def get_default_action(state):
1276 """Return the default action."""
1277 return universe.categories["menu"][state].get("action")
1279 def get_choice_action(user, choice):
1280 """Run any indicated script for the given choice."""
1281 actions = get_menu_actions(user.state)
1282 if choice in actions.keys(): return actions[choice]
1283 elif choice in user.menu_choices.keys(): return get_default_action(user.state)
1286 def handle_user_input(user):
1287 """The main handler, branches to a state-specific handler."""
1289 # check to make sure the state is expected, then call that handler
1290 if "handler_" + user.state in globals():
1291 exec("handler_" + user.state + "(user)")
1293 generic_menu_handler(user)
1295 # since we got input, flag that the menu/prompt needs to be redisplayed
1296 user.menu_seen = False
1298 # if the user's client echo is off, send a blank line for aesthetics
1299 if user.echoing: user.received_newline = True
1301 def generic_menu_handler(user):
1302 """A generic menu choice handler."""
1304 # get a lower-case representation of the next line of input
1305 if user.input_queue:
1306 choice = user.input_queue.pop(0)
1307 if choice: choice = choice.lower()
1309 if not choice: choice = get_default_menu_choice(user.state)
1310 if choice in user.menu_choices:
1311 exec(get_choice_action(user, choice))
1312 new_state = get_choice_branch(user, choice)
1313 if new_state: user.state = new_state
1314 else: user.error = "default"
1316 def handler_entering_account_name(user):
1317 """Handle the login account name."""
1319 # get the next waiting line of input
1320 input_data = user.input_queue.pop(0)
1322 # did the user enter anything?
1325 # keep only the first word and convert to lower-case
1326 name = input_data.lower()
1328 # fail if there are non-alphanumeric characters
1329 if name != filter(lambda x: x>="0" and x<="9" or x>="a" and x<="z", name):
1330 user.error = "bad_name"
1332 # if that account exists, time to request a password
1333 elif name in universe.categories["account"]:
1334 user.account = universe.categories["account"][name]
1335 user.state = "checking_password"
1337 # otherwise, this could be a brand new user
1339 user.account = Element("account:" + name, universe)
1340 user.account.set("name", name)
1341 log("New user: " + name, 2)
1342 user.state = "checking_new_account_name"
1344 # if the user entered nothing for a name, then buhbye
1346 user.state = "disconnecting"
1348 def handler_checking_password(user):
1349 """Handle the login account password."""
1351 # get the next waiting line of input
1352 input_data = user.input_queue.pop(0)
1354 # does the hashed input equal the stored hash?
1355 if new_md5(user.account.get("name") + input_data).hexdigest() == user.account.get("passhash"):
1357 # if so, set the username and load from cold storage
1358 if not user.replace_old_connections():
1360 user.state = "main_utility"
1362 # if at first your hashes don't match, try, try again
1363 elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
1364 user.password_tries += 1
1365 user.error = "incorrect"
1367 # we've exceeded the maximum number of password failures, so disconnect
1369 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
1370 user.state = "disconnecting"
1372 def handler_entering_new_password(user):
1373 """Handle a new password entry."""
1375 # get the next waiting line of input
1376 input_data = user.input_queue.pop(0)
1378 # make sure the password is strong--at least one upper, one lower and
1379 # one digit, seven or more characters in length
1380 if len(input_data) > 6 and len(filter(lambda x: x>="0" and x<="9", input_data)) and len(filter(lambda x: x>="A" and x<="Z", input_data)) and len(filter(lambda x: x>="a" and x<="z", input_data)):
1382 # hash and store it, then move on to verification
1383 user.account.set("passhash", new_md5(user.account.get("name") + input_data).hexdigest())
1384 user.state = "verifying_new_password"
1386 # the password was weak, try again if you haven't tried too many times
1387 elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
1388 user.password_tries += 1
1391 # too many tries, so adios
1393 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
1394 user.account.destroy()
1395 user.state = "disconnecting"
1397 def handler_verifying_new_password(user):
1398 """Handle the re-entered new password for verification."""
1400 # get the next waiting line of input
1401 input_data = user.input_queue.pop(0)
1403 # hash the input and match it to storage
1404 if new_md5(user.account.get("name") + input_data).hexdigest() == user.account.get("passhash"):
1407 # the hashes matched, so go active
1408 if not user.replace_old_connections(): user.state = "main_utility"
1410 # go back to entering the new password as long as you haven't tried
1412 elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
1413 user.password_tries += 1
1414 user.error = "differs"
1415 user.state = "entering_new_password"
1417 # otherwise, sayonara
1419 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
1420 user.account.destroy()
1421 user.state = "disconnecting"
1423 def handler_active(user):
1424 """Handle input for active users."""
1426 # get the next waiting line of input
1427 input_data = user.input_queue.pop(0)
1432 # split out the command (first word) and parameters (everything else)
1433 if input_data.find(" ") > 0:
1434 command_name, parameters = input_data.split(" ", 1)
1436 command_name = input_data
1439 # lowercase the command
1440 command_name = command_name.lower()
1442 # the command matches a command word for which we have data
1443 if command_name in universe.categories["command"]:
1444 command = universe.categories["command"][command_name]
1445 else: command = None
1447 # if it's allowed, do it
1448 if user.avatar.can_run(command): exec(command.get("action"))
1450 # otherwise, give an error
1451 elif command_name: command_error(user.avatar, input_data)
1453 # if no input, just idle back with a prompt
1454 else: user.send("", just_prompt=True)
1456 def command_halt(actor, parameters):
1457 """Halt the world."""
1460 # see if there's a message or use a generic one
1461 if parameters: message = "Halting: " + parameters
1462 else: message = "User " + actor.owner.account.get("name") + " halted the world."
1465 broadcast(message, add_prompt=False)
1468 # set a flag to terminate the world
1469 universe.terminate_world = True
1471 def command_reload(actor):
1472 """Reload all code modules, configs and data."""
1475 # let the user know and log
1476 actor.send("Reloading all code modules, configs and data.")
1477 log("User " + actor.owner.account.get("name") + " reloaded the world.", 8)
1479 # set a flag to reload
1480 universe.reload_modules = True
1482 def command_quit(actor):
1483 """Leave the world and go back to the main menu."""
1485 actor.owner.deactivate_avatar()
1486 actor.owner.state = "main_utility"
1488 def command_help(actor, parameters):
1489 """List available commands and provide help for commands."""
1491 # did the user ask for help on a specific command word?
1492 if parameters and actor.owner:
1494 # is the command word one for which we have data?
1495 if parameters in universe.categories["command"]:
1496 command = universe.categories["command"][parameters]
1497 else: command = None
1499 # only for allowed commands
1500 if actor.can_run(command):
1502 # add a description if provided
1503 description = command.get("description")
1505 description = "(no short description provided)"
1506 if command.getboolean("administrative"): output = "$(red)"
1507 else: output = "$(grn)"
1508 output += parameters + "$(nrm) - " + description + "$(eol)$(eol)"
1510 # add the help text if provided
1511 help_text = command.get("help")
1513 help_text = "No help is provided for this command."
1516 # no data for the requested command word
1518 output = "That is not an available command."
1520 # no specific command word was indicated
1523 # give a sorted list of commands with descriptions if provided
1524 output = "These are the commands available to you:$(eol)$(eol)"
1525 sorted_commands = universe.categories["command"].keys()
1526 sorted_commands.sort()
1527 for item in sorted_commands:
1528 command = universe.categories["command"][item]
1529 if actor.can_run(command):
1530 description = command.get("description")
1532 description = "(no short description provided)"
1533 if command.getboolean("administrative"): output += " $(red)"
1534 else: output += " $(grn)"
1535 output += item + "$(nrm) - " + description + "$(eol)"
1536 output += "$(eol)Enter \"help COMMAND\" for help on a command named \"COMMAND\"."
1538 # send the accumulated output to the user
1541 def command_move(actor, parameters):
1542 """Move the avatar in a given direction."""
1543 if parameters in universe.contents[actor.get("location")].portals():
1544 actor.move_direction(parameters)
1545 else: actor.send("You cannot go that way.")
1547 def command_look(actor, parameters):
1549 if parameters: actor.send("You can't look at or in anything yet.")
1550 else: actor.look_at(actor.get("location"))
1552 def command_say(actor, parameters):
1553 """Speak to others in the same room."""
1555 # check for replacement macros
1556 if replace_macros(actor.owner, parameters, True) != parameters:
1557 actor.send("You cannot speak $_(replacement macros).")
1559 # the user entered a message
1562 # get rid of quote marks on the ends of the message and
1563 # capitalize the first letter
1564 message = parameters.strip("\"'`").capitalize()
1566 # a dictionary of punctuation:action pairs
1568 for facet in universe.categories["internal"]["language"].facets():
1569 if facet.startswith("punctuation_"):
1570 action = facet.split("_")[1]
1571 for mark in universe.categories["internal"]["language"].getlist(facet):
1572 actions[mark] = action
1574 # match the punctuation used, if any, to an action
1575 default_punctuation = universe.categories["internal"]["language"].get("default_punctuation")
1576 action = actions[default_punctuation]
1577 for mark in actions.keys():
1578 if message.endswith(mark) and mark != default_punctuation:
1579 action = actions[mark]
1582 # if the action is default and there is no mark, add one
1583 if action == actions[default_punctuation] and not message.endswith(default_punctuation):
1584 message += default_punctuation
1586 # capitalize a list of words within the message
1587 capitalize_words = universe.categories["internal"]["language"].getlist("capitalize_words")
1588 for word in capitalize_words:
1589 message = message.replace(" " + word + " ", " " + word.capitalize() + " ")
1592 actor.echo_to_location(actor.get("name") + " " + action + "s, \"" + message + "\"")
1593 actor.send("You " + action + ", \"" + message + "\"")
1595 # there was no message
1597 actor.send("What do you want to say?")
1599 def command_show(actor, parameters):
1600 """Show program data."""
1602 if parameters.find(" ") < 1:
1603 if parameters == "time":
1604 message = universe.categories["internal"]["counters"].get("elapsed") + " increments elapsed since the world was created."
1605 elif parameters == "categories":
1606 message = "These are the element categories:$(eol)"
1607 categories = universe.categories.keys()
1609 for category in categories: message += "$(eol) $(grn)" + category + "$(nrm)"
1610 elif parameters == "files":
1611 message = "These are the current files containing the universe:$(eol)"
1612 filenames = universe.files.keys()
1614 for filename in filenames: message += "$(eol) $(grn)" + filename + "$(nrm)"
1617 arguments = parameters.split()
1618 if arguments[0] == "category":
1619 if arguments[1] in universe.categories:
1620 message = "These are the elements in the \"" + arguments[1] + "\" category:$(eol)"
1621 elements = universe.categories[arguments[1]].keys()
1623 for element in elements:
1624 message += "$(eol) $(grn)" + universe.categories[arguments[1]][element].key + "$(nrm)"
1625 elif arguments[0] == "element":
1626 if arguments[1] in universe.contents:
1627 message = "These are the properties of the \"" + arguments[1] + "\" element:$(eol)"
1628 element = universe.contents[arguments[1]]
1629 facets = element.facets()
1631 for facet in facets:
1632 message += "$(eol) $(grn)" + facet + ": $(red)" + escape_macros(element.get(facet)) + "$(nrm)"
1633 elif arguments[0] == "result":
1634 if len(arguments) > 1:
1636 message = repr(eval(" ".join(arguments[1:])))
1638 message = "Your expression raised an exception!"
1639 elif arguments[0] == "log":
1640 if match("^\d+$", arguments[1]) and int(arguments[1]) > 0:
1641 linecount = int(arguments[1])
1642 if linecount > len(universe.loglines): linecount = len(universe.loglist)
1643 message = "There are " + str(len(universe.loglist)) + " log lines in memory."
1644 message += " The most recent " + str(linecount) + " lines are:$(eol)$(eol)"
1645 for line in universe.loglist[-linecount:]:
1646 message += " " + line + "$(eol)"
1647 else: message = "\"" + arguments[1] + "\" is not a positive integer greater than 0."
1649 if parameters: message = "I don't know what \"" + parameters + "\" is."
1650 else: message = "What do you want to show?"
1653 def command_create(actor, parameters):
1654 """Create an element if it does not exist."""
1655 if not parameters: message = "You must at least specify an element to create."
1656 elif not actor.owner: message = ""
1658 arguments = parameters.split()
1659 if len(arguments) == 1: arguments.append("")
1660 if len(arguments) == 2:
1661 element, filename = arguments
1662 if element in universe.contents: message = "The \"" + element + "\" element already exists."
1664 message = "You create \"" + element + "\" within the universe."
1665 logline = actor.owner.account.get("name") + " created an element: " + element
1667 logline += " in file " + filename
1668 if filename not in universe.files:
1669 message += " Warning: \"" + filename + "\" is not yet included in any other file and will not be read on startup unless this is remedied."
1670 Element(element, universe, filename)
1672 elif len(arguments) > 2: message = "You can only specify an element and a filename."
1675 def command_destroy(actor, parameters):
1676 """Destroy an element if it exists."""
1678 if not parameters: message = "You must specify an element to destroy."
1680 if parameters not in universe.contents: message = "The \"" + parameters + "\" element does not exist."
1682 universe.contents[parameters].destroy()
1683 message = "You destroy \"" + parameters + "\" within the universe."
1684 log(actor.owner.account.get("name") + " destroyed an element: " + parameters, 6)
1687 def command_set(actor, parameters):
1688 """Set a facet of an element."""
1689 if not parameters: message = "You must specify an element, a facet and a value."
1691 arguments = parameters.split(" ", 2)
1692 if len(arguments) == 1: message = "What facet of element \"" + arguments[0] + "\" would you like to set?"
1693 elif len(arguments) == 2: message = "What value would you like to set for the \"" + arguments[1] + "\" facet of the \"" + arguments[0] + "\" element?"
1695 element, facet, value = arguments
1696 if element not in universe.contents: message = "The \"" + element + "\" element does not exist."
1698 universe.contents[element].set(facet, value)
1699 message = "You have successfully (re)set the \"" + facet + "\" facet of element \"" + element + "\". Try \"show element " + element + "\" for verification."
1702 def command_delete(actor, parameters):
1703 """Delete a facet from an element."""
1704 if not parameters: message = "You must specify an element and a facet."
1706 arguments = parameters.split(" ")
1707 if len(arguments) == 1: message = "What facet of element \"" + arguments[0] + "\" would you like to delete?"
1708 elif len(arguments) != 2: message = "You may only specify an element and a facet."
1710 element, facet = arguments
1711 if element not in universe.contents: message = "The \"" + element + "\" element does not exist."
1712 elif facet not in universe.contents[element].facets(): message = "The \"" + element + "\" element has no \"" + facet + "\" facet."
1714 universe.contents[element].remove_facet(facet)
1715 message = "You have successfully deleted the \"" + facet + "\" facet of element \"" + element + "\". Try \"show element " + element + "\" for verification."
1718 def command_error(actor, input_data):
1719 """Generic error for an unrecognized command word."""
1721 # 90% of the time use a generic error
1723 message = "I'm not sure what \"" + input_data + "\" means..."
1725 # 10% of the time use the classic diku error
1727 message = "Arglebargle, glop-glyf!?!"
1729 # send the error message
1732 # if there is no universe, create an empty one
1733 if not "universe" in locals(): universe = Universe()