def session_from_sessid(self, sessid): """ Return session based on sessid, or None if not found """ if is_iter(sessid): return [self.sessions.get(sid) for sid in sessid if sid in self.sessions] return self.sessions.get(sessid)
def _init_command(mcs, **kwargs): """ Helper command. Makes sure all data are stored as lowercase and do checking on all properties that should be in list form. Sets up locks to be more forgiving. This is used both by the metaclass and (optionally) at instantiation time. If kwargs are given, these are set as instance-specific properties on the command. """ for i in range(len(kwargs)): # used for dynamic creation of commands key, value = kwargs.popitem() setattr(mcs, key, value) mcs.key = mcs.key.lower() if mcs.aliases and not is_iter(mcs.aliases): try: mcs.aliases = [ str(alias).strip().lower() for alias in mcs.aliases.split(',') ] except Exception: mcs.aliases = [] mcs.aliases = list( set(alias for alias in mcs.aliases if alias and alias != mcs.key)) # optimization - a set is much faster to match against than a list mcs._matchset = set([mcs.key] + mcs.aliases) # optimization for looping over keys+aliases mcs._keyaliases = tuple(mcs._matchset) # by default we don't save the command between runs if not hasattr(mcs, "save_for_next"): mcs.save_for_next = False # pre-process locks as defined in class definition temp = [] if hasattr(mcs, 'permissions'): mcs.locks = mcs.permissions if not hasattr(mcs, 'locks'): # default if one forgets to define completely mcs.locks = "cmd:all()" if not "cmd:" in mcs.locks: mcs.locks = "cmd:all();" + mcs.locks for lockstring in mcs.locks.split(';'): if lockstring and not ':' in lockstring: lockstring = "cmd:%s" % lockstring temp.append(lockstring) mcs.lock_storage = ";".join(temp) if hasattr(mcs, 'arg_regex') and isinstance(mcs.arg_regex, basestring): mcs.arg_regex = re.compile(r"%s" % mcs.arg_regex, re.I) if not hasattr(mcs, "auto_help"): mcs.auto_help = True if not hasattr(mcs, 'is_exit'): mcs.is_exit = False if not hasattr(mcs, "help_category"): mcs.help_category = "general" mcs.help_category = mcs.help_category.lower()
def add(self, cmd): """ Add a command, a list of commands or a cmdset to this cmdset. Note that if cmd already exists in set, it will replace the old one (no priority checking etc at this point; this is often used to overload default commands). If cmd is another cmdset class or -instance, the commands of that command set is added to this one, as if they were part of the original cmdset definition. No merging or priority checks are made, rather later added commands will simply replace existing ones to make a unique set. """ if inherits_from(cmd, "src.commands.cmdset.CmdSet"): # cmd is a command set so merge all commands in that set # to this one. We raise a visible error if we created # an infinite loop (adding cmdset to itself somehow) try: cmd = self._instantiate(cmd) except RuntimeError: string = "Adding cmdset %(cmd)s to %(class)s lead to an " string += "infinite loop. When adding a cmdset to another, " string += "make sure they are not themself cyclically added to " string += "the new cmdset somewhere in the chain." raise RuntimeError( _(string) % { "cmd": cmd, "class": self.__class__ }) cmds = cmd.commands elif is_iter(cmd): cmds = [self._instantiate(c) for c in cmd] else: cmds = [self._instantiate(cmd)] commands = self.commands system_commands = self.system_commands for cmd in cmds: # add all commands if not hasattr(cmd, 'obj'): cmd.obj = self.cmdsetobj try: ic = commands.index(cmd) commands[ic] = cmd # replace except ValueError: commands.append(cmd) # extra run to make sure to avoid doublets self.commands = list(set(commands)) #print "In cmdset.add(cmd):", self.key, cmd # add system_command to separate list as well, # for quick look-up if cmd.key.startswith("__"): try: ic = system_commands.index(cmd) system_commands[ic] = cmd # replace except ValueError: system_commands.append(cmd)
def _init_command(mcs, **kwargs): """ Helper command. Makes sure all data are stored as lowercase and do checking on all properties that should be in list form. Sets up locks to be more forgiving. This is used both by the metaclass and (optionally) at instantiation time. If kwargs are given, these are set as instance-specific properties on the command. """ for i in range(len(kwargs)): # used for dynamic creation of commands key, value = kwargs.popitem() setattr(mcs, key, value) mcs.key = mcs.key.lower() if mcs.aliases and not is_iter(mcs.aliases): try: mcs.aliases = [str(alias).strip().lower() for alias in mcs.aliases.split(',')] except Exception: mcs.aliases = [] mcs.aliases = list(set(alias for alias in mcs.aliases if alias and alias != mcs.key)) # optimization - a set is much faster to match against than a list mcs._matchset = set([mcs.key] + mcs.aliases) # optimization for looping over keys+aliases mcs._keyaliases = tuple(mcs._matchset) # by default we don't save the command between runs if not hasattr(mcs, "save_for_next"): mcs.save_for_next = False # pre-process locks as defined in class definition temp = [] if hasattr(mcs, 'permissions'): mcs.locks = mcs.permissions if not hasattr(mcs, 'locks'): # default if one forgets to define completely mcs.locks = "cmd:all()" if not "cmd:" in mcs.locks: mcs.locks = "cmd:all();" + mcs.locks for lockstring in mcs.locks.split(';'): if lockstring and not ':' in lockstring: lockstring = "cmd:%s" % lockstring temp.append(lockstring) mcs.lock_storage = ";".join(temp) if hasattr(mcs, 'arg_regex') and isinstance(mcs.arg_regex, basestring): mcs.arg_regex = re.compile(r"%s" % mcs.arg_regex, re.I) if not hasattr(mcs, "auto_help"): mcs.auto_help = True if not hasattr(mcs, 'is_exit'): mcs.is_exit = False if not hasattr(mcs, "help_category"): mcs.help_category = "general" mcs.help_category = mcs.help_category.lower()
def sessions_from_character(self, character): """ Given a game character, return any matching sessions. """ sessid = character.sessid.get() if is_iter(sessid): return [self.sessions.get(sess) for sess in sessid if sessid in self.sessions] return self.sessions.get(sessid)
def add(self, cmd): """ Add a command, a list of commands or a cmdset to this cmdset. Note that if cmd already exists in set, it will replace the old one (no priority checking etc at this point; this is often used to overload default commands). If cmd is another cmdset class or -instance, the commands of that command set is added to this one, as if they were part of the original cmdset definition. No merging or priority checks are made, rather later added commands will simply replace existing ones to make a unique set. """ if inherits_from(cmd, "src.commands.cmdset.CmdSet"): # cmd is a command set so merge all commands in that set # to this one. We raise a visible error if we created # an infinite loop (adding cmdset to itself somehow) try: cmd = self._instantiate(cmd) except RuntimeError: string = "Adding cmdset %(cmd)s to %(class)s lead to an " string += "infinite loop. When adding a cmdset to another, " string += "make sure they are not themself cyclically added to " string += "the new cmdset somewhere in the chain." raise RuntimeError(_(string) % {"cmd": cmd, "class": self.__class__}) cmds = cmd.commands elif is_iter(cmd): cmds = [self._instantiate(c) for c in cmd] else: cmds = [self._instantiate(cmd)] commands = self.commands system_commands = self.system_commands for cmd in cmds: # add all commands if not hasattr(cmd, 'obj'): cmd.obj = self.cmdsetobj try: ic = commands.index(cmd) commands[ic] = cmd # replace except ValueError: commands.append(cmd) # extra run to make sure to avoid doublets self.commands = list(set(commands)) #print "In cmdset.add(cmd):", self.key, cmd # add system_command to separate list as well, # for quick look-up if cmd.key.startswith("__"): try: ic = system_commands.index(cmd) system_commands[ic] = cmd # replace except ValueError: system_commands.append(cmd)
def session_from_player(self, player, sessid): """ Given a player and a session id, return the actual session object """ if is_iter(sessid): sessions = [self.sessions.get(sid) for sid in sessid] s = [sess for sess in sessions if sess and sess.logged_in and player.uid == sess.uid] return s session = self.sessions.get(sessid) return session and session.logged_in and player.uid == session.uid and session or None
def session_from_sessid(self, sessid): """ Return session based on sessid, or None if not found """ if is_iter(sessid): return [ self.sessions.get(sid) for sid in sessid if sid in self.sessions ] return self.sessions.get(sessid)
def sessions_from_character(self, character): """ Given a game character, return any matching sessions. """ sessid = character.sessid.get() if is_iter(sessid): return [ self.sessions.get(sess) for sess in sessid if sessid in self.sessions ] return self.sessions.get(sessid)
def get_objs_with_key_or_alias(self, ostring, exact=True, candidates=None, typeclasses=None): """ Returns objects based on key or alias match. Will also do fuzzy matching based on the utils.string_partial_matching function. candidates - list of candidate objects to restrict on typeclasses - list of typeclass path strings to restrict on """ if not isinstance(ostring, basestring): if hasattr(ostring, "key"): ostring = ostring.key else: return [] if is_iter(candidates) and not len(candidates): # if candidates is an empty iterable there can be no matches # Exit early. return [] # build query objects candidates_id = [_GA(obj, "id") for obj in make_iter(candidates) if obj] cand_restriction = candidates != None and Q(pk__in=make_iter(candidates_id)) or Q() type_restriction = typeclasses and Q(db_typeclass_path__in=make_iter(typeclasses)) or Q() if exact: # exact match - do direct search return self.filter( cand_restriction & type_restriction & ( Q(db_key__iexact=ostring) | Q(db_tags__db_key__iexact=ostring) & Q(db_tags__db_category__iexact="objectalias") ) ).distinct() elif candidates: # fuzzy with candidates key_candidates = self.filter(cand_restriction & type_restriction) else: # fuzzy without supplied candidates - we select our own candidates key_candidates = self.filter( type_restriction & (Q(db_key__istartswith=ostring) | Q(db_tags__db_key__istartswith=ostring)) ).distinct() candidates_id = [_GA(obj, "id") for obj in key_candidates] # fuzzy matching key_strings = key_candidates.values_list("db_key", flat=True) index_matches = string_partial_matching(key_strings, ostring, ret_index=True) if index_matches: return [obj for ind, obj in enumerate(key_candidates) if ind in index_matches] else: alias_candidates = self.filter(id__in=candidates_id, db_tags__db_category__iexact="objectalias") # print alias_candidates alias_strings = alias_candidates.values_list("db_key", flat=True) index_matches = string_partial_matching(alias_strings, ostring, ret_index=True) if index_matches: return [alias.db_obj for ind, alias in enumerate(alias_candidates) if ind in index_matches] return []
def session_from_player(self, player, sessid): """ Given a player and a session id, return the actual session object """ if is_iter(sessid): sessions = [self.sessions.get(sid) for sid in sessid] s = [ sess for sess in sessions if sess and sess.logged_in and player.uid == sess.uid ] return s session = self.sessions.get(sessid) return session and session.logged_in and player.uid == session.uid and session or None
def __init__(self, caller, nodes=None, startnode="START", endnode="END"): """ We specify startnode/endnode so that the system knows where to enter and where to exit the menu tree. If nodes is given, it shuld be a list of valid node objects to add to the tree. """ self.tree = {} self.startnode = startnode self.endnode = endnode self.caller = caller if nodes and utils.is_iter(nodes): for node in nodes: self.add(node)
def __init__(mcs, *args, **kwargs): """ Simply make sure all data are stored as lowercase and do checking on all properties that should be in list form. Sets up locks to be more forgiving. """ mcs.key = mcs.key.lower() if mcs.aliases and not is_iter(mcs.aliases): try: mcs.aliases = [str(alias).strip().lower() for alias in mcs.aliases.split(',')] except Exception: mcs.aliases = [] mcs.aliases = list(set(alias for alias in mcs.aliases if alias != mcs.key)) # optimization - a set is much faster to match against than a list mcs._matchset = set([mcs.key] + mcs.aliases) # optimization for looping over keys+aliases mcs._keyaliases = tuple(mcs._matchset) # by default we don't save the command between runs if not hasattr(mcs, "save_for_next"): mcs.save_for_next = False # pre-process locks as defined in class definition temp = [] if hasattr(mcs, 'permissions'): mcs.locks = mcs.permissions if not hasattr(mcs, 'locks'): # default if one forgets to define completely mcs.locks = "cmd:all()" for lockstring in mcs.locks.split(';'): if lockstring and not ':' in lockstring: lockstring = "cmd:%s" % lockstring temp.append(lockstring) mcs.lock_storage = ";".join(temp) if hasattr(mcs, 'arg_regex') and isinstance(mcs.arg_regex, basestring): mcs.arg_regex = re.compile(r"%s" % mcs.arg_regex, re.I) else: mcs.arg_regex = None if not hasattr(mcs, "auto_help"): mcs.auto_help = True if not hasattr(mcs, 'is_exit'): mcs.is_exit = False if not hasattr(mcs, "help_category"): mcs.help_category = "general" mcs.help_category = mcs.help_category.lower() super(CommandMeta, mcs).__init__(*args, **kwargs)
def create_channel(key, aliases=None, desc=None, locks=None, keep_log=True, typeclass=None): """ Create A communication Channel. A Channel serves as a central hub for distributing Msgs to groups of people without specifying the receivers explicitly. Instead players may 'connect' to the channel and follow the flow of messages. By default the channel allows access to all old messages, but this can be turned off with the keep_log switch. key - this must be unique. aliases - list of alternative (likely shorter) keynames. locks - lock string definitions """ global _ChannelDB, _channelhandler if not _ChannelDB: from src.comms.models import ChannelDB as _ChannelDB if not _channelhandler: from src.comms import channelhandler as _channelhandler if not typeclass: typeclass = settings.BASE_CHANNEL_TYPECLASS try: new_channel = _ChannelDB(typeclass=typeclass, db_key=key) new_channel.save() new_channel = new_channel.typeclass if aliases: if not utils.is_iter(aliases): aliases = [aliases] new_channel.aliases.add(aliases) new_channel.save() new_channel.db.desc = desc new_channel.db.keep_log = keep_log except IntegrityError: string = "Could not add channel: key '%s' already exists." % key logger.log_errmsg(string) return None if locks: new_channel.locks.add(locks) new_channel.save() _channelhandler.CHANNELHANDLER.add_channel(new_channel) new_channel.at_channel_create() return new_channel
def _format_help(self, channel): "builds a doc string" key = channel.key aliases = channel.aliases if not utils.is_iter(aliases): aliases = [aliases] ustring = "%s <message>" % key.lower() + "".join(["\n %s <message>" % alias.lower() for alias in aliases]) desc = channel.desc string = \ """ Channel '%s' Usage (not including your personal aliases): %s %s """ % (key, ustring, desc) return string
def do_mssp(self, option): """ Negotiate all the information. """ self.mssp_table = { # Required fields "NAME": "Evennia", "PLAYERS": self.get_player_count, "UPTIME" : self.get_uptime, # Generic "CRAWL DELAY": "-1", "HOSTNAME": "", # current or new hostname "PORT": ["4000"], # most important port should be last in list "CODEBASE": "Evennia", "CONTACT": "", # email for contacting the mud "CREATED": "", # year MUD was created "ICON": "", # url to icon 32x32 or larger; <32kb. "IP": "", # current or new IP address "LANGUAGE": "", # name of language used, e.g. English "LOCATION": "", # full English name of server country "MINIMUM AGE": "0", # set to 0 if not applicable "WEBSITE": "www.evennia.com", # Categorisation "FAMILY": "Custom", # evennia goes under 'Custom' "GENRE": "None", # Adult, Fantasy, Historical, Horror, Modern, None, or Science Fiction "GAMEPLAY": "None", # Adventure, Educational, Hack and Slash, None, # Player versus Player, Player versus Environment, # Roleplaying, Simulation, Social or Strategy "STATUS": "Open Beta", # Alpha, Closed Beta, Open Beta, Live "GAMESYSTEM": "Custom", # D&D, d20 System, World of Darkness, etc. Use Custom if homebrew "INTERMUD": "IMC2", # evennia supports IMC2. "SUBGENRE": "None", # LASG, Medieval Fantasy, World War II, Frankenstein, # Cyberpunk, Dragonlance, etc. Or None if not available. # World "AREAS": "0", "HELPFILES": "0", "MOBILES": "0", "OBJECTS": "0", "ROOMS": "0", # use 0 if room-less "CLASSES": "0", # use 0 if class-less "LEVELS": "0", # use 0 if level-less "RACES": "0", # use 0 if race-less "SKILLS": "0", # use 0 if skill-less # Protocols set to 1 or 0) "ANSI": "1", "GMCP": "0", "MCCP": "0", "MCP": "0", "MSDP": "0", "MSP": "0", "MXP": "0", "PUEBLO": "0", "UTF-8": "1", "VT100": "0", "XTERM 256 COLORS": "0", # Commercial set to 1 or 0) "PAY TO PLAY": "0", "PAY FOR PERKS": "0", # Hiring set to 1 or 0) "HIRING BUILDERS": "0", "HIRING CODERS": "0", # Extended variables # World "DBSIZE": "0", "EXITS": "0", "EXTRA DESCRIPTIONS": "0", "MUDPROGS": "0", "MUDTRIGS": "0", "RESETS": "0", # Game (set to 1, 0 or one of the given alternatives) "ADULT MATERIAL": "0", "MULTICLASSING": "0", "NEWBIE FRIENDLY": "0", "PLAYER CITIES": "0", "PLAYER CLANS": "0", "PLAYER CRAFTING": "0", "PLAYER GUILDS": "0", "EQUIPMENT SYSTEM": "None", # "None", "Level", "Skill", "Both" "MULTIPLAYING": "None", # "None", "Restricted", "Full" "PLAYERKILLING": "None", # "None", "Restricted", "Full" "QUEST SYSTEM": "None", # "None", "Immortal Run", "Automated", "Integrated" "ROLEPLAYING": "None", # "None", "Accepted", "Encouraged", "Enforced" "TRAINING SYSTEM": "None", # "None", "Level", "Skill", "Both" "WORLD ORIGINALITY": "None", # "All Stock", "Mostly Stock", "Mostly Original", "All Original" # Protocols (only change if you added/removed something manually) "ATCP": "0", "MSDP": "0", "MCCP": "1", "SSL": "1", "UTF-8": "1", "ZMP": "0", "XTERM 256 COLORS": "0"} # update the static table with the custom one if MSSPTable_CUSTOM: self.mssp_table.update(MSSPTable_CUSTOM) varlist = '' for variable, value in self.mssp_table.items(): if callable(value): value = value() if utils.is_iter(value): for partval in value: varlist += MSSP_VAR + str(variable) + MSSP_VAL + str(partval) else: varlist += MSSP_VAR + str(variable) + MSSP_VAL + str(value) # send to crawler by subnegotiation self.protocol.requestNegotiation(MSSP, varlist) self.protocol.handshake_done()
def do_mssp(self, option): """ Negotiate all the information. """ self.mssp_table = { # Required fields "NAME": "Evennia", "PLAYERS": self.get_player_count, "UPTIME": self.get_uptime, # Generic "CRAWL DELAY": "-1", "HOSTNAME": "", # current or new hostname "PORT": ["4000"], # most important port should be last in list "CODEBASE": "Evennia", "CONTACT": "", # email for contacting the mud "CREATED": "", # year MUD was created "ICON": "", # url to icon 32x32 or larger; <32kb. "IP": "", # current or new IP address "LANGUAGE": "", # name of language used, e.g. English "LOCATION": "", # full English name of server country "MINIMUM AGE": "0", # set to 0 if not applicable "WEBSITE": "www.evennia.com", # Categorisation "FAMILY": "Custom", # evennia goes under 'Custom' "GENRE": "None", # Adult, Fantasy, Historical, Horror, Modern, None, or Science Fiction "GAMEPLAY": "None", # Adventure, Educational, Hack and Slash, None, # Player versus Player, Player versus Environment, # Roleplaying, Simulation, Social or Strategy "STATUS": "Open Beta", # Alpha, Closed Beta, Open Beta, Live "GAMESYSTEM": "Custom", # D&D, d20 System, World of Darkness, etc. Use Custom if homebrew "INTERMUD": "IMC2", # evennia supports IMC2. "SUBGENRE": "None", # LASG, Medieval Fantasy, World War II, Frankenstein, # Cyberpunk, Dragonlance, etc. Or None if not available. # World "AREAS": "0", "HELPFILES": "0", "MOBILES": "0", "OBJECTS": "0", "ROOMS": "0", # use 0 if room-less "CLASSES": "0", # use 0 if class-less "LEVELS": "0", # use 0 if level-less "RACES": "0", # use 0 if race-less "SKILLS": "0", # use 0 if skill-less # Protocols set to 1 or 0) "ANSI": "1", "GMCP": "0", "MCCP": "0", "MCP": "0", "MSDP": "0", "MSP": "0", "MXP": "0", "PUEBLO": "0", "UTF-8": "1", "VT100": "0", "XTERM 256 COLORS": "0", # Commercial set to 1 or 0) "PAY TO PLAY": "0", "PAY FOR PERKS": "0", # Hiring set to 1 or 0) "HIRING BUILDERS": "0", "HIRING CODERS": "0", # Extended variables # World "DBSIZE": "0", "EXITS": "0", "EXTRA DESCRIPTIONS": "0", "MUDPROGS": "0", "MUDTRIGS": "0", "RESETS": "0", # Game (set to 1, 0 or one of the given alternatives) "ADULT MATERIAL": "0", "MULTICLASSING": "0", "NEWBIE FRIENDLY": "0", "PLAYER CITIES": "0", "PLAYER CLANS": "0", "PLAYER CRAFTING": "0", "PLAYER GUILDS": "0", "EQUIPMENT SYSTEM": "None", # "None", "Level", "Skill", "Both" "MULTIPLAYING": "None", # "None", "Restricted", "Full" "PLAYERKILLING": "None", # "None", "Restricted", "Full" "QUEST SYSTEM": "None", # "None", "Immortal Run", "Automated", "Integrated" "ROLEPLAYING": "None", # "None", "Accepted", "Encouraged", "Enforced" "TRAINING SYSTEM": "None", # "None", "Level", "Skill", "Both" "WORLD ORIGINALITY": "None", # "All Stock", "Mostly Stock", "Mostly Original", "All Original" # Protocols (only change if you added/removed something manually) "ATCP": "0", "MSDP": "0", "MCCP": "1", "SSL": "1", "UTF-8": "1", "ZMP": "0", "XTERM 256 COLORS": "0" } # update the static table with the custom one if MSSPTable_CUSTOM: self.mssp_table.update(MSSPTable_CUSTOM) varlist = '' for variable, value in self.mssp_table.items(): if callable(value): value = value() if utils.is_iter(value): for partval in value: varlist += MSSP_VAR + str(variable) + MSSP_VAL + str( partval) else: varlist += MSSP_VAR + str(variable) + MSSP_VAL + str(value) # send to crawler by subnegotiation self.protocol.requestNegotiation(MSSP, varlist) self.protocol.handshake_done()
def get_objs_with_key_or_alias(self, ostring, exact=True, candidates=None, typeclasses=None): """ Returns objects based on key or alias match. Will also do fuzzy matching based on the utils.string_partial_matching function. candidates - list of candidate objects to restrict on typeclasses - list of typeclass path strings to restrict on """ if not isinstance(ostring, basestring): if hasattr(ostring, "key"): ostring = ostring.key else: return [] if is_iter(candidates) and not len(candidates): # if candidates is an empty iterable there can be no matches # Exit early. return [] # build query objects candidates_id = [ _GA(obj, "id") for obj in make_iter(candidates) if obj ] cand_restriction = candidates != None and Q( pk__in=make_iter(candidates_id)) or Q() type_restriction = typeclasses and Q( db_typeclass_path__in=make_iter(typeclasses)) or Q() if exact: # exact match - do direct search return self.filter(cand_restriction & type_restriction & ( Q(db_key__iexact=ostring) | Q(db_tags__db_key__iexact=ostring) & Q(db_tags__db_tagtype__iexact="alias"))).distinct() elif candidates: # fuzzy with candidates key_candidates = self.filter(cand_restriction & type_restriction) else: # fuzzy without supplied candidates - we select our own candidates key_candidates = self.filter(type_restriction & ( Q(db_key__istartswith=ostring) | Q(db_tags__db_key__istartswith=ostring))).distinct() candidates_id = [_GA(obj, "id") for obj in key_candidates] # fuzzy matching key_strings = key_candidates.values_list("db_key", flat=True) index_matches = string_partial_matching(key_strings, ostring, ret_index=True) if index_matches: return [ obj for ind, obj in enumerate(key_candidates) if ind in index_matches ] else: alias_candidates = self.filter(id__in=candidates_id, db_tags__db_tagtype__iexact="alias") alias_strings = alias_candidates.values_list("db_key", flat=True) index_matches = string_partial_matching(alias_strings, ostring, ret_index=True) if index_matches: return [ alias.db_obj for ind, alias in enumerate(alias_candidates) if ind in index_matches ] return []
def test_is_iter(self): self.assertEqual(True, utils.is_iter([1,2,3,4])) self.assertEqual(False, utils.is_iter("This is not an iterable"))
def test_is_iter(self): self.assertEqual(True, utils.is_iter([1, 2, 3, 4])) self.assertEqual(False, utils.is_iter("This is not an iterable"))
def aliases_set(self, value): "Setter. Allows for self.aliases = value. Stores as a comma-separated string." if is_iter(value): value = ",".join([str(val).strip().lower() for val in value]) self.db_aliases = value self.save()
def func(self): "Implements the command." caller = self.caller args = self.args if hasattr(caller, 'player'): caller = caller.player if not args: caller.msg("Usage: @delplayer[/delobj] <player/user name or #id> [: reason]") return reason = "" if ':' in args: args, reason = [arg.strip() for arg in args.split(':', 1)] # We use player_search since we want to be sure to find also players # that lack characters. players = caller.search("*%s" % args) if not players: try: players = PlayerDB.objects.filter(id=args) except ValueError: pass if not players: # try to find a user instead of a Player try: user = User.objects.get(id=args) except Exception: try: user = User.objects.get(username__iexact=args) except Exception: string = "No Player nor User found matching '%s'." % args caller.msg(string) return try: player = user.get_profile() except Exception: player = None if player and not player.access(caller, 'delete'): string = "You don't have the permissions to delete this player." caller.msg(string) return string = "" name = user.username user.delete() if player: name = player.name player.delete() string = "Player %s was deleted." % name else: string += "The User %s was deleted. It had no Player associated with it." % name caller.msg(string) return elif utils.is_iter(players): string = "There were multiple matches:" for player in players: string += "\n %s %s" % (player.id, player.key) return else: # one single match player = players user = player.user character = player.character if not player.access(caller, 'delete'): string = "You don't have the permissions to delete that player." caller.msg(string) return uname = user.username # boot the player then delete if character and character.has_player: caller.msg("Booting and informing player ...") string = "\nYour account '%s' is being *permanently* deleted.\n" % uname if reason: string += " Reason given:\n '%s'" % reason character.msg(string) # we have a bootable object with a connected player sessions = SESSIONS.sessions_from_player(character.player) for session in sessions: session.msg(string) session.disconnect() user.delete() player.delete() caller.msg("Player %s was successfully deleted." % uname)
def cmdset_storage_set(self, value): "Setter. Allows for self.name = value. Stores as a comma-separated string." if utils.is_iter(value): value = ",".join([str(val).strip() for val in value]) _SA(self, "db_cmdset_storage", value) _GA(self, "save")()