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=""):
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 # keep track of our key name
53 # parse out appropriate category and subkey names, add to list
54 if self.key.find(":") > 0:
55 self.category, self.subkey = self.key.split(":", 1)
57 self.category = "other"
58 self.subkey = self.key
59 if not self.category in universe.categories: self.category = "other"
60 universe.categories[self.category][self.subkey] = self
62 # get an appropriate filename for the origin
63 if not filename: filename = universe.default_origins[self.category]
64 if not isabs(filename): filename = abspath(filename)
66 # add the file if it doesn't exist yet
67 if not filename in universe.files: DataFile(filename, universe)
69 # record a pointer to the origin file
70 self.origin = universe.files[filename]
72 # add a data section to the origin if necessary
73 if not self.origin.data.has_section(self.key):
74 self.origin.data.add_section(self.key)
76 # add this element to the universe contents
77 universe.contents[self.key] = self
80 """Remove an element from the universe and destroy it."""
81 log("Destroying: " + self.key + ".", 2)
82 self.origin.data.remove_section(self.key)
83 del universe.categories[self.category][self.subkey]
84 del universe.contents[self.key]
87 """Return a list of non-inherited facets for this element."""
88 if self.key in self.origin.data.sections():
89 return self.origin.data.options(self.key)
91 def has_facet(self, facet):
92 """Return whether the non-inherited facet exists."""
93 return facet in self.facets()
94 def remove_facet(self, facet):
95 """Remove a facet from the element."""
96 if self.has_facet(facet):
97 self.origin.data.remove_option(self.key, facet)
98 self.origin.modified = True
100 """Return a list of the element's inheritance lineage."""
101 if self.has_facet("inherit"):
102 ancestry = self.getlist("inherit")
103 for parent in ancestry[:]:
104 ancestors = universe.contents[parent].ancestry()
105 for ancestor in ancestors:
106 if ancestor not in ancestry: ancestry.append(ancestor)
109 def get(self, facet, default=None):
110 """Retrieve values."""
111 if default is None: default = ""
112 if self.origin.data.has_option(self.key, facet):
113 return self.origin.data.get(self.key, facet)
114 elif self.has_facet("inherit"):
115 for ancestor in self.ancestry():
116 if universe.contents[ancestor].has_facet(facet):
117 return universe.contents[ancestor].get(facet)
119 def getboolean(self, facet, default=None):
120 """Retrieve values as boolean type."""
121 if default is None: default=False
122 if self.origin.data.has_option(self.key, facet):
123 return self.origin.data.getboolean(self.key, facet)
124 elif self.has_facet("inherit"):
125 for ancestor in self.ancestry():
126 if universe.contents[ancestor].has_facet(facet):
127 return universe.contents[ancestor].getboolean(facet)
129 def getint(self, facet, default=None):
130 """Return values as int/long type."""
131 if default is None: default = 0
132 if self.origin.data.has_option(self.key, facet):
133 return self.origin.data.getint(self.key, facet)
134 elif self.has_facet("inherit"):
135 for ancestor in self.ancestry():
136 if universe.contents[ancestor].has_facet(facet):
137 return universe.contents[ancestor].getint(facet)
139 def getfloat(self, facet, default=None):
140 """Return values as float type."""
141 if default is None: default = 0.0
142 if self.origin.data.has_option(self.key, facet):
143 return self.origin.data.getfloat(self.key, facet)
144 elif self.has_facet("inherit"):
145 for ancestor in self.ancestry():
146 if universe.contents[ancestor].has_facet(facet):
147 return universe.contents[ancestor].getfloat(facet)
149 def getlist(self, facet, default=None):
150 """Return values as list type."""
151 if default is None: default = []
152 value = self.get(facet)
153 if value: return makelist(value)
155 def getdict(self, facet, default=None):
156 """Return values as dict type."""
157 if default is None: default = {}
158 value = self.get(facet)
159 if value: return makedict(value)
161 def set(self, facet, value):
163 if not self.has_facet(facet) or not self.get(facet) == value:
164 if type(value) is long: value = str(value)
165 elif not type(value) is str: value = repr(value)
166 self.origin.data.set(self.key, facet, value)
167 self.origin.modified = True
168 def append(self, facet, value):
169 """Append value tp a list."""
170 if type(value) is long: value = str(value)
171 elif not type(value) is str: value = repr(value)
172 newlist = self.getlist(facet)
173 newlist.append(value)
174 self.set(facet, newlist)
175 def send(self, message, eol="$(eol)"):
176 """Convenience method to pass messages to an owner."""
177 if self.owner: self.owner.send(message, eol)
178 def go_to(self, location):
179 """Relocate the element to a specific location."""
180 current = self.get("location")
181 if current and self.key in universe.contents[current].contents:
182 del universe.contents[current].contents[self.key]
183 if location in universe.contents: self.set("location", location)
184 universe.contents[location].contents[self.key] = self
185 self.look_at(location)
187 """Relocate the element to its default location."""
188 self.go_to(self.get("default_location"))
189 self.echo_to_location("You suddenly realize that " + self.get("name") + " is here.")
190 def move_direction(self, direction):
191 """Relocate the element in a specified direction."""
192 self.echo_to_location(self.get("name") + " exits " + universe.categories["internal"]["directions"].getdict(direction)["exit"] + ".")
193 self.send("You exit " + universe.categories["internal"]["directions"].getdict(direction)["exit"] + ".")
194 self.go_to(universe.contents[self.get("location")].link_neighbor(direction))
195 self.echo_to_location(self.get("name") + " arrives from " + universe.categories["internal"]["directions"].getdict(direction)["enter"] + ".")
196 def look_at(self, key):
197 """Show an element to another element."""
199 element = universe.contents[key]
201 name = element.get("name")
202 if name: message += "$(cyn)" + name + "$(nrm)$(eol)"
203 description = element.get("description")
204 if description: message += description + "$(eol)"
205 portal_list = element.portals().keys()
208 message += "$(cyn)[ Exits: " + ", ".join(portal_list) + " ]$(nrm)$(eol)"
209 for element in universe.contents[self.get("location")].contents.values():
210 if element.getboolean("is_actor") and element is not self:
211 message += "$(yel)" + element.get("name") + " is here.$(nrm)$(eol)"
214 """Map the portal directions for a room to neighbors."""
216 if match("""^location:-?\d+,-?\d+,-?\d+$""", self.key):
217 coordinates = [(int(x)) for x in self.key.split(":")[1].split(",")]
218 directions = universe.categories["internal"]["directions"]
219 offsets = dict([(x, directions.getdict(x)["vector"]) for x in directions.facets()])
220 for portal in self.getlist("gridlinks"):
221 adjacent = map(lambda c,o: c+o, coordinates, offsets[portal])
222 neighbor = "location:" + ",".join([(str(x)) for x in adjacent])
223 if neighbor in universe.contents: portals[portal] = neighbor
224 for facet in self.facets():
225 if facet.startswith("link_"):
226 neighbor = self.get(facet)
227 if neighbor in universe.contents:
228 portal = facet.split("_")[1]
229 portals[portal] = neighbor
231 def link_neighbor(self, direction):
232 """Return the element linked in a given direction."""
233 portals = self.portals()
234 if direction in portals: return portals[direction]
235 def echo_to_location(self, message):
236 """Show a message to other elements in the current location."""
237 for element in universe.contents[self.get("location")].contents.values():
238 if element is not self: element.send(message)
241 """A file containing universe elements."""
242 def __init__(self, filename, universe):
243 self.modified = False
244 self.data = RawConfigParser()
245 if access(filename, R_OK): self.data.read(filename)
246 self.filename = filename
247 universe.files[filename] = self
248 if self.data.has_option("__control__", "include_files"):
249 includes = makelist(self.data.get("__control__", "include_files"))
251 if self.data.has_option("__control__", "default_files"):
252 origins = makedict(self.data.get("__control__", "default_files"))
253 for key in origins.keys():
254 if not key in includes: includes.append(key)
255 universe.default_origins[key] = origins[key]
256 if not key in universe.categories:
257 universe.categories[key] = {}
258 if self.data.has_option("__control__", "private_files"):
259 for item in makelist(self.data.get("__control__", "private_files")):
260 if not item in includes: includes.append(item)
261 if not item in universe.private_files:
263 item = path_join(dirname(filename), item)
264 universe.private_files.append(item)
265 for section in self.data.sections():
266 if section != "__control__":
267 Element(section, universe, filename)
268 for include_file in includes:
269 if not isabs(include_file):
270 include_file = path_join(dirname(filename), include_file)
271 DataFile(include_file, universe)
272 def is_writeable(self):
273 """Returns True if the __control__ read_only is False."""
274 return not self.data.has_option("__control__", "read_only") or not self.data.getboolean("__control__", "read_only")
276 """Write the data, if necessary."""
278 # when modified, writeable and has content or the file exists
279 if self.modified and self.is_writeable() and ( self.data.sections() or exists(self.filename) ):
281 # make parent directories if necessary
282 if not exists(dirname(self.filename)):
283 makedirs(dirname(self.filename))
286 file_descriptor = file(self.filename, "w")
288 # if it's marked private, chmod it appropriately
289 if self.filename in universe.private_files and oct(S_IMODE(stat(self.filename)[ST_MODE])) != 0600:
290 chmod(self.filename, 0600)
292 # write it back sorted, instead of using ConfigParser
293 sections = self.data.sections()
295 for section in sections:
296 file_descriptor.write("[" + section + "]\n")
297 options = self.data.options(section)
299 for option in options:
300 file_descriptor.write(option + " = " + self.data.get(section, option) + "\n")
301 file_descriptor.write("\n")
303 # flush and close the file
304 file_descriptor.flush()
305 file_descriptor.close()
309 def __init__(self, filename=""):
310 """Initialize the universe."""
313 self.default_origins = {}
315 self.private_files = []
318 self.terminate_world = False
319 self.reload_modules = False
321 possible_filenames = [
327 "/usr/local/mudpy/mudpy.conf",
328 "/usr/local/mudpy/etc/mudpy.conf",
329 "/etc/mudpy/mudpy.conf",
332 for filename in possible_filenames:
333 if access(filename, R_OK): break
334 if not isabs(filename):
335 filename = abspath(filename)
336 DataFile(filename, self)
338 """Save the universe to persistent storage."""
339 for key in self.files: self.files[key].save()
341 def initialize_server_socket(self):
342 """Create and open the listening socket."""
344 # create a new ipv4 stream-type socket object
345 self.listening_socket = socket(AF_INET, SOCK_STREAM)
347 # set the socket options to allow existing open ones to be
348 # reused (fixes a bug where the server can't bind for a minute
349 # when restarting on linux systems)
350 self.listening_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
352 # bind the socket to to our desired server ipa and port
353 self.listening_socket.bind((self.categories["internal"]["network"].get("host"), self.categories["internal"]["network"].getint("port")))
355 # disable blocking so we can proceed whether or not we can
357 self.listening_socket.setblocking(0)
359 # start listening on the socket
360 self.listening_socket.listen(1)
362 # note that we're now ready for user connections
363 log("Waiting for connection(s)...")
366 """This is a connected user."""
369 """Default values for the in-memory user variables."""
371 self.last_address = ""
372 self.connection = None
373 self.authenticated = False
374 self.password_tries = 0
375 self.state = "initial"
376 self.menu_seen = False
378 self.input_queue = []
379 self.output_queue = []
380 self.partial_input = ""
382 self.received_newline = True
383 self.terminator = IAC+GA
384 self.negotiation_pause = 0
389 """Log, close the connection and remove."""
390 if self.account: name = self.account.get("name")
392 if name: message = "User " + name
393 else: message = "An unnamed user"
394 message += " logged out."
396 self.deactivate_avatar()
397 self.connection.close()
401 """Save, load a new user and relocate the connection."""
403 # get out of the list
406 # create a new user object
409 # set everything else equivalent
429 exec("new_user." + attribute + " = self." + attribute)
432 universe.userlist.append(new_user)
434 # get rid of the old user object
437 def replace_old_connections(self):
438 """Disconnect active users with the same name."""
440 # the default return value
443 # iterate over each user in the list
444 for old_user in universe.userlist:
446 # the name is the same but it's not us
447 if old_user.account.get("name") == self.account.get("name") and old_user is not self:
450 log("User " + self.account.get("name") + " reconnected--closing old connection to " + old_user.address + ".", 2)
451 old_user.send("$(eol)$(red)New connection from " + self.address + ". Terminating old connection...$(nrm)$(eol)", flush=True, add_prompt=False)
453 # close the old connection
454 old_user.connection.close()
456 # replace the old connection with this one
457 old_user.send("$(eol)$(red)Taking over old connection from " + old_user.address + ".$(nrm)")
458 old_user.connection = self.connection
459 old_user.last_address = old_user.address
460 old_user.address = self.address
461 old_user.echoing = self.echoing
463 # take this one out of the list and delete
469 # true if an old connection was replaced, false if not
472 def authenticate(self):
473 """Flag the user as authenticated and disconnect duplicates."""
474 if not self.state is "authenticated":
475 log("User " + self.account.get("name") + " logged in.", 2)
476 self.authenticated = True
477 if self.account.subkey in universe.categories["internal"]["limits"].getlist("default_admins"):
478 self.account.set("administrator", "True")
481 """Send the user their current menu."""
482 if not self.menu_seen:
483 self.menu_choices = get_menu_choices(self)
484 self.send(get_menu(self.state, self.error, self.echoing, self.terminator, self.menu_choices), "")
485 self.menu_seen = True
487 self.adjust_echoing()
489 def adjust_echoing(self):
490 """Adjust echoing to match state menu requirements."""
491 if self.echoing and not menu_echo_on(self.state): self.echoing = False
492 elif not self.echoing and menu_echo_on(self.state): self.echoing = True
495 """Remove a user from the list of connected users."""
496 universe.userlist.remove(self)
498 def send(self, output, eol="$(eol)", raw=False, flush=False, add_prompt=True, just_prompt=False):
499 """Send arbitrary text to a connected user."""
501 # unless raw mode is on, clean it up all nice and pretty
504 # strip extra $(eol) off if present
505 while output.startswith("$(eol)"): output = output[6:]
506 while output.endswith("$(eol)"): output = output[:-6]
508 # we'll take out GA or EOR and add them back on the end
509 if output.endswith(IAC+GA) or output.endswith(IAC+EOR):
512 else: terminate = False
514 # start with a newline, append the message, then end
515 # with the optional eol string passed to this function
516 # and the ansi escape to return to normal text
517 if not just_prompt: output = "$(eol)$(eol)" + output
518 output += eol + chr(27) + "[0m"
520 # tack on a prompt if active
521 if self.state == "active":
522 if not just_prompt: output += "$(eol)"
523 if add_prompt: output += "> "
525 # find and replace macros in the output
526 output = replace_macros(self, output)
528 # wrap the text at 80 characters
529 output = wrap_ansi_text(output, 80)
531 # tack the terminator back on
532 if terminate: output += self.terminator
534 # drop the output into the user's output queue
535 self.output_queue.append(output)
537 # if this is urgent, flush all pending output
538 if flush: self.flush()
541 """All the things to do to the user per increment."""
543 # if the world is terminating, disconnect
544 if universe.terminate_world:
545 self.state = "disconnecting"
546 self.menu_seen = False
548 # if output is paused, decrement the counter
549 if self.state == "initial":
550 if self.negotiation_pause: self.negotiation_pause -= 1
551 else: self.state = "entering_account_name"
553 # show the user a menu as needed
554 elif not self.state == "active": self.show_menu()
556 # flush any pending output in teh queue
559 # disconnect users with the appropriate state
560 if self.state == "disconnecting": self.quit()
562 # check for input and add it to the queue
565 # there is input waiting in the queue
566 if self.input_queue: handle_user_input(self)
569 """Try to send the last item in the queue and remove it."""
570 if self.output_queue:
571 if self.received_newline:
572 self.received_newline = False
573 if self.output_queue[0].startswith("\r\n"):
574 self.output_queue[0] = self.output_queue[0][2:]
576 self.connection.send(self.output_queue[0])
577 del self.output_queue[0]
582 def enqueue_input(self):
583 """Process and enqueue any new input."""
585 # check for some input
587 input_data = self.connection.recv(1024)
594 # tack this on to any previous partial
595 self.partial_input += input_data
597 # reply to and remove any IAC negotiation codes
598 self.negotiate_telnet_options()
600 # separate multiple input lines
601 new_input_lines = self.partial_input.split("\n")
603 # if input doesn't end in a newline, replace the
604 # held partial input with the last line of it
605 if not self.partial_input.endswith("\n"):
606 self.partial_input = new_input_lines.pop()
608 # otherwise, chop off the extra null input and reset
609 # the held partial input
611 new_input_lines.pop()
612 self.partial_input = ""
614 # iterate over the remaining lines
615 for line in new_input_lines:
617 # remove a trailing carriage return
618 if line.endswith("\r"): line = line.rstrip("\r")
620 # log non-printable characters remaining
621 removed = filter(lambda x: (x < " " or x > "~"), line)
623 logline = "Non-printable characters from "
624 if self.account and self.account.get("name"): logline += self.account.get("name") + ": "
625 else: logline += "unknown user: "
626 logline += repr(removed)
629 # filter out non-printables
630 line = filter(lambda x: " " <= x <= "~", line)
632 # strip off extra whitespace
635 # put on the end of the queue
636 self.input_queue.append(line)
638 def negotiate_telnet_options(self):
639 """Reply to/remove partial_input telnet negotiation options."""
641 # start at the begining of the input
644 # make a local copy to play with
645 text = self.partial_input
647 # as long as we haven't checked it all
648 while position < len(text):
650 # jump to the first IAC you find
651 position = text.find(IAC, position)
653 # if there wasn't an IAC in the input, skip to the end
654 if position < 0: position = len(text)
656 # replace a double (literal) IAC if there's an LF later
657 elif len(text) > position+1 and text[position+1] == IAC:
658 if text.find("\n", position) > 0: text = text.replace(IAC+IAC, IAC)
662 # this must be an option negotiation
663 elif len(text) > position+2 and text[position+1] in (DO, DONT, WILL, WONT):
665 negotiation = text[position+1:position+3]
667 # if we turned echo off, ignore the confirmation
668 if not self.echoing and negotiation == DO+ECHO: pass
671 elif negotiation == WILL+LINEMODE: self.send(IAC+DO+LINEMODE, raw=True)
673 # if the client likes EOR instead of GA, make a note of it
674 elif negotiation == DO+EOR: self.terminator = IAC+EOR
675 elif negotiation == DONT+EOR and self.terminator == IAC+EOR:
676 self.terminator = IAC+GA
678 # if the client doesn't want GA, oblige
679 elif negotiation == DO+SGA and self.terminator == IAC+GA:
681 self.send(IAC+WILL+SGA, raw=True)
683 # we don't want to allow anything else
684 elif text[position+1] == DO: self.send(IAC+WONT+text[position+2], raw=True)
685 elif text[position+1] == WILL: self.send(IAC+DONT+text[position+2], raw=True)
687 # strip the negotiation from the input
688 text = text.replace(text[position:position+3], "")
690 # get rid of IAC SB .* IAC SE
691 elif len(text) > position+4 and text[position:position+2] == IAC+SB:
692 end_subnegotiation = text.find(IAC+SE, position)
693 if end_subnegotiation > 0: text = text[:position] + text[end_subnegotiation+2:]
696 # otherwise, strip out a two-byte IAC command
697 elif len(text) > position+2: text = text.replace(text[position:position+2], "")
699 # and this means we got the begining of an IAC
702 # replace the input with our cleaned-up text
703 self.partial_input = text
705 def can_run(self, command):
706 """Check if the user can run this command object."""
708 # has to be in the commands category
709 if command not in universe.categories["command"].values(): result = False
711 # administrators can run any command
712 elif self.account.getboolean("administrator"): result = True
714 # everyone can run non-administrative commands
715 elif not command.getboolean("administrative"): result = True
717 # otherwise the command cannot be run by this user
720 # pass back the result
723 def new_avatar(self):
724 """Instantiate a new, unconfigured avatar for this user."""
726 while "avatar:" + self.account.get("name") + ":" + str(counter) in universe.categories["actor"].keys(): counter += 1
727 self.avatar = Element("actor:avatar:" + self.account.get("name") + ":" + str(counter), universe)
728 self.avatar.append("inherit", "archetype:avatar")
729 self.account.append("avatars", self.avatar.key)
731 def delete_avatar(self, avatar):
732 """Remove an avatar from the world and from the user's list."""
733 if self.avatar is universe.contents[avatar]: self.avatar = None
734 universe.contents[avatar].destroy()
735 avatars = self.account.getlist("avatars")
736 avatars.remove(avatar)
737 self.account.set("avatars", avatars)
739 def activate_avatar_by_index(self, index):
740 """Enter the world with a particular indexed avatar."""
741 self.avatar = universe.contents[self.account.getlist("avatars")[index]]
742 self.avatar.owner = self
743 self.state = "active"
744 self.avatar.go_home()
746 def deactivate_avatar(self):
747 """Have the active avatar leave the world."""
749 current = self.avatar.get("location")
750 self.avatar.set("default_location", current)
751 self.avatar.echo_to_location("You suddenly wonder where " + self.avatar.get("name") + " went.")
752 del universe.contents[current].contents[self.avatar.key]
753 self.avatar.remove_facet("location")
754 self.avatar.owner = None
758 """Destroy the user and associated avatars."""
759 for avatar in self.account.getlist("avatars"): self.delete_avatar(avatar)
760 self.account.destroy()
762 def list_avatar_names(self):
763 """List names of assigned avatars."""
764 return [ universe.contents[avatar].get("name") for avatar in self.account.getlist("avatars") ]
767 """Turn string into list type."""
768 if value[0] + value[-1] == "[]": return eval(value)
769 else: return [ value ]
772 """Turn string into dict type."""
773 if value[0] + value[-1] == "{}": return eval(value)
774 elif value.find(":") > 0: return eval("{" + value + "}")
775 else: return { value: None }
777 def broadcast(message, add_prompt=True):
778 """Send a message to all connected users."""
779 for each_user in universe.userlist: each_user.send("$(eol)" + message, add_prompt=add_prompt)
781 def log(message, level=0):
784 # a couple references we need
785 file_name = universe.categories["internal"]["logging"].get("file")
786 max_log_lines = universe.categories["internal"]["logging"].getint("max_log_lines")
787 syslog_name = universe.categories["internal"]["logging"].get("syslog")
788 timestamp = asctime()[4:19]
790 # turn the message into a list of lines
791 lines = filter(lambda x: x!="", [(x.rstrip()) for x in message.split("\n")])
793 # send the timestamp and line to a file
795 file_descriptor = file(file_name, "a")
796 for line in lines: file_descriptor.write(timestamp + " " + line + "\n")
797 file_descriptor.flush()
798 file_descriptor.close()
800 # send the timestamp and line to standard output
801 if universe.categories["internal"]["logging"].getboolean("stdout"):
802 for line in lines: print(timestamp + " " + line)
804 # send the line to the system log
806 openlog(syslog_name, LOG_PID, LOG_INFO | LOG_DAEMON)
807 for line in lines: syslog(line)
810 # display to connected administrators
811 for user in universe.userlist:
812 if user.state == "active" and user.account.getboolean("administrator") and user.account.getint("loglevel") <= level:
813 # iterate over every line in the message
816 full_message += "$(bld)$(red)" + timestamp + " " + line + "$(nrm)$(eol)"
817 user.send(full_message, flush=True)
819 # add to the recent log list
821 while 0 < len(universe.loglist) >= max_log_lines: del universe.loglist[0]
822 universe.loglist.append(timestamp + " " + line)
824 def wrap_ansi_text(text, width):
825 """Wrap text with arbitrary width while ignoring ANSI colors."""
827 # the current position in the entire text string, including all
828 # characters, printable or otherwise
829 absolute_position = 0
831 # the current text position relative to the begining of the line,
832 # ignoring color escape sequences
833 relative_position = 0
835 # whether the current character is part of a color escape sequence
838 # iterate over each character from the begining of the text
839 for each_character in text:
841 # the current character is the escape character
842 if each_character == chr(27):
845 # the current character is within an escape sequence
848 # the current character is m, which terminates the
849 # current escape sequence
850 if each_character == "m":
853 # the current character is a newline, so reset the relative
854 # position (start a new line)
855 elif each_character == "\n":
856 relative_position = 0
858 # the current character meets the requested maximum line width,
859 # so we need to backtrack and find a space at which to wrap
860 elif relative_position == width:
862 # distance of the current character examined from the
866 # count backwards until we find a space
867 while text[absolute_position - wrap_offset] != " ":
870 # insert an eol in place of the space
871 text = text[:absolute_position - wrap_offset] + "\r\n" + text[absolute_position - wrap_offset + 1:]
873 # increase the absolute position because an eol is two
874 # characters but the space it replaced was only one
875 absolute_position += 1
877 # now we're at the begining of a new line, plus the
878 # number of characters wrapped from the previous line
879 relative_position = wrap_offset
881 # as long as the character is not a carriage return and the
882 # other above conditions haven't been met, count it as a
883 # printable character
884 elif each_character != "\r":
885 relative_position += 1
887 # increase the absolute position for every character
888 absolute_position += 1
890 # return the newly-wrapped text
893 def weighted_choice(data):
894 """Takes a dict weighted by value and returns a random key."""
896 # this will hold our expanded list of keys from the data
899 # create thee expanded list of keys
900 for key in data.keys():
901 for count in range(data[key]):
904 # return one at random
905 return choice(expanded)
908 """Returns a random character name."""
910 # the vowels and consonants needed to create romaji syllables
911 vowels = [ "a", "i", "u", "e", "o" ]
912 consonants = ["'", "k", "z", "s", "sh", "z", "j", "t", "ch", "ts", "d", "n", "h", "f", "m", "y", "r", "w" ]
914 # this dict will hold our weighted list of syllables
917 # generate the list with an even weighting
918 for consonant in consonants:
920 syllables[consonant + vowel] = 1
922 # we'll build the name into this string
925 # create a name of random length from the syllables
926 for syllable in range(randrange(2, 6)):
927 name += weighted_choice(syllables)
929 # strip any leading quotemark, capitalize and return the name
930 return name.strip("'").capitalize()
932 def replace_macros(user, text, is_input=False):
933 """Replaces macros in text output."""
938 # third person pronouns
940 "female": { "obj": "her", "pos": "hers", "sub": "she" },
941 "male": { "obj": "him", "pos": "his", "sub": "he" },
942 "neuter": { "obj": "it", "pos": "its", "sub": "it" }
945 # a dict of replacement macros
948 "$(bld)": chr(27) + "[1m",
949 "$(nrm)": chr(27) + "[0m",
950 "$(blk)": chr(27) + "[30m",
951 "$(blu)": chr(27) + "[34m",
952 "$(cyn)": chr(27) + "[36m",
953 "$(grn)": chr(27) + "[32m",
954 "$(mgt)": chr(27) + "[35m",
955 "$(red)": chr(27) + "[31m",
956 "$(yel)": chr(27) + "[33m",
959 # add dynamic macros where possible
961 account_name = user.account.get("name")
963 macros["$(account)"] = account_name
965 avatar_gender = user.avatar.get("gender")
967 macros["$(tpop)"] = pronouns[avatar_gender]["obj"]
968 macros["$(tppp)"] = pronouns[avatar_gender]["pos"]
969 macros["$(tpsp)"] = pronouns[avatar_gender]["sub"]
971 # find and replace per the macros dict
972 macro_start = text.find("$(")
973 if macro_start == -1: break
974 macro_end = text.find(")", macro_start) + 1
975 macro = text[macro_start:macro_end]
976 if macro in macros.keys():
977 text = text.replace(macro, macros[macro])
979 # if we get here, log and replace it with null
981 text = text.replace(macro, "")
983 log("Unexpected replacement macro " + macro + " encountered.", 6)
985 # replace the look-like-a-macro sequence
986 text = text.replace("$_(", "$(")
990 def escape_macros(text):
991 """Escapes replacement macros in text."""
992 return text.replace("$(", "$_(")
994 def check_time(frequency):
995 """Check for a factor of the current increment count."""
996 if type(frequency) is str:
997 frequency = universe.categories["internal"]["time"].getint(frequency)
998 if not "counters" in universe.categories["internal"]:
999 Element("internal:counters", universe)
1000 return not universe.categories["internal"]["counters"].getint("elapsed") % frequency
1003 """The things which should happen on each pulse, aside from reloads."""
1005 # open the listening socket if it hasn't been already
1006 if not hasattr(universe, "listening_socket"):
1007 universe.initialize_server_socket()
1009 # assign a user if a new connection is waiting
1010 user = check_for_connection(universe.listening_socket)
1011 if user: universe.userlist.append(user)
1013 # iterate over the connected users
1014 for user in universe.userlist: user.pulse()
1016 # update the log every now and then
1017 if check_time("frequency_log"):
1018 log(str(len(universe.userlist)) + " connection(s)")
1020 # periodically save everything
1021 if check_time("frequency_save"):
1024 # pause for a configurable amount of time (decimal seconds)
1025 sleep(universe.categories["internal"]["time"].getfloat("increment"))
1027 # increment the elapsed increment counter
1028 universe.categories["internal"]["counters"].set("elapsed", universe.categories["internal"]["counters"].getint("elapsed") + 1)
1031 """Reload data into new persistent objects."""
1032 for user in universe.userlist[:]: user.reload()
1034 def check_for_connection(listening_socket):
1035 """Check for a waiting connection and return a new user object."""
1037 # try to accept a new connection
1039 connection, address = listening_socket.accept()
1043 # note that we got one
1044 log("Connection from " + address[0], 2)
1046 # disable blocking so we can proceed whether or not we can send/receive
1047 connection.setblocking(0)
1049 # create a new user object
1052 # associate this connection with it
1053 user.connection = connection
1055 # set the user's ipa from the connection's ipa
1056 user.address = address[0]
1058 # let the client know we WILL EOR
1059 user.send(IAC+WILL+EOR, raw=True)
1060 user.negotiation_pause = 2
1062 # return the new user object
1065 def get_menu(state, error=None, echoing=True, terminator="", choices=None):
1066 """Show the correct menu text to a user."""
1068 # make sure we don't reuse a mutable sequence by default
1069 if choices is None: choices = {}
1071 # begin with a telnet echo command sequence if needed
1072 message = get_echo_sequence(state, echoing)
1074 # get the description or error text
1075 message += get_menu_description(state, error)
1077 # get menu choices for the current state
1078 message += get_formatted_menu_choices(state, choices)
1080 # try to get a prompt, if it was defined
1081 message += get_menu_prompt(state)
1083 # throw in the default choice, if it exists
1084 message += get_formatted_default_menu_choice(state)
1086 # display a message indicating if echo is off
1087 message += get_echo_message(state)
1089 # tack on EOR or GA to indicate the prompt will not be followed by CRLF
1090 message += terminator
1092 # return the assembly of various strings defined above
1095 def menu_echo_on(state):
1096 """True if echo is on, false if it is off."""
1097 return universe.categories["menu"][state].getboolean("echo", True)
1099 def get_echo_sequence(state, echoing):
1100 """Build the appropriate IAC WILL/WONT ECHO sequence as needed."""
1102 # if the user has echo on and the menu specifies it should be turned
1103 # off, send: iac + will + echo + null
1104 if echoing and not menu_echo_on(state): return IAC+WILL+ECHO
1106 # if echo is not set to off in the menu and the user curently has echo
1107 # off, send: iac + wont + echo + null
1108 elif not echoing and menu_echo_on(state): return IAC+WONT+ECHO
1110 # default is not to send an echo control sequence at all
1113 def get_echo_message(state):
1114 """Return a message indicating that echo is off."""
1115 if menu_echo_on(state): return ""
1116 else: return "(won't echo) "
1118 def get_default_menu_choice(state):
1119 """Return the default choice for a menu."""
1120 return universe.categories["menu"][state].get("default")
1122 def get_formatted_default_menu_choice(state):
1123 """Default menu choice foratted for inclusion in a prompt string."""
1124 default_choice = get_default_menu_choice(state)
1125 if default_choice: return "[$(red)" + default_choice + "$(nrm)] "
1128 def get_menu_description(state, error):
1129 """Get the description or error text."""
1131 # an error condition was raised by the handler
1134 # try to get an error message matching the condition
1136 description = universe.categories["menu"][state].get("error_" + error)
1137 if not description: description = "That is not a valid choice..."
1138 description = "$(red)" + description + "$(nrm)"
1140 # there was no error condition
1143 # try to get a menu description for the current state
1144 description = universe.categories["menu"][state].get("description")
1146 # return the description or error message
1147 if description: description += "$(eol)$(eol)"
1150 def get_menu_prompt(state):
1151 """Try to get a prompt, if it was defined."""
1152 prompt = universe.categories["menu"][state].get("prompt")
1153 if prompt: prompt += " "
1156 def get_menu_choices(user):
1157 """Return a dict of choice:meaning."""
1158 menu = universe.categories["menu"][user.state]
1159 create_choices = menu.get("create")
1160 if create_choices: choices = eval(create_choices)
1165 for facet in menu.facets():
1166 if facet.startswith("demand_") and not eval(universe.categories["menu"][user.state].get(facet)):
1167 ignores.append(facet.split("_", 2)[1])
1168 elif facet.startswith("create_"):
1169 creates[facet] = facet.split("_", 2)[1]
1170 elif facet.startswith("choice_"):
1171 options[facet] = facet.split("_", 2)[1]
1172 for facet in creates.keys():
1173 if not creates[facet] in ignores:
1174 choices[creates[facet]] = eval(menu.get(facet))
1175 for facet in options.keys():
1176 if not options[facet] in ignores:
1177 choices[options[facet]] = menu.get(facet)
1180 def get_formatted_menu_choices(state, choices):
1181 """Returns a formatted string of menu choices."""
1183 choice_keys = choices.keys()
1185 for choice in choice_keys:
1186 choice_output += " [$(red)" + choice + "$(nrm)] " + choices[choice] + "$(eol)"
1187 if choice_output: choice_output += "$(eol)"
1188 return choice_output
1190 def get_menu_branches(state):
1191 """Return a dict of choice:branch."""
1193 for facet in universe.categories["menu"][state].facets():
1194 if facet.startswith("branch_"):
1195 branches[facet.split("_", 2)[1]] = universe.categories["menu"][state].get(facet)
1198 def get_default_branch(state):
1199 """Return the default branch."""
1200 return universe.categories["menu"][state].get("branch")
1202 def get_choice_branch(user, choice):
1203 """Returns the new state matching the given choice."""
1204 branches = get_menu_branches(user.state)
1205 if choice in branches.keys(): return branches[choice]
1206 elif choice in user.menu_choices.keys(): return get_default_branch(user.state)
1209 def get_menu_actions(state):
1210 """Return a dict of choice:branch."""
1212 for facet in universe.categories["menu"][state].facets():
1213 if facet.startswith("action_"):
1214 actions[facet.split("_", 2)[1]] = universe.categories["menu"][state].get(facet)
1217 def get_default_action(state):
1218 """Return the default action."""
1219 return universe.categories["menu"][state].get("action")
1221 def get_choice_action(user, choice):
1222 """Run any indicated script for the given choice."""
1223 actions = get_menu_actions(user.state)
1224 if choice in actions.keys(): return actions[choice]
1225 elif choice in user.menu_choices.keys(): return get_default_action(user.state)
1228 def handle_user_input(user):
1229 """The main handler, branches to a state-specific handler."""
1231 # check to make sure the state is expected, then call that handler
1232 if "handler_" + user.state in globals():
1233 exec("handler_" + user.state + "(user)")
1235 generic_menu_handler(user)
1237 # since we got input, flag that the menu/prompt needs to be redisplayed
1238 user.menu_seen = False
1240 # if the user's client echo is off, send a blank line for aesthetics
1241 if user.echoing: user.received_newline = True
1243 def generic_menu_handler(user):
1244 """A generic menu choice handler."""
1246 # get a lower-case representation of the next line of input
1247 if user.input_queue:
1248 choice = user.input_queue.pop(0)
1249 if choice: choice = choice.lower()
1251 if not choice: choice = get_default_menu_choice(user.state)
1252 if choice in user.menu_choices:
1253 exec(get_choice_action(user, choice))
1254 new_state = get_choice_branch(user, choice)
1255 if new_state: user.state = new_state
1256 else: user.error = "default"
1258 def handler_entering_account_name(user):
1259 """Handle the login account name."""
1261 # get the next waiting line of input
1262 input_data = user.input_queue.pop(0)
1264 # did the user enter anything?
1267 # keep only the first word and convert to lower-case
1268 name = input_data.lower()
1270 # fail if there are non-alphanumeric characters
1271 if name != filter(lambda x: x>="0" and x<="9" or x>="a" and x<="z", name):
1272 user.error = "bad_name"
1274 # if that account exists, time to request a password
1275 elif name in universe.categories["account"]:
1276 user.account = universe.categories["account"][name]
1277 user.state = "checking_password"
1279 # otherwise, this could be a brand new user
1281 user.account = Element("account:" + name, universe)
1282 user.account.set("name", name)
1283 log("New user: " + name, 2)
1284 user.state = "checking_new_account_name"
1286 # if the user entered nothing for a name, then buhbye
1288 user.state = "disconnecting"
1290 def handler_checking_password(user):
1291 """Handle the login account password."""
1293 # get the next waiting line of input
1294 input_data = user.input_queue.pop(0)
1296 # does the hashed input equal the stored hash?
1297 if new_md5(user.account.get("name") + input_data).hexdigest() == user.account.get("passhash"):
1299 # if so, set the username and load from cold storage
1300 if not user.replace_old_connections():
1302 user.state = "main_utility"
1304 # if at first your hashes don't match, try, try again
1305 elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
1306 user.password_tries += 1
1307 user.error = "incorrect"
1309 # we've exceeded the maximum number of password failures, so disconnect
1311 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
1312 user.state = "disconnecting"
1314 def handler_entering_new_password(user):
1315 """Handle a new password entry."""
1317 # get the next waiting line of input
1318 input_data = user.input_queue.pop(0)
1320 # make sure the password is strong--at least one upper, one lower and
1321 # one digit, seven or more characters in length
1322 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)):
1324 # hash and store it, then move on to verification
1325 user.account.set("passhash", new_md5(user.account.get("name") + input_data).hexdigest())
1326 user.state = "verifying_new_password"
1328 # the password was weak, try again if you haven't tried too many times
1329 elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
1330 user.password_tries += 1
1333 # too many tries, so adios
1335 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
1336 user.account.destroy()
1337 user.state = "disconnecting"
1339 def handler_verifying_new_password(user):
1340 """Handle the re-entered new password for verification."""
1342 # get the next waiting line of input
1343 input_data = user.input_queue.pop(0)
1345 # hash the input and match it to storage
1346 if new_md5(user.account.get("name") + input_data).hexdigest() == user.account.get("passhash"):
1349 # the hashes matched, so go active
1350 if not user.replace_old_connections(): user.state = "main_utility"
1352 # go back to entering the new password as long as you haven't tried
1354 elif user.password_tries < universe.categories["internal"]["limits"].getint("password_tries") - 1:
1355 user.password_tries += 1
1356 user.error = "differs"
1357 user.state = "entering_new_password"
1359 # otherwise, sayonara
1361 user.send("$(eol)$(red)Too many failed password attempts...$(nrm)$(eol)")
1362 user.account.destroy()
1363 user.state = "disconnecting"
1365 def handler_active(user):
1366 """Handle input for active users."""
1368 # get the next waiting line of input
1369 input_data = user.input_queue.pop(0)
1374 # split out the command (first word) and parameters (everything else)
1375 if input_data.find(" ") > 0:
1376 command_name, parameters = input_data.split(" ", 1)
1378 command_name = input_data
1381 # lowercase the command
1382 command_name = command_name.lower()
1384 # the command matches a command word for which we have data
1385 if command_name in universe.categories["command"]:
1386 command = universe.categories["command"][command_name]
1387 else: command = None
1389 # if it's allowed, do it
1390 if user.can_run(command): exec(command.get("action"))
1392 # otherwise, give an error
1393 elif command_name: command_error(user, input_data)
1395 # if no input, just idle back with a prompt
1396 else: user.send("", just_prompt=True)
1398 def command_halt(user, parameters):
1399 """Halt the world."""
1401 # see if there's a message or use a generic one
1402 if parameters: message = "Halting: " + parameters
1403 else: message = "User " + user.account.get("name") + " halted the world."
1406 broadcast(message, add_prompt=False)
1409 # set a flag to terminate the world
1410 universe.terminate_world = True
1412 def command_reload(user):
1413 """Reload all code modules, configs and data."""
1415 # let the user know and log
1416 user.send("Reloading all code modules, configs and data.")
1417 log("User " + user.account.get("name") + " reloaded the world.", 8)
1419 # set a flag to reload
1420 universe.reload_modules = True
1422 def command_quit(user):
1423 """Leave the world and go back to the main menu."""
1424 user.deactivate_avatar()
1425 user.state = "main_utility"
1427 def command_help(user, parameters):
1428 """List available commands and provide help for commands."""
1430 # did the user ask for help on a specific command word?
1433 # is the command word one for which we have data?
1434 if parameters in universe.categories["command"]:
1435 command = universe.categories["command"][parameters]
1436 else: command = None
1438 # only for allowed commands
1439 if user.can_run(command):
1441 # add a description if provided
1442 description = command.get("description")
1444 description = "(no short description provided)"
1445 if command.getboolean("administrative"): output = "$(red)"
1446 else: output = "$(grn)"
1447 output += parameters + "$(nrm) - " + description + "$(eol)$(eol)"
1449 # add the help text if provided
1450 help_text = command.get("help")
1452 help_text = "No help is provided for this command."
1455 # no data for the requested command word
1457 output = "That is not an available command."
1459 # no specific command word was indicated
1462 # give a sorted list of commands with descriptions if provided
1463 output = "These are the commands available to you:$(eol)$(eol)"
1464 sorted_commands = universe.categories["command"].keys()
1465 sorted_commands.sort()
1466 for item in sorted_commands:
1467 command = universe.categories["command"][item]
1468 if user.can_run(command):
1469 description = command.get("description")
1471 description = "(no short description provided)"
1472 if command.getboolean("administrative"): output += " $(red)"
1473 else: output += " $(grn)"
1474 output += item + "$(nrm) - " + description + "$(eol)"
1475 output += "$(eol)Enter \"help COMMAND\" for help on a command named \"COMMAND\"."
1477 # send the accumulated output to the user
1480 def command_move(user, parameters):
1481 """Move the avatar in a given direction."""
1482 if parameters in universe.contents[user.avatar.get("location")].portals():
1483 user.avatar.move_direction(parameters)
1484 else: user.send("You cannot go that way.")
1486 def command_look(user, parameters):
1488 if parameters: user.send("You can't look at or in anything yet.")
1489 else: user.avatar.look_at(user.avatar.get("location"))
1491 def command_say(user, parameters):
1492 """Speak to others in the same room."""
1494 # check for replacement macros
1495 if replace_macros(user, parameters, True) != parameters:
1496 user.send("You cannot speak $_(replacement macros).")
1498 # the user entered a message
1501 # get rid of quote marks on the ends of the message and
1502 # capitalize the first letter
1503 message = parameters.strip("\"'`").capitalize()
1505 # a dictionary of punctuation:action pairs
1507 for facet in universe.categories["internal"]["language"].facets():
1508 if facet.startswith("punctuation_"):
1509 action = facet.split("_")[1]
1510 for mark in universe.categories["internal"]["language"].getlist(facet):
1511 actions[mark] = action
1513 # match the punctuation used, if any, to an action
1514 default_punctuation = universe.categories["internal"]["language"].get("default_punctuation")
1515 action = actions[default_punctuation]
1516 for mark in actions.keys():
1517 if message.endswith(mark) and mark != default_punctuation:
1518 action = actions[mark]
1521 # if the action is default and there is no mark, add one
1522 if action == actions[default_punctuation] and not message.endswith(default_punctuation):
1523 message += default_punctuation
1525 # capitalize a list of words within the message
1526 capitalize_words = universe.categories["internal"]["language"].getlist("capitalize_words")
1527 for word in capitalize_words:
1528 message = message.replace(" " + word + " ", " " + word.capitalize() + " ")
1531 user.avatar.echo_to_location(user.avatar.get("name") + " " + action + "s, \"" + message + "\"")
1532 user.send("You " + action + ", \"" + message + "\"")
1534 # there was no message
1536 user.send("What do you want to say?")
1538 def command_show(user, parameters):
1539 """Show program data."""
1541 if parameters.find(" ") < 1:
1542 if parameters == "time":
1543 message = universe.categories["internal"]["counters"].get("elapsed") + " increments elapsed since the world was created."
1544 elif parameters == "categories":
1545 message = "These are the element categories:$(eol)"
1546 categories = universe.categories.keys()
1548 for category in categories: message += "$(eol) $(grn)" + category + "$(nrm)"
1549 elif parameters == "files":
1550 message = "These are the current files containing the universe:$(eol)"
1551 filenames = universe.files.keys()
1553 for filename in filenames: message += "$(eol) $(grn)" + filename + "$(nrm)"
1556 arguments = parameters.split()
1557 if arguments[0] == "category":
1558 if arguments[1] in universe.categories:
1559 message = "These are the elements in the \"" + arguments[1] + "\" category:$(eol)"
1560 elements = universe.categories[arguments[1]].keys()
1562 for element in elements:
1563 message += "$(eol) $(grn)" + universe.categories[arguments[1]][element].key + "$(nrm)"
1564 elif arguments[0] == "element":
1565 if arguments[1] in universe.contents:
1566 message = "These are the properties of the \"" + arguments[1] + "\" element:$(eol)"
1567 element = universe.contents[arguments[1]]
1568 facets = element.facets()
1570 for facet in facets:
1571 message += "$(eol) $(grn)" + facet + ": $(red)" + escape_macros(element.get(facet)) + "$(nrm)"
1572 elif arguments[0] == "result":
1573 if len(arguments) > 1:
1575 message = repr(eval(" ".join(arguments[1:])))
1577 message = "Your expression raised an exception!"
1578 elif arguments[0] == "log":
1579 if match("^\d+$", arguments[1]) and int(arguments[1]) > 0:
1580 linecount = int(arguments[1])
1581 if linecount > len(universe.loglist): linecount = len(universe.loglist)
1582 message = "There are " + str(len(universe.loglist)) + " log lines in memory."
1583 message += " The most recent " + str(linecount) + " lines are:$(eol)$(eol)"
1584 for line in universe.loglist[-linecount:]:
1585 message += " " + line + "$(eol)"
1586 else: message = "\"" + arguments[1] + "\" is not a positive integer greater than 0."
1588 if parameters: message = "I don't know what \"" + parameters + "\" is."
1589 else: message = "What do you want to show?"
1592 def command_create(user, parameters):
1593 """Create an element if it does not exist."""
1594 if not parameters: message = "You must at least specify an element to create."
1596 arguments = parameters.split()
1597 if len(arguments) == 1: arguments.append("")
1598 if len(arguments) == 2:
1599 element, filename = arguments
1600 if element in universe.contents: message = "The \"" + element + "\" element already exists."
1602 message = "You create \"" + element + "\" within the universe."
1603 logline = user.account.get("name") + " created an element: " + element
1605 logline += " in file " + filename
1606 if filename not in universe.files:
1607 message += " Warning: \"" + filename + "\" is not yet included in any other file and will not be read on startup unless this is remedied."
1608 Element(element, universe, filename)
1610 elif len(arguments) > 2: message = "You can only specify an element and a filename."
1613 def command_destroy(user, parameters):
1614 """Destroy an element if it exists."""
1615 if not parameters: message = "You must specify an element to destroy."
1617 if parameters not in universe.contents: message = "The \"" + parameters + "\" element does not exist."
1619 universe.contents[parameters].destroy()
1620 message = "You destroy \"" + parameters + "\" within the universe."
1621 log(user.account.get("name") + " destroyed an element: " + parameters, 6)
1624 def command_set(user, parameters):
1625 """Set a facet of an element."""
1626 if not parameters: message = "You must specify an element, a facet and a value."
1628 arguments = parameters.split(" ", 2)
1629 if len(arguments) == 1: message = "What facet of element \"" + arguments[0] + "\" would you like to set?"
1630 elif len(arguments) == 2: message = "What value would you like to set for the \"" + arguments[1] + "\" facet of the \"" + arguments[0] + "\" element?"
1632 element, facet, value = arguments
1633 if element not in universe.contents: message = "The \"" + element + "\" element does not exist."
1635 universe.contents[element].set(facet, value)
1636 message = "You have successfully (re)set the \"" + facet + "\" facet of element \"" + element + "\". Try \"show element " + element + "\" for verification."
1639 def command_delete(user, parameters):
1640 """Delete a facet from an element."""
1641 if not parameters: message = "You must specify an element and a facet."
1643 arguments = parameters.split(" ")
1644 if len(arguments) == 1: message = "What facet of element \"" + arguments[0] + "\" would you like to delete?"
1645 elif len(arguments) != 2: message = "You may only specify an element and a facet."
1647 element, facet = arguments
1648 if element not in universe.contents: message = "The \"" + element + "\" element does not exist."
1649 elif facet not in universe.contents[element].facets(): message = "The \"" + element + "\" element has no \"" + facet + "\" facet."
1651 universe.contents[element].remove_facet(facet)
1652 message = "You have successfully deleted the \"" + facet + "\" facet of element \"" + element + "\". Try \"show element " + element + "\" for verification."
1655 def command_error(user, input_data):
1656 """Generic error for an unrecognized command word."""
1658 # 90% of the time use a generic error
1660 message = "I'm not sure what \"" + input_data + "\" means..."
1662 # 10% of the time use the classic diku error
1664 message = "Arglebargle, glop-glyf!?!"
1666 # send the error message
1669 # if there is no universe, create an empty one
1670 if not "universe" in locals(): universe = Universe()