Make PEP8 cleanup of line spaces and character distances as well as indents

This commit is contained in:
Griatch 2017-08-19 23:16:36 +02:00
parent 7ff783fea1
commit b278337172
189 changed files with 2039 additions and 1583 deletions

View file

@ -47,6 +47,7 @@ manually later.
# Helper functions # Helper functions
def _green(string): def _green(string):
if USE_COLOR: if USE_COLOR:
return "%s%s%s" % (ANSI_GREEN, string, ANSI_NORMAL) return "%s%s%s" % (ANSI_GREEN, string, ANSI_NORMAL)
@ -287,7 +288,6 @@ def rename_in_file(path, in_list, out_list, is_interactive):
continue continue
if __name__ == "__main__": if __name__ == "__main__":
import argparse import argparse

View file

@ -5,7 +5,8 @@ the python bin directory and makes the 'evennia' program available on
the command %path%. the command %path%.
""" """
import os, sys import os
import sys
# for pip install -e # for pip install -e
sys.path.insert(0, os.path.abspath(os.getcwd())) sys.path.insert(0, os.path.abspath(os.getcwd()))

View file

@ -109,9 +109,11 @@ def _create_version():
pass pass
return version return version
__version__ = _create_version() __version__ = _create_version()
del _create_version del _create_version
def _init(): def _init():
""" """
This function is called automatically by the launcher only after This function is called automatically by the launcher only after
@ -191,6 +193,7 @@ def _init():
Parent for other containers Parent for other containers
""" """
def _help(self): def _help(self):
"Returns list of contents" "Returns list of contents"
names = [name for name in self.__class__.__dict__ if not name.startswith('_')] names = [name for name in self.__class__.__dict__ if not name.startswith('_')]
@ -198,7 +201,6 @@ def _init():
print(self.__doc__ + "-" * 60 + "\n" + ", ".join(names)) print(self.__doc__ + "-" * 60 + "\n" + ", ".join(names))
help = property(_help) help = property(_help)
class DBmanagers(_EvContainer): class DBmanagers(_EvContainer):
""" """
Links to instantiated database managers. Links to instantiated database managers.
@ -241,7 +243,6 @@ def _init():
managers = DBmanagers() managers = DBmanagers()
del DBmanagers del DBmanagers
class DefaultCmds(_EvContainer): class DefaultCmds(_EvContainer):
""" """
This container holds direct shortcuts to all default commands in Evennia. This container holds direct shortcuts to all default commands in Evennia.
@ -282,7 +283,6 @@ def _init():
default_cmds = DefaultCmds() default_cmds = DefaultCmds()
del DefaultCmds del DefaultCmds
class SystemCmds(_EvContainer): class SystemCmds(_EvContainer):
""" """
Creating commands with keys set to these constants will make Creating commands with keys set to these constants will make
@ -313,6 +313,7 @@ def _init():
del SystemCmds del SystemCmds
del _EvContainer del _EvContainer
del object del object
del absolute_import del absolute_import
del print_function del print_function

View file

@ -879,10 +879,10 @@ class DefaultAccount(with_metaclass(TypeclassBase, AccountDB)):
result.append(nsess == 1 and "\n\n|wConnected session:|n" or "\n\n|wConnected sessions (%i):|n" % nsess) result.append(nsess == 1 and "\n\n|wConnected session:|n" or "\n\n|wConnected sessions (%i):|n" % nsess)
for isess, sess in enumerate(sessions): for isess, sess in enumerate(sessions):
csessid = sess.sessid csessid = sess.sessid
addr = "%s (%s)" % (sess.protocol_key, isinstance(sess.address, tuple) addr = "%s (%s)" % (sess.protocol_key, isinstance(sess.address, tuple) and
and str(sess.address[0]) or str(sess.address)) str(sess.address[0]) or str(sess.address))
result.append("\n %s %s" % (session.sessid == csessid and "|w* %s|n" % (isess + 1) result.append("\n %s %s" % (session.sessid == csessid and "|w* %s|n" % (isess + 1) or
or " %s" % (isess + 1), addr)) " %s" % (isess + 1), addr))
result.append("\n\n |whelp|n - more commands") result.append("\n\n |whelp|n - more commands")
result.append("\n |wooc <Text>|n - talk on public channel") result.append("\n |wooc <Text>|n - talk on public channel")
@ -928,6 +928,7 @@ class DefaultGuest(DefaultAccount):
This class is used for guest logins. Unlike Accounts, Guests and This class is used for guest logins. Unlike Accounts, Guests and
their characters are deleted after disconnection. their characters are deleted after disconnection.
""" """
def at_post_login(self, session=None, **kwargs): def at_post_login(self, session=None, **kwargs):
""" """
In theory, guests only have one character regardless of which In theory, guests only have one character regardless of which

View file

@ -252,4 +252,5 @@ class AccountDBAdmin(BaseUserAdmin):
return HttpResponseRedirect(reverse("admin:accounts_accountdb_change", args=[obj.id])) return HttpResponseRedirect(reverse("admin:accounts_accountdb_change", args=[obj.id]))
return HttpResponseRedirect(reverse("admin:accounts_accountdb_change", args=[obj.id])) return HttpResponseRedirect(reverse("admin:accounts_accountdb_change", args=[obj.id]))
admin.site.register(AccountDB, AccountDBAdmin) admin.site.register(AccountDB, AccountDBAdmin)

View file

@ -28,6 +28,7 @@ class BotStarter(DefaultScript):
into gear when it is initialized. into gear when it is initialized.
""" """
def at_script_creation(self): def at_script_creation(self):
""" """
Called once, when script is created. Called once, when script is created.
@ -148,6 +149,7 @@ class IRCBot(Bot):
Bot for handling IRC connections. Bot for handling IRC connections.
""" """
def start(self, ev_channel=None, irc_botname=None, irc_channel=None, irc_network=None, irc_port=None, irc_ssl=None): def start(self, ev_channel=None, irc_botname=None, irc_channel=None, irc_network=None, irc_port=None, irc_ssl=None):
""" """
Start by telling the portal to start a new session. Start by telling the portal to start a new session.
@ -359,6 +361,7 @@ class RSSBot(Bot):
its feed at regular intervals. its feed at regular intervals.
""" """
def start(self, ev_channel=None, rss_url=None, rss_rate=None): def start(self, ev_channel=None, rss_url=None, rss_rate=None):
""" """
Start by telling the portal to start a new RSS session Start by telling the portal to start a new RSS session

View file

@ -38,6 +38,7 @@ class AccountDBManager(TypedObjectManager, UserManager):
#swap_character #swap_character
""" """
def num_total_accounts(self): def num_total_accounts(self):
""" """
Get total number of accounts. Get total number of accounts.

View file

@ -3,12 +3,14 @@ from __future__ import unicode_literals
from django.db import models, migrations from django.db import models, migrations
def convert_defaults(apps, schema_editor): def convert_defaults(apps, schema_editor):
AccountDB = apps.get_model("accounts", "AccountDB") AccountDB = apps.get_model("accounts", "AccountDB")
for account in AccountDB.objects.filter(db_typeclass_path="src.accounts.account.Account"): for account in AccountDB.objects.filter(db_typeclass_path="src.accounts.account.Account"):
account.db_typeclass_path = "typeclasses.accounts.Account" account.db_typeclass_path = "typeclasses.accounts.Account"
account.save() account.save()
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [

View file

@ -234,19 +234,23 @@ class NoCmdSets(Exception):
class ExecSystemCommand(Exception): class ExecSystemCommand(Exception):
"Run a system command" "Run a system command"
def __init__(self, syscmd, sysarg): def __init__(self, syscmd, sysarg):
self.args = (syscmd, sysarg) # needed by exception error handling self.args = (syscmd, sysarg) # needed by exception error handling
self.syscmd = syscmd self.syscmd = syscmd
self.sysarg = sysarg self.sysarg = sysarg
class ErrorReported(Exception): class ErrorReported(Exception):
"Re-raised when a subsructure already reported the error" "Re-raised when a subsructure already reported the error"
def __init__(self, raw_string): def __init__(self, raw_string):
self.args = (raw_string,) self.args = (raw_string,)
self.raw_string = raw_string self.raw_string = raw_string
# Helper function # Helper function
@inlineCallbacks @inlineCallbacks
def get_and_merge_cmdsets(caller, session, account, obj, callertype, raw_string): def get_and_merge_cmdsets(caller, session, account, obj, callertype, raw_string):
""" """
@ -333,7 +337,6 @@ def get_and_merge_cmdsets(caller, session, account, obj, callertype, raw_string)
_msg_err(caller, _ERROR_CMDSETS) _msg_err(caller, _ERROR_CMDSETS)
raise ErrorReported(raw_string) raise ErrorReported(raw_string)
@inlineCallbacks @inlineCallbacks
def _get_cmdsets(obj): def _get_cmdsets(obj):
""" """
@ -615,7 +618,6 @@ def cmdhandler(called_by, raw_string, _testing=False, callertype="session", sess
finally: finally:
_COMMAND_NESTING[called_by] -= 1 _COMMAND_NESTING[called_by] -= 1
raw_string = to_unicode(raw_string, force_string=True) raw_string = to_unicode(raw_string, force_string=True)
session, account, obj = session, None, None session, account, obj = session, None, None

View file

@ -14,6 +14,7 @@ from evennia.utils.logger import log_trace
_MULTIMATCH_REGEX = re.compile(settings.SEARCH_MULTIMATCH_REGEX, re.I + re.U) _MULTIMATCH_REGEX = re.compile(settings.SEARCH_MULTIMATCH_REGEX, re.I + re.U)
_CMD_IGNORE_PREFIXES = settings.CMD_IGNORE_PREFIXES _CMD_IGNORE_PREFIXES = settings.CMD_IGNORE_PREFIXES
def cmdparser(raw_string, cmdset, caller, match_index=None): def cmdparser(raw_string, cmdset, caller, match_index=None):
""" """
This function is called by the cmdhandler once it has This function is called by the cmdhandler once it has
@ -83,8 +84,8 @@ def cmdparser(raw_string, cmdset, caller, match_index=None):
for cmd in cmdset: for cmd in cmdset:
matches.extend([create_match(cmdname, raw_string, cmd, cmdname) matches.extend([create_match(cmdname, raw_string, cmd, cmdname)
for cmdname in [cmd.key] + cmd.aliases for cmdname in [cmd.key] + cmd.aliases
if cmdname and l_raw_string.startswith(cmdname.lower()) if cmdname and l_raw_string.startswith(cmdname.lower()) and
and (not cmd.arg_regex or (not cmd.arg_regex or
cmd.arg_regex.match(l_raw_string[len(cmdname):]))]) cmd.arg_regex.match(l_raw_string[len(cmdname):]))])
else: else:
# strip prefixes set in settings # strip prefixes set in settings
@ -151,7 +152,7 @@ def cmdparser(raw_string, cmdset, caller, match_index=None):
quality = [mat[4] for mat in matches] quality = [mat[4] for mat in matches]
matches = matches[-quality.count(quality[-1]):] matches = matches[-quality.count(quality[-1]):]
if len(matches) > 1 and match_index != None and 0 < match_index <= len(matches): if len(matches) > 1 and match_index is not None and 0 < match_index <= len(matches):
# We couldn't separate match by quality, but we have an # We couldn't separate match by quality, but we have an
# index argument to tell us which match to use. # index argument to tell us which match to use.
matches = [matches[match_index - 1]] matches = [matches[match_index - 1]]

View file

@ -51,7 +51,7 @@ class _CmdSetMeta(type):
cls.key = cls.__name__ cls.key = cls.__name__
cls.path = "%s.%s" % (cls.__module__, cls.__name__) cls.path = "%s.%s" % (cls.__module__, cls.__name__)
if not type(cls.key_mergetypes) == dict: if not isinstance(cls.key_mergetypes, dict):
cls.key_mergetypes = {} cls.key_mergetypes = {}
super(_CmdSetMeta, cls).__init__(*args, **kwargs) super(_CmdSetMeta, cls).__init__(*args, **kwargs)
@ -214,7 +214,7 @@ class CmdSet(with_metaclass(_CmdSetMeta, object)):
cmdset_c.commands.extend(cmdset_b.commands) cmdset_c.commands.extend(cmdset_b.commands)
else: else:
cmdset_c.commands.extend([cmd for cmd in cmdset_b cmdset_c.commands.extend([cmd for cmd in cmdset_b
if not cmd in cmdset_a]) if cmd not in cmdset_a])
return cmdset_c return cmdset_c
def _intersect(self, cmdset_a, cmdset_b): def _intersect(self, cmdset_a, cmdset_b):
@ -280,7 +280,7 @@ class CmdSet(with_metaclass(_CmdSetMeta, object)):
""" """
cmdset_c = cmdset_a._duplicate() cmdset_c = cmdset_a._duplicate()
cmdset_c.commands = [cmd for cmd in cmdset_b if not cmd in cmdset_a] cmdset_c.commands = [cmd for cmd in cmdset_b if cmd not in cmdset_a]
return cmdset_c return cmdset_c
def _instantiate(self, cmd): def _instantiate(self, cmd):

View file

@ -122,6 +122,7 @@ class _ErrorCmdSet(CmdSet):
key = "_CMDSET_ERROR" key = "_CMDSET_ERROR"
errmessage = "Error when loading cmdset." errmessage = "Error when loading cmdset."
class _EmptyCmdSet(CmdSet): class _EmptyCmdSet(CmdSet):
""" """
This cmdset represents an empty cmdset This cmdset represents an empty cmdset
@ -130,6 +131,7 @@ class _EmptyCmdSet(CmdSet):
priority = -101 priority = -101
mergetype = "Union" mergetype = "Union"
def import_cmdset(path, cmdsetobj, emit_to_obj=None, no_logging=False): def import_cmdset(path, cmdsetobj, emit_to_obj=None, no_logging=False):
""" """
This helper function is used by the cmdsethandler to load a cmdset This helper function is used by the cmdsethandler to load a cmdset
@ -542,7 +544,6 @@ class CmdSetHandler(object):
# legacy alias # legacy alias
delete_default = remove_default delete_default = remove_default
def all(self): def all(self):
""" """
Show all cmdsets. Show all cmdsets.

View file

@ -60,7 +60,7 @@ def _init_command(cls, **kwargs):
if "cmd:" not in cls.locks: if "cmd:" not in cls.locks:
cls.locks = "cmd:all();" + cls.locks cls.locks = "cmd:all();" + cls.locks
for lockstring in cls.locks.split(';'): for lockstring in cls.locks.split(';'):
if lockstring and not ':' in lockstring: if lockstring and ':' not in lockstring:
lockstring = "cmd:%s" % lockstring lockstring = "cmd:%s" % lockstring
temp.append(lockstring) temp.append(lockstring)
cls.lock_storage = ";".join(temp) cls.lock_storage = ";".join(temp)

View file

@ -364,7 +364,7 @@ class CmdSessions(COMMAND_DEFAULT_CLASS):
for sess in sorted(sessions, key=lambda x: x.sessid): for sess in sorted(sessions, key=lambda x: x.sessid):
char = account.get_puppet(sess) char = account.get_puppet(sess)
table.add_row(str(sess.sessid), str(sess.protocol_key), table.add_row(str(sess.sessid), str(sess.protocol_key),
type(sess.address) == tuple and sess.address[0] or sess.address, isinstance(sess.address, tuple) and sess.address[0] or sess.address,
char and str(char) or "None", char and str(char) or "None",
char and str(char.location) or "N/A") char and str(char.location) or "N/A")
self.msg("|wYour current session(s):|n\n%s" % table) self.msg("|wYour current session(s):|n\n%s" % table)
@ -552,7 +552,7 @@ class CmdOption(COMMAND_DEFAULT_CLASS):
flags[new_name] = new_val flags[new_name] = new_val
self.msg("Option |w%s|n was changed from '|w%s|n' to '|w%s|n'." % (new_name, old_val, new_val)) self.msg("Option |w%s|n was changed from '|w%s|n' to '|w%s|n'." % (new_name, old_val, new_val))
return {new_name: new_val} return {new_name: new_val}
except Exception, err: except Exception as err:
self.msg("|rCould not set option |w%s|r:|n %s" % (new_name, err)) self.msg("|rCould not set option |w%s|r:|n %s" % (new_name, err))
return False return False

View file

@ -171,8 +171,8 @@ class CmdBan(COMMAND_DEFAULT_CLASS):
if not banlist: if not banlist:
banlist = [] banlist = []
if not self.args or (self.switches if not self.args or (self.switches and
and not any(switch in ('ip', 'name') not any(switch in ('ip', 'name')
for switch in self.switches)): for switch in self.switches)):
self.caller.msg(list_bans(banlist)) self.caller.msg(list_bans(banlist))
return return

View file

@ -41,6 +41,7 @@ _DEFAULT_WIDTH = settings.CLIENT_DEFAULT_WIDTH
_PROTOTYPE_PARENTS = None _PROTOTYPE_PARENTS = None
class ObjManipCommand(COMMAND_DEFAULT_CLASS): class ObjManipCommand(COMMAND_DEFAULT_CLASS):
""" """
This is a parent class for some of the defining objmanip commands This is a parent class for some of the defining objmanip commands
@ -522,6 +523,7 @@ class CmdCreate(ObjManipCommand):
def _desc_load(caller): def _desc_load(caller):
return caller.db.evmenu_target.db.desc or "" return caller.db.evmenu_target.db.desc or ""
def _desc_save(caller, buf): def _desc_save(caller, buf):
""" """
Save line buffer to the desc prop. This should Save line buffer to the desc prop. This should
@ -531,10 +533,12 @@ def _desc_save(caller, buf):
caller.msg("Saved.") caller.msg("Saved.")
return True return True
def _desc_quit(caller): def _desc_quit(caller):
caller.attributes.remove("evmenu_target") caller.attributes.remove("evmenu_target")
caller.msg("Exited editor.") caller.msg("Exited editor.")
class CmdDesc(COMMAND_DEFAULT_CLASS): class CmdDesc(COMMAND_DEFAULT_CLASS):
""" """
describe an object or the current room. describe an object or the current room.
@ -642,7 +646,7 @@ class CmdDestroy(COMMAND_DEFAULT_CLASS):
objname = obj.name objname = obj.name
if not (obj.access(caller, "control") or obj.access(caller, 'delete')): if not (obj.access(caller, "control") or obj.access(caller, 'delete')):
return "\nYou don't have permission to delete %s." % objname return "\nYou don't have permission to delete %s." % objname
if obj.account and not 'override' in self.switches: if obj.account and 'override' not in self.switches:
return "\nObject %s is controlled by an active account. Use /override to delete anyway." % objname return "\nObject %s is controlled by an active account. Use /override to delete anyway." % objname
if obj.dbid == int(settings.DEFAULT_HOME.lstrip("#")): if obj.dbid == int(settings.DEFAULT_HOME.lstrip("#")):
return "\nYou are trying to delete |c%s|n, which is set as DEFAULT_HOME. " \ return "\nYou are trying to delete |c%s|n, which is set as DEFAULT_HOME. " \
@ -821,6 +825,7 @@ class CmdDig(ObjManipCommand):
if new_room and ('teleport' in self.switches or "tel" in self.switches): if new_room and ('teleport' in self.switches or "tel" in self.switches):
caller.move_to(new_room) caller.move_to(new_room)
class CmdTunnel(COMMAND_DEFAULT_CLASS): class CmdTunnel(COMMAND_DEFAULT_CLASS):
""" """
create new rooms in cardinal directions only create new rooms in cardinal directions only
@ -893,7 +898,7 @@ class CmdTunnel(COMMAND_DEFAULT_CLASS):
if "tel" in self.switches: if "tel" in self.switches:
telswitch = "/teleport" telswitch = "/teleport"
backstring = "" backstring = ""
if not "oneway" in self.switches: if "oneway" not in self.switches:
backstring = ", %s;%s" % (backname, backshort) backstring = ", %s;%s" % (backname, backshort)
# build the string we will use to call @dig # build the string we will use to call @dig
@ -1484,10 +1489,11 @@ class CmdSetAttribute(ObjManipCommand):
old_value = obj.attributes.get(attr) old_value = obj.attributes.get(attr)
if old_value is not None and not isinstance(old_value, basestring): if old_value is not None and not isinstance(old_value, basestring):
typ = type(old_value).__name__ typ = type(old_value).__name__
self.caller.msg("|RWARNING! Saving this buffer will overwrite the "\ self.caller.msg("|RWARNING! Saving this buffer will overwrite the "
"current attribute (of type %s) with a string!|n" % typ) "current attribute (of type %s) with a string!|n" % typ)
return str(old_value) return str(old_value)
return old_value return old_value
def save(caller, buf): def save(caller, buf):
"Called when editor saves its buffer." "Called when editor saves its buffer."
obj.attributes.add(attr, buf) obj.attributes.add(attr, buf)
@ -1495,7 +1501,6 @@ class CmdSetAttribute(ObjManipCommand):
# start the editor # start the editor
EvEditor(self.caller, load, save, key="%s/%s" % (obj, attr)) EvEditor(self.caller, load, save, key="%s/%s" % (obj, attr))
def func(self): def func(self):
"Implement the set attribute - a limited form of @py." "Implement the set attribute - a limited form of @py."
@ -1523,7 +1528,7 @@ class CmdSetAttribute(ObjManipCommand):
if "edit" in self.switches: if "edit" in self.switches:
# edit in the line editor # edit in the line editor
if len(attrs) > 1: if len(attrs) > 1:
caller.msg("The Line editor can only be applied " \ caller.msg("The Line editor can only be applied "
"to one attribute at a time.") "to one attribute at a time.")
return return
self.edit_handler(obj, attrs[0]) self.edit_handler(obj, attrs[0])
@ -1644,7 +1649,7 @@ class CmdTypeclass(COMMAND_DEFAULT_CLASS):
return return
is_same = obj.is_typeclass(new_typeclass, exact=True) is_same = obj.is_typeclass(new_typeclass, exact=True)
if is_same and not 'force' in self.switches: if is_same and 'force' not in self.switches:
string = "%s already has the typeclass '%s'. Use /force to override." % (obj.name, new_typeclass) string = "%s already has the typeclass '%s'. Use /force to override." % (obj.name, new_typeclass)
else: else:
update = "update" in self.switches update = "update" in self.switches
@ -1797,8 +1802,8 @@ class CmdLock(ObjManipCommand):
# we have a = separator, so we are assigning a new lock # we have a = separator, so we are assigning a new lock
if self.switches: if self.switches:
swi = ", ".join(self.switches) swi = ", ".join(self.switches)
caller.msg("Switch(es) |w%s|n can not be used with a "\ caller.msg("Switch(es) |w%s|n can not be used with a "
"lock assignment. Use e.g. " \ "lock assignment. Use e.g. "
"|w@lock/del objname/locktype|n instead." % swi) "|w@lock/del objname/locktype|n instead." % swi)
return return
@ -1957,11 +1962,10 @@ class CmdExamine(ObjManipCommand):
locks_string = " Default" locks_string = " Default"
string += "\n|wLocks|n:%s" % locks_string string += "\n|wLocks|n:%s" % locks_string
if not (len(obj.cmdset.all()) == 1 and obj.cmdset.current.key == "_EMPTY_CMDSET"): if not (len(obj.cmdset.all()) == 1 and obj.cmdset.current.key == "_EMPTY_CMDSET"):
# all() returns a 'stack', so make a copy to sort. # all() returns a 'stack', so make a copy to sort.
stored_cmdsets = sorted(obj.cmdset.all(), key=lambda x: x.priority, reverse=True) stored_cmdsets = sorted(obj.cmdset.all(), key=lambda x: x.priority, reverse=True)
string += "\n|wStored Cmdset(s)|n:\n %s" % ("\n ".join("%s [%s] (%s, prio %s)" % \ string += "\n|wStored Cmdset(s)|n:\n %s" % ("\n ".join("%s [%s] (%s, prio %s)" %
(cmdset.path, cmdset.key, cmdset.mergetype, cmdset.priority) (cmdset.path, cmdset.key, cmdset.mergetype, cmdset.priority)
for cmdset in stored_cmdsets if cmdset.key != "_EMPTY_CMDSET")) for cmdset in stored_cmdsets if cmdset.key != "_EMPTY_CMDSET"))
@ -1986,11 +1990,10 @@ class CmdExamine(ObjManipCommand):
pass pass
all_cmdsets = [cmdset for cmdset in dict(all_cmdsets).values()] all_cmdsets = [cmdset for cmdset in dict(all_cmdsets).values()]
all_cmdsets.sort(key=lambda x: x.priority, reverse=True) all_cmdsets.sort(key=lambda x: x.priority, reverse=True)
string += "\n|wMerged Cmdset(s)|n:\n %s" % ("\n ".join("%s [%s] (%s, prio %s)" % \ string += "\n|wMerged Cmdset(s)|n:\n %s" % ("\n ".join("%s [%s] (%s, prio %s)" %
(cmdset.path, cmdset.key, cmdset.mergetype, cmdset.priority) (cmdset.path, cmdset.key, cmdset.mergetype, cmdset.priority)
for cmdset in all_cmdsets)) for cmdset in all_cmdsets))
# list the commands available to this object # list the commands available to this object
avail_cmdset = sorted([cmd.key for cmd in avail_cmdset avail_cmdset = sorted([cmd.key for cmd in avail_cmdset
if cmd.access(obj, "cmd")]) if cmd.access(obj, "cmd")])
@ -2561,6 +2564,7 @@ class CmdTag(COMMAND_DEFAULT_CLASS):
# Reload the server and the prototypes should be available. # Reload the server and the prototypes should be available.
# #
class CmdSpawn(COMMAND_DEFAULT_CLASS): class CmdSpawn(COMMAND_DEFAULT_CLASS):
""" """
spawn objects from prototype spawn objects from prototype
@ -2628,7 +2632,6 @@ class CmdSpawn(COMMAND_DEFAULT_CLASS):
self.caller.msg(string) self.caller.msg(string)
return return
if isinstance(prototype, basestring): if isinstance(prototype, basestring):
# A prototype key # A prototype key
keystr = prototype keystr = prototype
@ -2647,9 +2650,8 @@ class CmdSpawn(COMMAND_DEFAULT_CLASS):
self.caller.msg("The prototype must be a prototype key or a Python dictionary.") self.caller.msg("The prototype must be a prototype key or a Python dictionary.")
return return
if not "noloc" in self.switches and not "location" in prototype: if "noloc" in self.switches and not "location" not in prototype:
prototype["location"] = self.caller.location prototype["location"] = self.caller.location
for obj in spawn(prototype): for obj in spawn(prototype):
self.caller.msg("Spawned %s." % obj.get_display_name(self.caller)) self.caller.msg("Spawned %s." % obj.get_display_name(self.caller))

View file

@ -9,6 +9,7 @@ from evennia.commands.default import general, help, admin, system
from evennia.commands.default import building from evennia.commands.default import building
from evennia.commands.default import batchprocess from evennia.commands.default import batchprocess
class CharacterCmdSet(CmdSet): class CharacterCmdSet(CmdSet):
""" """
Implements the default command set. Implements the default command set.

View file

@ -4,6 +4,7 @@ This module stores session-level commands.
from evennia.commands.cmdset import CmdSet from evennia.commands.cmdset import CmdSet
from evennia.commands.default import account from evennia.commands.default import account
class SessionCmdSet(CmdSet): class SessionCmdSet(CmdSet):
""" """
Sets up the unlogged cmdset. Sets up the unlogged cmdset.

View file

@ -614,7 +614,7 @@ class CmdClock(COMMAND_DEFAULT_CLASS):
# Try to add the lock # Try to add the lock
try: try:
channel.locks.add(self.rhs) channel.locks.add(self.rhs)
except LockException, err: except LockException as err:
self.msg(err) self.msg(err)
return return
string = "Lock(s) applied. " string = "Lock(s) applied. "

View file

@ -419,6 +419,7 @@ class CmdSay(COMMAND_DEFAULT_CLASS):
# Call the at_after_say hook on the character # Call the at_after_say hook on the character
caller.at_say(speech) caller.at_say(speech)
class CmdWhisper(COMMAND_DEFAULT_CLASS): class CmdWhisper(COMMAND_DEFAULT_CLASS):
""" """
Speak privately as your character to another Speak privately as your character to another

View file

@ -22,6 +22,7 @@ class MuxCommand(Command):
used by Evennia to create the automatic help entry for used by Evennia to create the automatic help entry for
the command, so make sure to document consistently here. the command, so make sure to document consistently here.
""" """
def has_perm(self, srcobj): def has_perm(self, srcobj):
""" """
This is called by the cmdhandler to determine This is called by the cmdhandler to determine
@ -191,6 +192,7 @@ class MuxAccountCommand(MuxCommand):
creating a new property "character" that is set only if a creating a new property "character" that is set only if a
character is actually attached to this Account and Session. character is actually attached to this Account and Session.
""" """
def parse(self): def parse(self):
""" """
We run the parent parser as usual, then fix the result We run the parent parser as usual, then fix the result

View file

@ -332,6 +332,7 @@ class TestBatchProcess(CommandTest):
# we make sure to delete the button again here to stop the running reactor # we make sure to delete the button again here to stop the running reactor
self.call(building.CmdDestroy(), "button", "button was destroyed.") self.call(building.CmdDestroy(), "button", "button was destroyed.")
class CmdInterrupt(Command): class CmdInterrupt(Command):
key = "interrupt" key = "interrupt"

View file

@ -168,8 +168,8 @@ def create_normal_account(session, name, password):
# Check IP and/or name bans # Check IP and/or name bans
bans = ServerConfig.objects.conf("server_bans") bans = ServerConfig.objects.conf("server_bans")
if bans and (any(tup[0] == account.name.lower() for tup in bans) if bans and (any(tup[0] == account.name.lower() for tup in bans) or
or
any(tup[2].match(session.address) for tup in bans if tup[2])): any(tup[2].match(session.address) for tup in bans if tup[2])):
# this is a banned IP or name! # this is a banned IP or name!
string = "|rYou have been banned and cannot continue from here." \ string = "|rYou have been banned and cannot continue from here." \
@ -301,8 +301,8 @@ class CmdUnconnectedCreate(COMMAND_DEFAULT_CLASS):
# Check IP and/or name bans # Check IP and/or name bans
bans = ServerConfig.objects.conf("server_bans") bans = ServerConfig.objects.conf("server_bans")
if bans and (any(tup[0] == accountname.lower() for tup in bans) if bans and (any(tup[0] == accountname.lower() for tup in bans) or
or
any(tup[2].match(session.address) for tup in bans if tup[2])): any(tup[2].match(session.address) for tup in bans if tup[2])):
# this is a banned IP or name! # this is a banned IP or name!
string = "|rYou have been banned and cannot continue from here." \ string = "|rYou have been banned and cannot continue from here." \

View file

@ -12,45 +12,66 @@ from evennia.commands.command import Command
class _CmdA(Command): class _CmdA(Command):
key = "A" key = "A"
def __init__(self, cmdset, *args, **kwargs): def __init__(self, cmdset, *args, **kwargs):
super(_CmdA, self).__init__(*args, **kwargs) super(_CmdA, self).__init__(*args, **kwargs)
self.from_cmdset = cmdset self.from_cmdset = cmdset
class _CmdB(Command): class _CmdB(Command):
key = "B" key = "B"
def __init__(self, cmdset, *args, **kwargs): def __init__(self, cmdset, *args, **kwargs):
super(_CmdB, self).__init__(*args, **kwargs) super(_CmdB, self).__init__(*args, **kwargs)
self.from_cmdset = cmdset self.from_cmdset = cmdset
class _CmdC(Command): class _CmdC(Command):
key = "C" key = "C"
def __init__(self, cmdset, *args, **kwargs): def __init__(self, cmdset, *args, **kwargs):
super(_CmdC, self).__init__(*args, **kwargs) super(_CmdC, self).__init__(*args, **kwargs)
self.from_cmdset = cmdset self.from_cmdset = cmdset
class _CmdD(Command): class _CmdD(Command):
key = "D" key = "D"
def __init__(self, cmdset, *args, **kwargs): def __init__(self, cmdset, *args, **kwargs):
super(_CmdD, self).__init__(*args, **kwargs) super(_CmdD, self).__init__(*args, **kwargs)
self.from_cmdset = cmdset self.from_cmdset = cmdset
class _CmdSetA(CmdSet): class _CmdSetA(CmdSet):
key = "A" key = "A"
def at_cmdset_creation(self): def at_cmdset_creation(self):
self.add(_CmdA("A")) self.add(_CmdA("A"))
self.add(_CmdB("A")) self.add(_CmdB("A"))
self.add(_CmdC("A")) self.add(_CmdC("A"))
self.add(_CmdD("A")) self.add(_CmdD("A"))
class _CmdSetB(CmdSet): class _CmdSetB(CmdSet):
key = "B" key = "B"
def at_cmdset_creation(self): def at_cmdset_creation(self):
self.add(_CmdA("B")) self.add(_CmdA("B"))
self.add(_CmdB("B")) self.add(_CmdB("B"))
self.add(_CmdC("B")) self.add(_CmdC("B"))
class _CmdSetC(CmdSet): class _CmdSetC(CmdSet):
key = "C" key = "C"
def at_cmdset_creation(self): def at_cmdset_creation(self):
self.add(_CmdA("C")) self.add(_CmdA("C"))
self.add(_CmdB("C")) self.add(_CmdB("C"))
class _CmdSetD(CmdSet): class _CmdSetD(CmdSet):
key = "D" key = "D"
def at_cmdset_creation(self): def at_cmdset_creation(self):
self.add(_CmdA("D")) self.add(_CmdA("D"))
self.add(_CmdB("D")) self.add(_CmdB("D"))
@ -59,8 +80,10 @@ class _CmdSetD(CmdSet):
# testing Command Sets # testing Command Sets
class TestCmdSetMergers(TestCase): class TestCmdSetMergers(TestCase):
"Test merging of cmdsets" "Test merging of cmdsets"
def setUp(self): def setUp(self):
super(TestCmdSetMergers, self).setUp() super(TestCmdSetMergers, self).setUp()
self.cmdset_a = _CmdSetA() self.cmdset_a = _CmdSetA()
@ -240,10 +263,14 @@ class TestCmdSetMergers(TestCase):
# test cmdhandler functions # test cmdhandler functions
from evennia.commands import cmdhandler from evennia.commands import cmdhandler
from twisted.trial.unittest import TestCase as TwistedTestCase from twisted.trial.unittest import TestCase as TwistedTestCase
class TestGetAndMergeCmdSets(TwistedTestCase, EvenniaTest): class TestGetAndMergeCmdSets(TwistedTestCase, EvenniaTest):
"Test the cmdhandler.get_and_merge_cmdsets function." "Test the cmdhandler.get_and_merge_cmdsets function."
def setUp(self): def setUp(self):
super(TestGetAndMergeCmdSets, self).setUp() super(TestGetAndMergeCmdSets, self).setUp()
self.cmdset_a = _CmdSetA() self.cmdset_a = _CmdSetA()
@ -261,6 +288,7 @@ class TestGetAndMergeCmdSets(TwistedTestCase, EvenniaTest):
a.no_channels = True a.no_channels = True
self.set_cmdsets(self.session, a) self.set_cmdsets(self.session, a)
deferred = cmdhandler.get_and_merge_cmdsets(self.session, self.session, None, None, "session", "") deferred = cmdhandler.get_and_merge_cmdsets(self.session, self.session, None, None, "session", "")
def _callback(cmdset): def _callback(cmdset):
self.assertEqual(cmdset.key, "A") self.assertEqual(cmdset.key, "A")
deferred.addCallback(_callback) deferred.addCallback(_callback)
@ -273,6 +301,7 @@ class TestGetAndMergeCmdSets(TwistedTestCase, EvenniaTest):
self.set_cmdsets(self.account, a) self.set_cmdsets(self.account, a)
deferred = cmdhandler.get_and_merge_cmdsets(self.account, None, self.account, None, "account", "") deferred = cmdhandler.get_and_merge_cmdsets(self.account, None, self.account, None, "account", "")
# get_and_merge_cmdsets converts to lower-case internally. # get_and_merge_cmdsets converts to lower-case internally.
def _callback(cmdset): def _callback(cmdset):
pcmdset = AccountCmdSet() pcmdset = AccountCmdSet()
pcmdset.at_cmdset_creation() pcmdset.at_cmdset_creation()
@ -286,7 +315,8 @@ class TestGetAndMergeCmdSets(TwistedTestCase, EvenniaTest):
self.set_cmdsets(self.obj1, self.cmdset_a) self.set_cmdsets(self.obj1, self.cmdset_a)
deferred = cmdhandler.get_and_merge_cmdsets(self.obj1, None, None, self.obj1, "object", "") deferred = cmdhandler.get_and_merge_cmdsets(self.obj1, None, None, self.obj1, "object", "")
# get_and_merge_cmdsets converts to lower-case internally. # get_and_merge_cmdsets converts to lower-case internally.
_callback = lambda cmdset: self.assertEqual(sum(1 for cmd in cmdset.commands if cmd.key in ("a", "b", "c", "d")), 4)
def _callback(cmdset): return self.assertEqual(sum(1 for cmd in cmdset.commands if cmd.key in ("a", "b", "c", "d")), 4)
deferred.addCallback(_callback) deferred.addCallback(_callback)
return deferred return deferred
@ -296,6 +326,7 @@ class TestGetAndMergeCmdSets(TwistedTestCase, EvenniaTest):
a.no_channels = True a.no_channels = True
self.set_cmdsets(self.obj1, a, b, c, d) self.set_cmdsets(self.obj1, a, b, c, d)
deferred = cmdhandler.get_and_merge_cmdsets(self.obj1, None, None, self.obj1, "object", "") deferred = cmdhandler.get_and_merge_cmdsets(self.obj1, None, None, self.obj1, "object", "")
def _callback(cmdset): def _callback(cmdset):
self.assertTrue(cmdset.no_exits) self.assertTrue(cmdset.no_exits)
self.assertTrue(cmdset.no_channels) self.assertTrue(cmdset.no_channels)
@ -315,6 +346,7 @@ class TestGetAndMergeCmdSets(TwistedTestCase, EvenniaTest):
a, b, c, d = self.cmdset_a, self.cmdset_b, self.cmdset_c, self.cmdset_d a, b, c, d = self.cmdset_a, self.cmdset_b, self.cmdset_c, self.cmdset_d
self.set_cmdsets(self.account, a, b, c, d) self.set_cmdsets(self.account, a, b, c, d)
deferred = cmdhandler.get_and_merge_cmdsets(self.session, self.session, self.account, self.char1, "session", "") deferred = cmdhandler.get_and_merge_cmdsets(self.session, self.session, self.account, self.char1, "session", "")
def _callback(cmdset): def _callback(cmdset):
pcmdset = AccountCmdSet() pcmdset = AccountCmdSet()
pcmdset.at_cmdset_creation() pcmdset.at_cmdset_creation()
@ -332,6 +364,7 @@ class TestGetAndMergeCmdSets(TwistedTestCase, EvenniaTest):
d.duplicates = True d.duplicates = True
self.set_cmdsets(self.obj1, a, b, c, d) self.set_cmdsets(self.obj1, a, b, c, d)
deferred = cmdhandler.get_and_merge_cmdsets(self.obj1, None, None, self.obj1, "object", "") deferred = cmdhandler.get_and_merge_cmdsets(self.obj1, None, None, self.obj1, "object", "")
def _callback(cmdset): def _callback(cmdset):
self.assertEqual(len(cmdset.commands), 9) self.assertEqual(len(cmdset.commands), 9)
deferred.addCallback(_callback) deferred.addCallback(_callback)

View file

@ -34,6 +34,7 @@ from django.utils.translation import ugettext as _
_CHANNEL_COMMAND_CLASS = None _CHANNEL_COMMAND_CLASS = None
_CHANNELDB = None _CHANNELDB = None
class ChannelCommand(command.Command): class ChannelCommand(command.Command):
""" """
{channelkey} channel {channelkey} channel
@ -130,7 +131,8 @@ class ChannelCommand(command.Command):
if self.history_start is not None: if self.history_start is not None:
# Try to view history # Try to view history
log_file = channel.attributes.get("log_file", default="channel_%s.log" % channel.key) log_file = channel.attributes.get("log_file", default="channel_%s.log" % channel.key)
send_msg = lambda lines: self.msg("".join(line.split("[-]", 1)[1]
def send_msg(lines): return self.msg("".join(line.split("[-]", 1)[1]
if "[-]" in line else line for line in lines)) if "[-]" in line else line for line in lines))
tail_log_file(log_file, self.history_start, 20, callback=send_msg) tail_log_file(log_file, self.history_start, 20, callback=send_msg)
else: else:
@ -164,6 +166,7 @@ class ChannelHandler(object):
evennia.create_channel()) evennia.create_channel())
""" """
def __init__(self): def __init__(self):
""" """
Initializes the channel handler's internal state. Initializes the channel handler's internal state.
@ -281,5 +284,6 @@ class ChannelHandler(object):
self.cached_cmdsets[source_object] = chan_cmdset self.cached_cmdsets[source_object] = chan_cmdset
return chan_cmdset return chan_cmdset
CHANNEL_HANDLER = ChannelHandler() CHANNEL_HANDLER = ChannelHandler()
CHANNELHANDLER = CHANNEL_HANDLER # legacy CHANNELHANDLER = CHANNEL_HANDLER # legacy

View file

@ -357,7 +357,6 @@ class DefaultChannel(with_metaclass(TypeclassBase, ChannelDB)):
# hooks # hooks
def channel_prefix(self, msg=None, emit=False, **kwargs): def channel_prefix(self, msg=None, emit=False, **kwargs):
""" """
Hook method. How the channel should prefix itself for users. Hook method. How the channel should prefix itself for users.

View file

@ -332,6 +332,7 @@ class ChannelDBManager(TypedObjectManager):
subscribed to the Channel. subscribed to the Channel.
""" """
def get_all_channels(self): def get_all_channels(self):
""" """
Get all channels. Get all channels.

View file

@ -3,12 +3,14 @@ from __future__ import unicode_literals
from django.db import models, migrations from django.db import models, migrations
def convert_defaults(apps, schema_editor): def convert_defaults(apps, schema_editor):
ChannelDB = apps.get_model("comms", "ChannelDB") ChannelDB = apps.get_model("comms", "ChannelDB")
for channel in ChannelDB.objects.filter(db_typeclass_path="src.comms.comms.Channel"): for channel in ChannelDB.objects.filter(db_typeclass_path="src.comms.comms.Channel"):
channel.db_typeclass_path = "typeclasses.channels.Channel" channel.db_typeclass_path = "typeclasses.channels.Channel"
channel.save() channel.save()
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [

View file

@ -3,6 +3,7 @@ from __future__ import unicode_literals
from django.db import migrations from django.db import migrations
def convert_channelnames(apps, schema_editor): def convert_channelnames(apps, schema_editor):
ChannelDB = apps.get_model("comms", "ChannelDB") ChannelDB = apps.get_model("comms", "ChannelDB")
for chan in ChannelDB.objects.filter(db_key="MUDinfo"): for chan in ChannelDB.objects.filter(db_key="MUDinfo"):
@ -13,6 +14,7 @@ def convert_channelnames(apps, schema_editor):
chan.db_key = "MudInfo" chan.db_key = "MudInfo"
chan.save() chan.save()
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [

View file

@ -250,7 +250,6 @@ class Msg(SharedMemoryModel):
elif clsname == "ChannelDB": elif clsname == "ChannelDB":
self.db_receivers_channels.add(receiver) self.db_receivers_channels.add(receiver)
#@receivers.deleter #@receivers.deleter
def __receivers_del(self): def __receivers_del(self):
"Deleter. Clears all receivers" "Deleter. Clears all receivers"
@ -370,6 +369,7 @@ class Msg(SharedMemoryModel):
# #
#------------------------------------------------------------ #------------------------------------------------------------
class TempMsg(object): class TempMsg(object):
""" """
This is a non-persistent object for sending temporary messages This is a non-persistent object for sending temporary messages
@ -377,6 +377,7 @@ class TempMsg(object):
doesn't require sender to be given. doesn't require sender to be given.
""" """
def __init__(self, senders=None, receivers=None, channels=None, message="", header="", type="", lockstring="", hide_from=None): def __init__(self, senders=None, receivers=None, channels=None, message="", header="", type="", lockstring="", hide_from=None):
""" """
Creates the temp message. Creates the temp message.
@ -471,6 +472,7 @@ class SubscriptionHandler(object):
channel and hides away which type of entity is channel and hides away which type of entity is
subscribing (Account or Object) subscribing (Account or Object)
""" """
def __init__(self, obj): def __init__(self, obj):
""" """
Initialize the handler Initialize the handler

View file

@ -105,6 +105,7 @@ class TradeTimeout(DefaultScript):
""" """
This times out the trade request, in case player B did not reply in time. This times out the trade request, in case player B did not reply in time.
""" """
def at_script_creation(self): def at_script_creation(self):
""" """
Called when script is first created Called when script is first created
@ -136,6 +137,7 @@ class TradeHandler(object):
Objects of this class handles the ongoing trade, notably storing the current Objects of this class handles the ongoing trade, notably storing the current
offers from each side and wether both have accepted or not. offers from each side and wether both have accepted or not.
""" """
def __init__(self, part_a, part_b): def __init__(self, part_a, part_b):
""" """
Initializes the trade. This is called when part A tries to Initializes the trade. This is called when part A tries to
@ -391,6 +393,7 @@ class CmdTradeBase(Command):
Base command for Trade commands to inherit from. Implements the Base command for Trade commands to inherit from. Implements the
custom parsing. custom parsing.
""" """
def parse(self): def parse(self):
""" """
Parse the relevant parts and make it easily Parse the relevant parts and make it easily

View file

@ -179,6 +179,7 @@ class OOCCmdSetCharGen(default_cmds.AccountCmdSet):
""" """
Extends the default OOC cmdset. Extends the default OOC cmdset.
""" """
def at_cmdset_creation(self): def at_cmdset_creation(self):
"""Install everything from the default set, then overload""" """Install everything from the default set, then overload"""
self.add(CmdOOCLook()) self.add(CmdOOCLook())

View file

@ -295,6 +295,7 @@ class ClothedCharacter(DefaultCharacter):
just copy the return_appearance hook defined below to your own game's just copy the return_appearance hook defined below to your own game's
character typeclass. character typeclass.
""" """
def return_appearance(self, looker): def return_appearance(self, looker):
""" """
This formats a description. It is the hook a 'look' command This formats a description. It is the hook a 'look' command

View file

@ -111,7 +111,7 @@ def gametime_to_realtime(format=False, **kwargs):
name = name[:-1] name = name[:-1]
if name not in UNITS: if name not in UNITS:
raise ValueError("the unit {} isn't defined as a valid " \ raise ValueError("the unit {} isn't defined as a valid "
"game time unit".format(name)) "game time unit".format(name))
rtime += value * UNITS[name] rtime += value * UNITS[name]
rtime /= TIMEFACTOR rtime /= TIMEFACTOR
@ -149,6 +149,7 @@ def realtime_to_gametime(secs=0, mins=0, hrs=0, days=0, weeks=0,
return time_to_tuple(gtime, *units) return time_to_tuple(gtime, *units)
return gtime return gtime
def custom_gametime(absolute=False): def custom_gametime(absolute=False):
""" """
Return the custom game time as a tuple of units, as defined in settings. Return the custom game time as a tuple of units, as defined in settings.
@ -168,6 +169,7 @@ def custom_gametime(absolute=False):
del units[-1] del units[-1]
return time_to_tuple(current, *units) return time_to_tuple(current, *units)
def real_seconds_until(**kwargs): def real_seconds_until(**kwargs):
""" """
Return the real seconds until game time. Return the real seconds until game time.
@ -228,6 +230,7 @@ def real_seconds_until(**kwargs):
return (projected - current) / TIMEFACTOR return (projected - current) / TIMEFACTOR
def schedule(callback, repeat=False, **kwargs): def schedule(callback, repeat=False, **kwargs):
""" """
Call the callback when the game time is up. Call the callback when the game time is up.
@ -264,6 +267,8 @@ def schedule(callback, repeat=False, **kwargs):
return script return script
# Scripts dealing in gametime (use `schedule` to create it) # Scripts dealing in gametime (use `schedule` to create it)
class GametimeScript(DefaultScript): class GametimeScript(DefaultScript):
"""Gametime-sensitive script.""" """Gametime-sensitive script."""

View file

@ -118,6 +118,7 @@ def roll_dice(dicenum, dicetype, modifier=None, conditional=None, return_tuple=F
else: else:
return result return result
RE_PARTS = re.compile(r"(d|\+|-|/|\*|<|>|<=|>=|!=|==)") RE_PARTS = re.compile(r"(d|\+|-|/|\*|<|>|<=|>=|!=|==)")
RE_MOD = re.compile(r"(\+|-|/|\*)") RE_MOD = re.compile(r"(\+|-|/|\*)")
RE_COND = re.compile(r"(<|>|<=|>=|!=|==)") RE_COND = re.compile(r"(<|>|<=|>=|!=|==)")
@ -255,6 +256,7 @@ class DiceCmdSet(CmdSet):
a small cmdset for testing purposes. a small cmdset for testing purposes.
Add with @py self.cmdset.add("contrib.dice.DiceCmdSet") Add with @py self.cmdset.add("contrib.dice.DiceCmdSet")
""" """
def at_cmdset_creation(self): def at_cmdset_creation(self):
"""Called when set is created""" """Called when set is created"""
self.add(CmdDice()) self.add(CmdDice())

View file

@ -24,6 +24,7 @@ class EvenniaGameIndexClient(object):
Evennia Game Index. Since EGI is in the early goings, this isn't Evennia Game Index. Since EGI is in the early goings, this isn't
incredibly configurable as far as what is being sent. incredibly configurable as far as what is being sent.
""" """
def __init__(self, on_bad_request=None): def __init__(self, on_bad_request=None):
""" """
:param on_bad_request: Optional callable to trigger when a bad request :param on_bad_request: Optional callable to trigger when a bad request
@ -131,6 +132,7 @@ class SimpleResponseReceiver(protocol.Protocol):
""" """
Used for pulling the response body out of an HTTP response. Used for pulling the response body out of an HTTP response.
""" """
def __init__(self, status_code, d): def __init__(self, status_code, d):
self.status_code = status_code self.status_code = status_code
self.buf = '' self.buf = ''

View file

@ -108,6 +108,7 @@ class ExtendedRoom(DefaultRoom):
time. It also allows for "details", together with a slightly modified time. It also allows for "details", together with a slightly modified
look command. look command.
""" """
def at_object_creation(self): def at_object_creation(self):
"""Called when room is first created only.""" """Called when room is first created only."""
self.db.spring_desc = "" self.db.spring_desc = ""
@ -281,6 +282,7 @@ class CmdExtendedLook(default_cmds.CmdLook):
Observes your location, details at your location or objects in your vicinity. Observes your location, details at your location or objects in your vicinity.
""" """
def func(self): def func(self):
""" """
Handle the looking - add fallback to details. Handle the looking - add fallback to details.

View file

@ -54,6 +54,7 @@ _RE_GENDER_PRONOUN = re.compile(r'(?<!\|)\|(?!\|)[sSoOpPaA]')
# in-game command for setting the gender # in-game command for setting the gender
class SetGender(Command): class SetGender(Command):
""" """
Sets gender on yourself Sets gender on yourself
@ -72,7 +73,7 @@ class SetGender(Command):
""" """
caller = self.caller caller = self.caller
arg = self.args.strip().lower() arg = self.args.strip().lower()
if not arg in ("male", "female", "neutral", "ambiguous"): if arg not in ("male", "female", "neutral", "ambiguous"):
caller.msg("Usage: @gender male||female||neutral||ambiguous") caller.msg("Usage: @gender male||female||neutral||ambiguous")
return return
caller.db.gender = arg caller.db.gender = arg

View file

@ -4,6 +4,7 @@ Module containing the CallbackHandler for individual objects.
from collections import namedtuple from collections import namedtuple
class CallbackHandler(object): class CallbackHandler(object):
""" """
@ -200,5 +201,6 @@ class CallbackHandler(object):
return Callback(**callback) return Callback(**callback)
Callback = namedtuple("Callback", ("obj", "name", "number", "code", "author", Callback = namedtuple("Callback", ("obj", "name", "number", "code", "author",
"valid", "parameters", "created_on", "updated_by", "updated_on")) "valid", "parameters", "created_on", "updated_by", "updated_on"))

View file

@ -73,6 +73,7 @@ them and when. You can then accept a specific callback:
Use the /del switch to remove callbacks that should not be connected. Use the /del switch to remove callbacks that should not be connected.
""" """
class CmdCallback(COMMAND_DEFAULT_CLASS): class CmdCallback(COMMAND_DEFAULT_CLASS):
""" """
@ -141,7 +142,7 @@ class CmdCallback(COMMAND_DEFAULT_CLASS):
self.is_validator = validator self.is_validator = validator
self.autovalid = autovalid self.autovalid = autovalid
if self.handler is None: if self.handler is None:
caller.msg("The event handler is not running, can't " \ caller.msg("The event handler is not running, can't "
"access the event system.") "access the event system.")
return return
@ -170,7 +171,7 @@ class CmdCallback(COMMAND_DEFAULT_CLASS):
elif switch in ["tasks", "task"]: elif switch in ["tasks", "task"]:
self.list_tasks() self.list_tasks()
else: else:
caller.msg("Mutually exclusive or invalid switches were " \ caller.msg("Mutually exclusive or invalid switches were "
"used, cannot proceed.") "used, cannot proceed.")
def list_callbacks(self): def list_callbacks(self):
@ -277,8 +278,8 @@ class CmdCallback(COMMAND_DEFAULT_CLASS):
types = self.handler.get_events(obj) types = self.handler.get_events(obj)
# Check that the callback exists # Check that the callback exists
if not callback_name.startswith("chain_") and not callback_name in types: if not callback_name.startswith("chain_") and callback_name not in types:
self.msg("The callback name {} can't be found in {} of " \ self.msg("The callback name {} can't be found in {} of "
"typeclass {}.".format(callback_name, obj, type(obj))) "typeclass {}.".format(callback_name, obj, type(obj)))
return return
@ -313,7 +314,7 @@ class CmdCallback(COMMAND_DEFAULT_CLASS):
return return
# Check that the callback exists # Check that the callback exists
if not callback_name in callbacks: if callback_name not in callbacks:
self.msg("The callback name {} can't be found in {}.".format( self.msg("The callback name {} can't be found in {}.".format(
callback_name, obj)) callback_name, obj))
return return
@ -377,7 +378,7 @@ class CmdCallback(COMMAND_DEFAULT_CLASS):
return return
# Check that the callback exists # Check that the callback exists
if not callback_name in callbacks: if callback_name not in callbacks:
self.msg("The callback name {} can't be found in {}.".format( self.msg("The callback name {} can't be found in {}.".format(
callback_name, obj)) callback_name, obj))
return return
@ -388,7 +389,7 @@ class CmdCallback(COMMAND_DEFAULT_CLASS):
callback = callbacks[callback_name][0] callback = callbacks[callback_name][0]
else: else:
if not parameters: if not parameters:
self.msg("Which callback do you wish to delete? Specify " \ self.msg("Which callback do you wish to delete? Specify "
"a number.") "a number.")
self.list_callbacks() self.list_callbacks()
return return
@ -469,7 +470,7 @@ class CmdCallback(COMMAND_DEFAULT_CLASS):
return return
# Check that the callback exists # Check that the callback exists
if not callback_name in callbacks: if callback_name not in callbacks:
self.msg("The callback name {} can't be found in {}.".format( self.msg("The callback name {} can't be found in {}.".format(
callback_name, obj)) callback_name, obj))
return return
@ -520,9 +521,12 @@ class CmdCallback(COMMAND_DEFAULT_CLASS):
self.msg(unicode(table)) self.msg(unicode(table))
# Private functions to handle editing # Private functions to handle editing
def _ev_load(caller): def _ev_load(caller):
return caller.db._callback and caller.db._callback.get("code", "") or "" return caller.db._callback and caller.db._callback.get("code", "") or ""
def _ev_save(caller, buf): def _ev_save(caller, buf):
"""Save and add the callback.""" """Save and add the callback."""
lock = "perm({}) or perm(events_without_validation)".format( lock = "perm({}) or perm(events_without_validation)".format(
@ -530,7 +534,7 @@ def _ev_save(caller, buf):
autovalid = caller.locks.check_lockstring(caller, lock) autovalid = caller.locks.check_lockstring(caller, lock)
callback = caller.db._callback callback = caller.db._callback
handler = get_event_handler() handler = get_event_handler()
if not handler or not callback or not all(key in callback for key in \ if not handler or not callback or not all(key in callback for key in
("obj", "name", "number", "valid")): ("obj", "name", "number", "valid")):
caller.msg("Couldn't save this callback.") caller.msg("Couldn't save this callback.")
return False return False
@ -543,10 +547,11 @@ def _ev_save(caller, buf):
caller, valid=autovalid) caller, valid=autovalid)
return True return True
def _ev_quit(caller): def _ev_quit(caller):
callback = caller.db._callback callback = caller.db._callback
handler = get_event_handler() handler = get_event_handler()
if not handler or not callback or not all(key in callback for key in \ if not handler or not callback or not all(key in callback for key in
("obj", "name", "number", "valid")): ("obj", "name", "number", "valid")):
caller.msg("Couldn't save this callback.") caller.msg("Couldn't save this callback.")
return False return False

View file

@ -8,6 +8,7 @@ Eventfuncs are just Python functions that can be used inside of calllbacks.
from evennia import ObjectDB, ScriptDB from evennia import ObjectDB, ScriptDB
from evennia.contrib.ingame_python.utils import InterruptEvent from evennia.contrib.ingame_python.utils import InterruptEvent
def deny(): def deny():
""" """
Deny, that is stop, the callback here. Deny, that is stop, the callback here.
@ -22,6 +23,7 @@ def deny():
""" """
raise InterruptEvent raise InterruptEvent
def get(**kwargs): def get(**kwargs):
""" """
Return an object with the given search option or None if None is found. Return an object with the given search option or None if None is found.
@ -53,6 +55,7 @@ def get(**kwargs):
return object return object
def call_event(obj, event_name, seconds=0): def call_event(obj, event_name, seconds=0):
""" """
Call the specified event in X seconds. Call the specified event in X seconds.

View file

@ -21,6 +21,7 @@ from evennia.contrib.ingame_python.utils import get_next_wait, EVENTS, Interrupt
# Constants # Constants
RE_LINE_ERROR = re.compile(r'^ File "\<string\>", line (\d+)') RE_LINE_ERROR = re.compile(r'^ File "\<string\>", line (\d+)')
class EventHandler(DefaultScript): class EventHandler(DefaultScript):
""" """
@ -414,12 +415,12 @@ class EventHandler(DefaultScript):
# Errors should not pass silently # Errors should not pass silently
allowed = ("number", "parameters", "locals") allowed = ("number", "parameters", "locals")
if any(k for k in kwargs if k not in allowed): if any(k for k in kwargs if k not in allowed):
raise TypeError("Unknown keyword arguments were specified " \ raise TypeError("Unknown keyword arguments were specified "
"to call callbacks: {}".format(kwargs)) "to call callbacks: {}".format(kwargs))
event = self.get_events(obj).get(callback_name) event = self.get_events(obj).get(callback_name)
if locals is None and not event: if locals is None and not event:
logger.log_err("The callback {} for the object {} (typeclass " \ logger.log_err("The callback {} for the object {} (typeclass "
"{}) can't be found".format(callback_name, obj, type(obj))) "{}) can't be found".format(callback_name, obj, type(obj)))
return False return False
@ -430,7 +431,7 @@ class EventHandler(DefaultScript):
try: try:
locals[variable] = args[i] locals[variable] = args[i]
except IndexError: except IndexError:
logger.log_trace("callback {} of {} ({}): need variable " \ logger.log_trace("callback {} of {} ({}): need variable "
"{} in position {}".format(callback_name, obj, "{} in position {}".format(callback_name, obj,
type(obj), variable, i)) type(obj), variable, i))
return False return False
@ -482,7 +483,7 @@ class EventHandler(DefaultScript):
number = callback["number"] number = callback["number"]
obj = callback["obj"] obj = callback["obj"]
oid = obj.id oid = obj.id
logger.log_err("An error occurred during the callback {} of " \ logger.log_err("An error occurred during the callback {} of "
"{} (#{}), number {}\n{}".format(callback_name, obj, "{} (#{}), number {}\n{}".format(callback_name, obj,
oid, number + 1, "\n".join(trace))) oid, number + 1, "\n".join(trace)))
@ -655,7 +656,7 @@ def complete_task(task_id):
return return
if task_id not in script.db.tasks: if task_id not in script.db.tasks:
logger.log_err("The task #{} was scheduled, but it cannot be " \ logger.log_err("The task #{} was scheduled, but it cannot be "
"found".format(task_id)) "found".format(task_id))
return return

View file

@ -21,6 +21,7 @@ settings.EVENTS_CALENDAR = "standard"
# Constants # Constants
OLD_EVENTS = {} OLD_EVENTS = {}
class TestEventHandler(EvenniaTest): class TestEventHandler(EvenniaTest):
""" """

View file

@ -159,6 +159,7 @@ Variables you can use in this event:
character: the character connected to this event. character: the character connected to this event.
""" """
@register_events @register_events
class EventCharacter(DefaultCharacter): class EventCharacter(DefaultCharacter):
@ -489,6 +490,7 @@ Variables you can use in this event:
destination: the character's location after moving. destination: the character's location after moving.
""" """
@register_events @register_events
class EventExit(DefaultExit): class EventExit(DefaultExit):
@ -573,6 +575,7 @@ Variables you can use in this event:
object: the object connected to this event. object: the object connected to this event.
""" """
@register_events @register_events
class EventObject(DefaultObject): class EventObject(DefaultObject):
@ -621,6 +624,7 @@ class EventObject(DefaultObject):
super(EventObject, self).at_drop(dropper) super(EventObject, self).at_drop(dropper)
self.callbacks.call("drop", dropper, self) self.callbacks.call("drop", dropper, self)
# Room help # Room help
ROOM_CAN_DELETE = """ ROOM_CAN_DELETE = """
Can the room be deleted? Can the room be deleted?
@ -742,6 +746,7 @@ Variables you can use in this event:
room: the room connected to this event. room: the room connected to this event.
""" """
@register_events @register_events
class EventRoom(DefaultRoom): class EventRoom(DefaultRoom):

View file

@ -20,6 +20,7 @@ from evennia.contrib.custom_gametime import real_seconds_until as custom_rsu
# Temporary storage for events waiting for the script to be started # Temporary storage for events waiting for the script to be started
EVENTS = [] EVENTS = []
def get_event_handler(): def get_event_handler():
"""Return the event handler or None.""" """Return the event handler or None."""
try: try:
@ -30,6 +31,7 @@ def get_event_handler():
return script return script
def register_events(path_or_typeclass): def register_events(path_or_typeclass):
""" """
Register the events in this typeclass. Register the events in this typeclass.
@ -84,6 +86,8 @@ def register_events(path_or_typeclass):
return typeclass return typeclass
# Custom callbacks for specific event types # Custom callbacks for specific event types
def get_next_wait(format): def get_next_wait(format):
""" """
Get the length of time in seconds before format. Get the length of time in seconds before format.
@ -104,7 +108,7 @@ def get_next_wait(format):
""" """
calendar = getattr(settings, "EVENTS_CALENDAR", None) calendar = getattr(settings, "EVENTS_CALENDAR", None)
if calendar is None: if calendar is None:
logger.log_err("A time-related event has been set whereas " \ logger.log_err("A time-related event has been set whereas "
"the gametime calendar has not been set in the settings.") "the gametime calendar has not been set in the settings.")
return return
elif calendar == "standard": elif calendar == "standard":
@ -131,7 +135,7 @@ def get_next_wait(format):
break break
if not piece.isdigit(): if not piece.isdigit():
logger.log_trace("The time specified '{}' in {} isn't " \ logger.log_trace("The time specified '{}' in {} isn't "
"a valid number".format(piece, format)) "a valid number".format(piece, format))
return return
@ -154,6 +158,7 @@ def get_next_wait(format):
usual = gametime_to_realtime(**kwargs) usual = gametime_to_realtime(**kwargs)
return until, usual, details return until, usual, details
def time_event(obj, event_name, number, parameters): def time_event(obj, event_name, number, parameters):
""" """
Create a time-related event. Create a time-related event.
@ -173,6 +178,7 @@ def time_event(obj, event_name, number, parameters):
script.db.number = number script.db.number = number
script.ndb.usual = usual script.ndb.usual = usual
def keyword_event(callbacks, parameters): def keyword_event(callbacks, parameters):
""" """
Custom call for events with keywords (like push, or pull, or turn...). Custom call for events with keywords (like push, or pull, or turn...).
@ -201,6 +207,7 @@ def keyword_event(callbacks, parameters):
return to_call return to_call
def phrase_event(callbacks, parameters): def phrase_event(callbacks, parameters):
""" """
Custom call for events with keywords in sentences (like say or whisper). Custom call for events with keywords in sentences (like say or whisper).
@ -236,6 +243,7 @@ def phrase_event(callbacks, parameters):
return to_call return to_call
class InterruptEvent(RuntimeError): class InterruptEvent(RuntimeError):
""" """

View file

@ -22,6 +22,7 @@ _HEAD_CHAR = "|015-|n"
_SUB_HEAD_CHAR = "-" _SUB_HEAD_CHAR = "-"
_WIDTH = 78 _WIDTH = 78
class CmdMail(default_cmds.MuxCommand): class CmdMail(default_cmds.MuxCommand):
""" """
Commands that allow either IC or OOC communications Commands that allow either IC or OOC communications
@ -253,4 +254,3 @@ class CmdMail(default_cmds.MuxCommand):
self.caller.msg(_HEAD_CHAR * _WIDTH) self.caller.msg(_HEAD_CHAR * _WIDTH)
else: else:
self.caller.msg("There are no messages in your inbox.") self.caller.msg("There are no messages in your inbox.")

View file

@ -173,6 +173,7 @@ def example1_build_temple(x, y, **kwargs):
# This is generally mandatory. # This is generally mandatory.
return room return room
# Include your trigger characters and build functions in a legend dict. # Include your trigger characters and build functions in a legend dict.
EXAMPLE1_LEGEND = {("", ""): example1_build_forest, EXAMPLE1_LEGEND = {("", ""): example1_build_forest,
("", "n"): example1_build_mountains, ("", "n"): example1_build_mountains,
@ -261,6 +262,7 @@ def example2_build_horizontal_exit(x, y, **kwargs):
kwargs["caller"].msg("Connected: " + west_room.key + kwargs["caller"].msg("Connected: " + west_room.key +
" & " + east_room.key) " & " + east_room.key)
# Include your trigger characters and build functions in a legend dict. # Include your trigger characters and build functions in a legend dict.
EXAMPLE2_LEGEND = {("", ""): example2_build_forest, EXAMPLE2_LEGEND = {("", ""): example2_build_forest,
("|"): example2_build_verticle_exit, ("|"): example2_build_verticle_exit,
@ -370,6 +372,7 @@ def build_map(caller, game_map, legend, iterations=1, build_exits=True):
# access command # access command
class CmdMapBuilder(COMMAND_DEFAULT_CLASS): class CmdMapBuilder(COMMAND_DEFAULT_CLASS):
""" """
Build a map from a 2D ASCII map. Build a map from a 2D ASCII map.
@ -478,4 +481,3 @@ class CmdMapBuilder(COMMAND_DEFAULT_CLASS):
# Pass map and legend to the build function. # Pass map and legend to the build function.
build_map(caller, game_map, legend, iterations, build_exits) build_map(caller, game_map, legend, iterations, build_exits)

View file

@ -97,6 +97,7 @@ def _update_store(caller, key=None, desc=None, delete=False, swapkey=None):
# eveditor save/load/quit functions # eveditor save/load/quit functions
def _save_editor(caller, buffer): def _save_editor(caller, buffer):
"Called when the editor saves its contents" "Called when the editor saves its contents"
key = caller.db._multidesc_editkey key = caller.db._multidesc_editkey
@ -104,6 +105,7 @@ def _save_editor(caller, buffer):
caller.msg("Saved description to key '%s'." % key) caller.msg("Saved description to key '%s'." % key)
return True return True
def _load_editor(caller): def _load_editor(caller):
"Called when the editor loads contents" "Called when the editor loads contents"
key = caller.db._multidesc_editkey key = caller.db._multidesc_editkey
@ -112,6 +114,7 @@ def _load_editor(caller):
return caller.db.multidesc[match[0]][1] return caller.db.multidesc[match[0]][1]
return "" return ""
def _quit_editor(caller): def _quit_editor(caller):
"Called when the editor quits" "Called when the editor quits"
del caller.db._multidesc_editkey del caller.db._multidesc_editkey
@ -161,7 +164,7 @@ class CmdMultiDesc(default_cmds.MuxCommand):
# list all stored descriptions, either in full or cropped. # list all stored descriptions, either in full or cropped.
# Note that we list starting from 1, not from 0. # Note that we list starting from 1, not from 0.
_update_store(caller) _update_store(caller)
do_crop = not "full" in switches do_crop = "full" not in switches
if do_crop: if do_crop:
outtext = ["|w%s:|n %s" % (key, crop(desc)) outtext = ["|w%s:|n %s" % (key, crop(desc))
for key, desc in caller.db.multidesc] for key, desc in caller.db.multidesc]
@ -249,6 +252,6 @@ class CmdMultiDesc(default_cmds.MuxCommand):
else: else:
caller.msg("|wCurrent desc:|n\n%s" % caller.db.desc) caller.msg("|wCurrent desc:|n\n%s" % caller.db.desc)
except DescValidateError, err: except DescValidateError as err:
# This is triggered by _key_to_index # This is triggered by _key_to_index
caller.msg(err) caller.msg(err)

View file

@ -57,6 +57,7 @@ import time
from evennia import DefaultScript, ScriptDB from evennia import DefaultScript, ScriptDB
from evennia.utils.create import create_script from evennia.utils.create import create_script
class RejectedRegex(RuntimeError): class RejectedRegex(RuntimeError):
"""The provided regular expression has been rejected. """The provided regular expression has been rejected.

View file

@ -148,13 +148,13 @@ class LanguageHandler(DefaultScript):
don't know the language well enough). don't know the language well enough).
""" """
def at_script_creation(self): def at_script_creation(self):
"Called when script is first started" "Called when script is first started"
self.key = "language_handler" self.key = "language_handler"
self.persistent = True self.persistent = True
self.db.language_storage = {} self.db.language_storage = {}
def add(self, key="default", phonemes=_PHONEMES, def add(self, key="default", phonemes=_PHONEMES,
grammar=_GRAMMAR, word_length_variance=0, noun_prefix="", grammar=_GRAMMAR, word_length_variance=0, noun_prefix="",
noun_postfix="", vowels=_VOWELS, manual_translations=None, noun_postfix="", vowels=_VOWELS, manual_translations=None,
@ -347,6 +347,8 @@ class LanguageHandler(DefaultScript):
# Language access functions # Language access functions
_LANGUAGE_HANDLER = None _LANGUAGE_HANDLER = None
def obfuscate_language(text, level=0.0, language="default"): def obfuscate_language(text, level=0.0, language="default"):
""" """
Main access method for the language parser. Main access method for the language parser.
@ -412,7 +414,6 @@ def available_languages():
return list(_LANGUAGE_HANDLER.attributes.get("language_storage", {})) return list(_LANGUAGE_HANDLER.attributes.get("language_storage", {}))
#------------------------------------------------------------ #------------------------------------------------------------
# #
# Whisper obscuration # Whisper obscuration
@ -427,6 +428,7 @@ def available_languages():
# #
#------------------------------------------------------------ #------------------------------------------------------------
_RE_WHISPER_OBSCURE = [ _RE_WHISPER_OBSCURE = [
re.compile(r"^$", _RE_FLAGS), # This is a Test! #0 full whisper re.compile(r"^$", _RE_FLAGS), # This is a Test! #0 full whisper
re.compile(r"[ae]", _RE_FLAGS), # This -s - Test! #1 add uy re.compile(r"[ae]", _RE_FLAGS), # This -s - Test! #1 add uy
@ -460,4 +462,3 @@ def obfuscate_whisper(whisper, level=0.0):
level = min(max(0.0, level), 1.0) level = min(max(0.0, level), 1.0)
olevel = int(13.0 * level) olevel = int(13.0 * level)
return _RE_WHISPER_OBSCURE[olevel].sub('...' if olevel == 13.0 else '-', whisper) return _RE_WHISPER_OBSCURE[olevel].sub('...' if olevel == 13.0 else '-', whisper)

View file

@ -168,6 +168,7 @@ _RE_LANGUAGE = re.compile(r"(?:\((\w+)\))*(\".+?\")")
# 2) for every person seeing the emote, parse this # 2) for every person seeing the emote, parse this
# intermediary form into the one valid for that char. # intermediary form into the one valid for that char.
class EmoteError(Exception): class EmoteError(Exception):
pass pass
@ -240,6 +241,7 @@ def ordered_permutation_regex(sentence):
regex = r"|".join(sorted(set(solution), key=len, reverse=True)) regex = r"|".join(sorted(set(solution), key=len, reverse=True))
return regex return regex
def regex_tuple_from_key_alias(obj): def regex_tuple_from_key_alias(obj):
""" """
This will build a regex tuple for any object, not just from those This will build a regex tuple for any object, not just from those
@ -546,6 +548,7 @@ def send_emote(sender, receivers, emote, anonymous_add="first"):
# Handlers for sdesc and recog # Handlers for sdesc and recog
#------------------------------------------------------------ #------------------------------------------------------------
class SdescHandler(object): class SdescHandler(object):
""" """
This Handler wraps all operations with sdescs. We This Handler wraps all operations with sdescs. We
@ -559,6 +562,7 @@ class SdescHandler(object):
_regex - an empty dictionary _regex - an empty dictionary
""" """
def __init__(self, obj): def __init__(self, obj):
""" """
Initialize the handler Initialize the handler
@ -656,6 +660,7 @@ class RecogHandler(object):
_recog_obj2regex _recog_obj2regex
""" """
def __init__(self, obj): def __init__(self, obj):
""" """
Initialize the handler Initialize the handler
@ -785,6 +790,7 @@ class RecogHandler(object):
class RPCommand(Command): class RPCommand(Command):
"simple parent" "simple parent"
def parse(self): def parse(self):
"strip extra whitespace" "strip extra whitespace"
self.args = self.args.strip() self.args = self.args.strip()
@ -843,7 +849,6 @@ class CmdSay(RPCommand): # replaces standard say
locks = "cmd:all()" locks = "cmd:all()"
def func(self): def func(self):
"Run the say command" "Run the say command"
caller = self.caller caller = self.caller
@ -884,7 +889,7 @@ class CmdSdesc(RPCommand): # set/look at own sdesc
sdesc = _RE_CHAREND.sub("", self.args) sdesc = _RE_CHAREND.sub("", self.args)
try: try:
sdesc = caller.sdesc.add(sdesc) sdesc = caller.sdesc.add(sdesc)
except SdescError, err: except SdescError as err:
caller.msg(err) caller.msg(err)
return return
caller.msg("%s's sdesc was set to '%s'." % (caller.key, sdesc)) caller.msg("%s's sdesc was set to '%s'." % (caller.key, sdesc))
@ -1053,7 +1058,7 @@ class CmdRecog(RPCommand): # assign personal alias to object in room
sdesc = obj.sdesc.get() if hasattr(obj, "sdesc") else obj.key sdesc = obj.sdesc.get() if hasattr(obj, "sdesc") else obj.key
try: try:
alias = caller.recog.add(obj, alias) alias = caller.recog.add(obj, alias)
except RecogError, err: except RecogError as err:
caller.msg(err) caller.msg(err)
return return
caller.msg("%s will now remember |w%s|n as |w%s|n." % (caller.key, sdesc, alias)) caller.msg("%s will now remember |w%s|n as |w%s|n." % (caller.key, sdesc, alias))
@ -1110,6 +1115,7 @@ class RPSystemCmdSet(CmdSet):
""" """
Mix-in for adding rp-commands to default cmdset. Mix-in for adding rp-commands to default cmdset.
""" """
def at_cmdset_creation(self): def at_cmdset_creation(self):
self.add(CmdEmote()) self.add(CmdEmote())
self.add(CmdSay()) self.add(CmdSay())
@ -1258,7 +1264,8 @@ class ContribRPObject(DefaultObject):
# the sdesc-related substitution # the sdesc-related substitution
is_builder = self.locks.check_lockstring(self, "perm(Builder)") is_builder = self.locks.check_lockstring(self, "perm(Builder)")
use_dbref = is_builder if use_dbref is None else use_dbref use_dbref = is_builder if use_dbref is None else use_dbref
search_obj = lambda string: ObjectDB.objects.object_search(string,
def search_obj(string): return ObjectDB.objects.object_search(string,
attribute_name=attribute_name, attribute_name=attribute_name,
typeclass=typeclass, typeclass=typeclass,
candidates=candidates, candidates=candidates,

View file

@ -40,6 +40,7 @@ class SimpleDoor(DefaultExit):
sides using `exitname.setlock("traverse:false())` sides using `exitname.setlock("traverse:false())`
""" """
def at_object_creation(self): def at_object_creation(self):
""" """
Called the very first time the door is created. Called the very first time the door is created.
@ -165,4 +166,3 @@ class CmdOpenCloseDoor(default_cmds.MuxCommand):
else: else:
door.setlock("traverse:false()") door.setlock("traverse:false()")
self.caller.msg("You close %s." % door.key) self.caller.msg("You close %s." % door.key)

View file

@ -42,10 +42,12 @@ MOVE_DELAY = {"stroll": 6,
"run": 2, "run": 2,
"sprint": 1} "sprint": 1}
class SlowExit(DefaultExit): class SlowExit(DefaultExit):
""" """
This overloads the way moving happens. This overloads the way moving happens.
""" """
def at_traverse(self, traversing_object, target_location): def at_traverse(self, traversing_object, target_location):
""" """
Implements the actual traversal, using utils.delay to delay the move_to. Implements the actual traversal, using utils.delay to delay the move_to.
@ -87,6 +89,7 @@ SPEED_DESCS = {"stroll": "strolling",
"run": "running", "run": "running",
"sprint": "sprinting"} "sprint": "sprinting"}
class CmdSetSpeed(Command): class CmdSetSpeed(Command):
""" """
set your movement speed set your movement speed

View file

@ -48,6 +48,7 @@ def info1(caller):
return text, options return text, options
def info2(caller): def info2(caller):
text = "'My name is not really important ... I'm just an NPC after all.'" text = "'My name is not really important ... I'm just an NPC after all.'"
@ -67,7 +68,6 @@ def info3(caller):
{"desc": "Wait, why don't you tell me your name first?", {"desc": "Wait, why don't you tell me your name first?",
"goto": "info2"}) "goto": "info2"})
return text, options return text, options
@ -82,6 +82,7 @@ def END(caller):
# The talk command (sits on the NPC) # The talk command (sits on the NPC)
# #
class CmdTalk(default_cmds.MuxCommand): class CmdTalk(default_cmds.MuxCommand):
""" """
Talks to an npc Talks to an npc
@ -112,6 +113,7 @@ class CmdTalk(default_cmds.MuxCommand):
class TalkingCmdSet(CmdSet): class TalkingCmdSet(CmdSet):
"Stores the talk command." "Stores the talk command."
key = "talkingcmdset" key = "talkingcmdset"
def at_cmdset_creation(self): def at_cmdset_creation(self):
"populates the cmdset" "populates the cmdset"
self.add(CmdTalk()) self.add(CmdTalk())
@ -122,6 +124,7 @@ class TalkingNPC(DefaultObject):
This implements a simple Object using the talk command and using This implements a simple Object using the talk command and using
the conversation defined above. the conversation defined above.
""" """
def at_object_creation(self): def at_object_creation(self):
"This is called when object is first created." "This is called when object is first created."
self.db.desc = "This is a talkative NPC." self.db.desc = "This is a talkative NPC."

View file

@ -64,6 +64,7 @@ class TestLanguage(EvenniaTest):
# Testing of emoting / sdesc / recog system # Testing of emoting / sdesc / recog system
from evennia import create_object from evennia import create_object
from evennia.contrib import rpsystem from evennia.contrib import rpsystem
@ -176,6 +177,7 @@ from evennia.contrib import extended_room
from evennia import gametime from evennia import gametime
from evennia.objects.objects import DefaultRoom from evennia.objects.objects import DefaultRoom
class ForceUTCDatetime(datetime.datetime): class ForceUTCDatetime(datetime.datetime):
"""Force UTC datetime.""" """Force UTC datetime."""
@ -185,6 +187,7 @@ class ForceUTCDatetime(datetime.datetime):
"""Force fromtimestamp to run with naive datetimes.""" """Force fromtimestamp to run with naive datetimes."""
return datetime.datetime.utcfromtimestamp(timestamp) return datetime.datetime.utcfromtimestamp(timestamp)
@patch('evennia.contrib.extended_room.datetime.datetime', ForceUTCDatetime) @patch('evennia.contrib.extended_room.datetime.datetime', ForceUTCDatetime)
class TestExtendedRoom(CommandTest): class TestExtendedRoom(CommandTest):
room_typeclass = extended_room.ExtendedRoom room_typeclass = extended_room.ExtendedRoom
@ -237,6 +240,7 @@ class TestExtendedRoom(CommandTest):
from evennia.contrib import barter from evennia.contrib import barter
class TestBarter(CommandTest): class TestBarter(CommandTest):
def setUp(self): def setUp(self):
@ -319,9 +323,11 @@ class TestBarter(CommandTest):
# Test wilderness # Test wilderness
from evennia.contrib import wilderness from evennia.contrib import wilderness
from evennia import DefaultCharacter from evennia import DefaultCharacter
class TestWilderness(EvenniaTest): class TestWilderness(EvenniaTest):
def setUp(self): def setUp(self):
@ -438,9 +444,11 @@ class TestWilderness(EvenniaTest):
new_loc = wilderness.get_new_coordinates(loc, direction) new_loc = wilderness.get_new_coordinates(loc, direction)
self.assertEquals(new_loc, correct_loc, direction) self.assertEquals(new_loc, correct_loc, direction)
# Testing chargen contrib # Testing chargen contrib
from evennia.contrib import chargen from evennia.contrib import chargen
class TestChargen(CommandTest): class TestChargen(CommandTest):
def test_ooclook(self): def test_ooclook(self):
@ -454,10 +462,12 @@ class TestChargen(CommandTest):
self.call(chargen.CmdOOCLook(), "", "You, TestAccount, are an OOC ghost without form.", caller=self.account) self.call(chargen.CmdOOCLook(), "", "You, TestAccount, are an OOC ghost without form.", caller=self.account)
self.call(chargen.CmdOOCLook(), "testchar", "testchar(", caller=self.account) self.call(chargen.CmdOOCLook(), "testchar", "testchar(", caller=self.account)
# Testing clothing contrib # Testing clothing contrib
from evennia.contrib import clothing from evennia.contrib import clothing
from evennia.objects.objects import DefaultRoom from evennia.objects.objects import DefaultRoom
class TestClothingCmd(CommandTest): class TestClothingCmd(CommandTest):
def test_clothingcommands(self): def test_clothingcommands(self):
@ -501,6 +511,7 @@ class TestClothingCmd(CommandTest):
# Test inventory command. # Test inventory command.
self.call(clothing.CmdInventory(), "", "You are not carrying or wearing anything.", caller=wearer) self.call(clothing.CmdInventory(), "", "You are not carrying or wearing anything.", caller=wearer)
class TestClothingFunc(EvenniaTest): class TestClothingFunc(EvenniaTest):
def test_clothingfunctions(self): def test_clothingfunctions(self):
@ -543,36 +554,44 @@ class TestClothingFunc(EvenniaTest):
# Testing custom_gametime # Testing custom_gametime
from evennia.contrib import custom_gametime from evennia.contrib import custom_gametime
def _testcallback(): def _testcallback():
pass pass
class TestCustomGameTime(EvenniaTest): class TestCustomGameTime(EvenniaTest):
def setUp(self): def setUp(self):
super(TestCustomGameTime, self).setUp() super(TestCustomGameTime, self).setUp()
gametime.gametime = Mock(return_value=2975000898.46) # does not seem to work gametime.gametime = Mock(return_value=2975000898.46) # does not seem to work
def tearDown(self): def tearDown(self):
if hasattr(self, "timescript"): if hasattr(self, "timescript"):
self.timescript.stop() self.timescript.stop()
def test_time_to_tuple(self): def test_time_to_tuple(self):
self.assertEqual(custom_gametime.time_to_tuple(10000, 34, 2, 4, 6, 1), (294, 2, 0, 0, 0, 0)) self.assertEqual(custom_gametime.time_to_tuple(10000, 34, 2, 4, 6, 1), (294, 2, 0, 0, 0, 0))
self.assertEqual(custom_gametime.time_to_tuple(10000, 3, 3, 4), (3333, 0, 0, 1)) self.assertEqual(custom_gametime.time_to_tuple(10000, 3, 3, 4), (3333, 0, 0, 1))
self.assertEqual(custom_gametime.time_to_tuple(100000, 239, 24, 3), (418, 4, 0, 2)) self.assertEqual(custom_gametime.time_to_tuple(100000, 239, 24, 3), (418, 4, 0, 2))
def test_gametime_to_realtime(self): def test_gametime_to_realtime(self):
self.assertEqual(custom_gametime.gametime_to_realtime(days=2, mins=4), 86520.0) self.assertEqual(custom_gametime.gametime_to_realtime(days=2, mins=4), 86520.0)
self.assertEqual(custom_gametime.gametime_to_realtime(format=True, days=2), (0, 0, 0, 1, 0, 0, 0)) self.assertEqual(custom_gametime.gametime_to_realtime(format=True, days=2), (0, 0, 0, 1, 0, 0, 0))
def test_realtime_to_gametime(self): def test_realtime_to_gametime(self):
self.assertEqual(custom_gametime.realtime_to_gametime(days=2, mins=34), 349680.0) self.assertEqual(custom_gametime.realtime_to_gametime(days=2, mins=34), 349680.0)
self.assertEqual(custom_gametime.realtime_to_gametime(days=2, mins=34, format=True), (0, 0, 0, 4, 1, 8, 0)) self.assertEqual(custom_gametime.realtime_to_gametime(days=2, mins=34, format=True), (0, 0, 0, 4, 1, 8, 0))
self.assertEqual(custom_gametime.realtime_to_gametime(format=True, days=2, mins=4), (0, 0, 0, 4, 0, 8, 0)) self.assertEqual(custom_gametime.realtime_to_gametime(format=True, days=2, mins=4), (0, 0, 0, 4, 0, 8, 0))
def test_custom_gametime(self): def test_custom_gametime(self):
self.assertEqual(custom_gametime.custom_gametime(), (102, 5, 2, 6, 21, 8, 18)) self.assertEqual(custom_gametime.custom_gametime(), (102, 5, 2, 6, 21, 8, 18))
self.assertEqual(custom_gametime.custom_gametime(absolute=True), (102, 5, 2, 6, 21, 8, 18)) self.assertEqual(custom_gametime.custom_gametime(absolute=True), (102, 5, 2, 6, 21, 8, 18))
def test_real_seconds_until(self): def test_real_seconds_until(self):
self.assertEqual(custom_gametime.real_seconds_until(year=2300, month=11, day=6), 31911667199.77) self.assertEqual(custom_gametime.real_seconds_until(year=2300, month=11, day=6), 31911667199.77)
def test_schedule(self): def test_schedule(self):
self.timescript = custom_gametime.schedule(_testcallback, repeat=True, min=5, sec=0) self.timescript = custom_gametime.schedule(_testcallback, repeat=True, min=5, sec=0)
self.assertEqual(self.timescript.interval, 1700.7699999809265) self.assertEqual(self.timescript.interval, 1700.7699999809265)
@ -588,6 +607,7 @@ class TestDice(CommandTest):
self.assertEqual(dice.roll_dice(6, 6, modifier=('+', 4)), mocked_randint() * 6 + 4) self.assertEqual(dice.roll_dice(6, 6, modifier=('+', 4)), mocked_randint() * 6 + 4)
self.assertEqual(dice.roll_dice(6, 6, conditional=('<', 35)), True) self.assertEqual(dice.roll_dice(6, 6, conditional=('<', 35)), True)
self.assertEqual(dice.roll_dice(6, 6, conditional=('>', 33)), False) self.assertEqual(dice.roll_dice(6, 6, conditional=('>', 33)), False)
def test_cmddice(self, mocked_randint): def test_cmddice(self, mocked_randint):
from evennia.contrib import dice from evennia.contrib import dice
self.call(dice.CmdDice(), "3d6 + 4", "You roll 3d6 + 4.| Roll(s): 5, 5 and 5. Total result is 19.") self.call(dice.CmdDice(), "3d6 + 4", "You roll 3d6 + 4.| Roll(s): 5, 5 and 5. Total result is 19.")
@ -596,29 +616,37 @@ class TestDice(CommandTest):
# Test email-login # Test email-login
from evennia.contrib import email_login from evennia.contrib import email_login
class TestEmailLogin(CommandTest): class TestEmailLogin(CommandTest):
def test_connect(self): def test_connect(self):
self.call(email_login.CmdUnconnectedConnect(), "mytest@test.com test", "The email 'mytest@test.com' does not match any accounts.") self.call(email_login.CmdUnconnectedConnect(), "mytest@test.com test", "The email 'mytest@test.com' does not match any accounts.")
self.call(email_login.CmdUnconnectedCreate(), '"mytest" mytest@test.com test11111', "A new account 'mytest' was created. Welcome!") self.call(email_login.CmdUnconnectedCreate(), '"mytest" mytest@test.com test11111', "A new account 'mytest' was created. Welcome!")
self.call(email_login.CmdUnconnectedConnect(), "mytest@test.com test11111", "", caller=self.account.sessions.get()[0]) self.call(email_login.CmdUnconnectedConnect(), "mytest@test.com test11111", "", caller=self.account.sessions.get()[0])
def test_quit(self): def test_quit(self):
self.call(email_login.CmdUnconnectedQuit(), "", "", caller=self.account.sessions.get()[0]) self.call(email_login.CmdUnconnectedQuit(), "", "", caller=self.account.sessions.get()[0])
def test_unconnectedlook(self): def test_unconnectedlook(self):
self.call(email_login.CmdUnconnectedLook(), "", "==========") self.call(email_login.CmdUnconnectedLook(), "", "==========")
def test_unconnectedhelp(self): def test_unconnectedhelp(self):
self.call(email_login.CmdUnconnectedHelp(), "", "You are not yet logged into the game.") self.call(email_login.CmdUnconnectedHelp(), "", "You are not yet logged into the game.")
# test gendersub contrib # test gendersub contrib
from evennia.contrib import gendersub from evennia.contrib import gendersub
class TestGenderSub(CommandTest): class TestGenderSub(CommandTest):
def test_setgender(self): def test_setgender(self):
self.call(gendersub.SetGender(), "male", "Your gender was set to male.") self.call(gendersub.SetGender(), "male", "Your gender was set to male.")
self.call(gendersub.SetGender(), "ambiguous", "Your gender was set to ambiguous.") self.call(gendersub.SetGender(), "ambiguous", "Your gender was set to ambiguous.")
self.call(gendersub.SetGender(), "Foo", "Usage: @gender") self.call(gendersub.SetGender(), "Foo", "Usage: @gender")
def test_gendercharacter(self): def test_gendercharacter(self):
char = create_object(gendersub.GenderCharacter, key="Gendered", location=self.room1) char = create_object(gendersub.GenderCharacter, key="Gendered", location=self.room1)
txt = "Test |p gender" txt = "Test |p gender"
@ -626,8 +654,10 @@ class TestGenderSub(CommandTest):
# test mail contrib # test mail contrib
from evennia.contrib import mail from evennia.contrib import mail
class TestMail(CommandTest): class TestMail(CommandTest):
def test_mail(self): def test_mail(self):
self.call(mail.CmdMail(), "2", "'2' is not a valid mail id.", caller=self.account) self.call(mail.CmdMail(), "2", "'2' is not a valid mail id.", caller=self.account)
@ -646,8 +676,10 @@ class TestMail(CommandTest):
# test map builder contrib # test map builder contrib
from evennia.contrib import mapbuilder from evennia.contrib import mapbuilder
class TestMapBuilder(CommandTest): class TestMapBuilder(CommandTest):
def test_cmdmapbuilder(self): def test_cmdmapbuilder(self):
self.call(mapbuilder.CmdMapBuilder(), self.call(mapbuilder.CmdMapBuilder(),
@ -674,6 +706,7 @@ class TestMapBuilder(CommandTest):
from evennia.contrib import menu_login from evennia.contrib import menu_login
class TestMenuLogin(CommandTest): class TestMenuLogin(CommandTest):
def test_cmdunloggedlook(self): def test_cmdunloggedlook(self):
self.call(menu_login.CmdUnloggedinLook(), "", "======") self.call(menu_login.CmdUnloggedinLook(), "", "======")
@ -683,6 +716,7 @@ class TestMenuLogin(CommandTest):
from evennia.contrib import multidescer from evennia.contrib import multidescer
class TestMultidescer(CommandTest): class TestMultidescer(CommandTest):
def test_cmdmultidesc(self): def test_cmdmultidesc(self):
self.call(multidescer.CmdMultiDesc(), "/list", "Stored descs:\ncaller:") self.call(multidescer.CmdMultiDesc(), "/list", "Stored descs:\ncaller:")
@ -698,8 +732,10 @@ class TestMultidescer(CommandTest):
# test simpledoor contrib # test simpledoor contrib
from evennia.contrib import simpledoor from evennia.contrib import simpledoor
class TestSimpleDoor(CommandTest): class TestSimpleDoor(CommandTest):
def test_cmdopen(self): def test_cmdopen(self):
self.call(simpledoor.CmdOpen(), "newdoor;door:contrib.simpledoor.SimpleDoor,backdoor;door = Room2", self.call(simpledoor.CmdOpen(), "newdoor;door:contrib.simpledoor.SimpleDoor,backdoor;door = Room2",
@ -712,9 +748,11 @@ class TestSimpleDoor(CommandTest):
# test slow_exit contrib # test slow_exit contrib
from evennia.contrib import slow_exit from evennia.contrib import slow_exit
slow_exit.MOVE_DELAY = {"stroll": 0, "walk": 0, "run": 0, "sprint": 0} slow_exit.MOVE_DELAY = {"stroll": 0, "walk": 0, "run": 0, "sprint": 0}
class TestSlowExit(CommandTest): class TestSlowExit(CommandTest):
def test_exit(self): def test_exit(self):
exi = create_object(slow_exit.SlowExit, key="slowexit", location=self.room1, destination=self.room2) exi = create_object(slow_exit.SlowExit, key="slowexit", location=self.room1, destination=self.room2)
@ -724,8 +762,10 @@ class TestSlowExit(CommandTest):
# test talking npc contrib # test talking npc contrib
from evennia.contrib import talking_npc from evennia.contrib import talking_npc
class TestTalkingNPC(CommandTest): class TestTalkingNPC(CommandTest):
def test_talkingnpc(self): def test_talkingnpc(self):
npc = create_object(talking_npc.TalkingNPC, key="npctalker", location=self.room1) npc = create_object(talking_npc.TalkingNPC, key="npctalker", location=self.room1)
@ -739,6 +779,7 @@ class TestTalkingNPC(CommandTest):
from evennia.contrib.tutorial_world import mob from evennia.contrib.tutorial_world import mob
class TestTutorialWorldMob(EvenniaTest): class TestTutorialWorldMob(EvenniaTest):
def test_mob(self): def test_mob(self):
mobobj = create_object(mob.Mob, key="mob") mobobj = create_object(mob.Mob, key="mob")
@ -752,24 +793,30 @@ class TestTutorialWorldMob(EvenniaTest):
# test tutorial_world/objects # test tutorial_world/objects
from evennia.contrib.tutorial_world import objects as tutobjects from evennia.contrib.tutorial_world import objects as tutobjects
class TestTutorialWorldObjects(CommandTest): class TestTutorialWorldObjects(CommandTest):
def test_tutorialobj(self): def test_tutorialobj(self):
obj1 = create_object(tutobjects.TutorialObject, key="tutobj") obj1 = create_object(tutobjects.TutorialObject, key="tutobj")
obj1.reset() obj1.reset()
self.assertEqual(obj1.location, obj1.home) self.assertEqual(obj1.location, obj1.home)
def test_readable(self): def test_readable(self):
readable = create_object(tutobjects.Readable, key="book", location=self.room1) readable = create_object(tutobjects.Readable, key="book", location=self.room1)
readable.db.readable_text = "Text to read" readable.db.readable_text = "Text to read"
self.call(tutobjects.CmdRead(), "book", "You read book:\n Text to read", obj=readable) self.call(tutobjects.CmdRead(), "book", "You read book:\n Text to read", obj=readable)
def test_climbable(self): def test_climbable(self):
climbable = create_object(tutobjects.Climbable, key="tree", location=self.room1) climbable = create_object(tutobjects.Climbable, key="tree", location=self.room1)
self.call(tutobjects.CmdClimb(), "tree", "You climb tree. Having looked around, you climb down again.", obj=climbable) self.call(tutobjects.CmdClimb(), "tree", "You climb tree. Having looked around, you climb down again.", obj=climbable)
self.assertEqual(self.char1.tags.get("tutorial_climbed_tree", category="tutorial_world"), "tutorial_climbed_tree") self.assertEqual(self.char1.tags.get("tutorial_climbed_tree", category="tutorial_world"), "tutorial_climbed_tree")
def test_obelisk(self): def test_obelisk(self):
obelisk = create_object(tutobjects.Obelisk, key="obelisk", location=self.room1) obelisk = create_object(tutobjects.Obelisk, key="obelisk", location=self.room1)
self.assertEqual(obelisk.return_appearance(self.char1).startswith("|cobelisk("), True) self.assertEqual(obelisk.return_appearance(self.char1).startswith("|cobelisk("), True)
def test_lightsource(self): def test_lightsource(self):
light = create_object(tutobjects.LightSource, key="torch", location=self.room1) light = create_object(tutobjects.LightSource, key="torch", location=self.room1)
self.call(tutobjects.CmdLight(), "", "You light torch.", obj=light) self.call(tutobjects.CmdLight(), "", "You light torch.", obj=light)
@ -777,6 +824,7 @@ class TestTutorialWorldObjects(CommandTest):
if hasattr(light, "deferred"): if hasattr(light, "deferred"):
light.deferred.cancel() light.deferred.cancel()
self.assertFalse(light.pk) self.assertFalse(light.pk)
def test_crumblingwall(self): def test_crumblingwall(self):
wall = create_object(tutobjects.CrumblingWall, key="wall", location=self.room1) wall = create_object(tutobjects.CrumblingWall, key="wall", location=self.room1)
self.assertFalse(wall.db.button_exposed) self.assertFalse(wall.db.button_exposed)
@ -798,18 +846,22 @@ class TestTutorialWorldObjects(CommandTest):
if hasattr(wall, "deferred"): if hasattr(wall, "deferred"):
wall.deferred.cancel() wall.deferred.cancel()
wall.delete() wall.delete()
def test_weapon(self): def test_weapon(self):
weapon = create_object(tutobjects.Weapon, key="sword", location=self.char1) weapon = create_object(tutobjects.Weapon, key="sword", location=self.char1)
self.call(tutobjects.CmdAttack(), "Char", "You stab with sword.", obj=weapon, cmdstring="stab") self.call(tutobjects.CmdAttack(), "Char", "You stab with sword.", obj=weapon, cmdstring="stab")
self.call(tutobjects.CmdAttack(), "Char", "You slash with sword.", obj=weapon, cmdstring="slash") self.call(tutobjects.CmdAttack(), "Char", "You slash with sword.", obj=weapon, cmdstring="slash")
def test_weaponrack(self): def test_weaponrack(self):
rack = create_object(tutobjects.WeaponRack, key="rack", location=self.room1) rack = create_object(tutobjects.WeaponRack, key="rack", location=self.room1)
rack.db.available_weapons = ["sword"] rack.db.available_weapons = ["sword"]
self.call(tutobjects.CmdGetWeapon(), "", "You find Rusty sword.", obj=rack) self.call(tutobjects.CmdGetWeapon(), "", "You find Rusty sword.", obj=rack)
# test tutorial_world/ # test tutorial_world/
from evennia.contrib.tutorial_world import rooms as tutrooms from evennia.contrib.tutorial_world import rooms as tutrooms
class TestTutorialWorldRooms(CommandTest): class TestTutorialWorldRooms(CommandTest):
def test_cmdtutorial(self): def test_cmdtutorial(self):
room = create_object(tutrooms.TutorialRoom, key="tutroom") room = create_object(tutrooms.TutorialRoom, key="tutroom")
@ -820,14 +872,17 @@ class TestTutorialWorldRooms(CommandTest):
self.call(tutrooms.CmdTutorialLook(), "detail", "A detail", obj=room) self.call(tutrooms.CmdTutorialLook(), "detail", "A detail", obj=room)
self.call(tutrooms.CmdTutorialLook(), "foo", "A detail", obj=room) self.call(tutrooms.CmdTutorialLook(), "foo", "A detail", obj=room)
room.delete() room.delete()
def test_weatherroom(self): def test_weatherroom(self):
room = create_object(tutrooms.WeatherRoom, key="weatherroom") room = create_object(tutrooms.WeatherRoom, key="weatherroom")
room.update_weather() room.update_weather()
tutrooms.TICKER_HANDLER.remove(interval=room.db.interval, callback=room.update_weather, idstring="tutorial") tutrooms.TICKER_HANDLER.remove(interval=room.db.interval, callback=room.update_weather, idstring="tutorial")
room.delete() room.delete()
def test_introroom(self): def test_introroom(self):
room = create_object(tutrooms.IntroRoom, key="introroom") room = create_object(tutrooms.IntroRoom, key="introroom")
room.at_object_receive(self.char1, self.room1) room.at_object_receive(self.char1, self.room1)
def test_bridgeroom(self): def test_bridgeroom(self):
room = create_object(tutrooms.BridgeRoom, key="bridgeroom") room = create_object(tutrooms.BridgeRoom, key="bridgeroom")
room.update_weather() room.update_weather()
@ -837,19 +892,24 @@ class TestTutorialWorldRooms(CommandTest):
room.at_object_leave(self.char1, self.room1) room.at_object_leave(self.char1, self.room1)
tutrooms.TICKER_HANDLER.remove(interval=room.db.interval, callback=room.update_weather, idstring="tutorial") tutrooms.TICKER_HANDLER.remove(interval=room.db.interval, callback=room.update_weather, idstring="tutorial")
room.delete() room.delete()
def test_darkroom(self): def test_darkroom(self):
room = create_object(tutrooms.DarkRoom, key="darkroom") room = create_object(tutrooms.DarkRoom, key="darkroom")
self.char1.move_to(room) self.char1.move_to(room)
self.call(tutrooms.CmdDarkHelp(), "", "Can't help you until") self.call(tutrooms.CmdDarkHelp(), "", "Can't help you until")
def test_teleportroom(self): def test_teleportroom(self):
create_object(tutrooms.TeleportRoom, key="teleportroom") create_object(tutrooms.TeleportRoom, key="teleportroom")
def test_outroroom(self): def test_outroroom(self):
create_object(tutrooms.OutroRoom, key="outroroom") create_object(tutrooms.OutroRoom, key="outroroom")
# test turnbattle # test turnbattle
from evennia.contrib import turnbattle from evennia.contrib import turnbattle
from evennia.objects.objects import DefaultRoom from evennia.objects.objects import DefaultRoom
class TestTurnBattleCmd(CommandTest): class TestTurnBattleCmd(CommandTest):
# Test combat commands # Test combat commands
@ -860,6 +920,7 @@ class TestTurnBattleCmd(CommandTest):
self.call(turnbattle.CmdDisengage(), "", "You can only do that in combat. (see: help fight)") self.call(turnbattle.CmdDisengage(), "", "You can only do that in combat. (see: help fight)")
self.call(turnbattle.CmdRest(), "", "Char rests to recover HP.") self.call(turnbattle.CmdRest(), "", "Char rests to recover HP.")
class TestTurnBattleFunc(EvenniaTest): class TestTurnBattleFunc(EvenniaTest):
# Test combat functions # Test combat functions
@ -944,6 +1005,7 @@ class TestTurnBattleFunc(EvenniaTest):
from evennia.contrib.unixcommand import UnixCommand from evennia.contrib.unixcommand import UnixCommand
class CmdDummy(UnixCommand): class CmdDummy(UnixCommand):
"""A dummy UnixCommand.""" """A dummy UnixCommand."""
@ -991,6 +1053,7 @@ class TestUnixCommand(CommandTest):
import re import re
from evennia.contrib import color_markups from evennia.contrib import color_markups
class TestColorMarkup(EvenniaTest): class TestColorMarkup(EvenniaTest):
""" """
Note: Normally this would be tested by importing the ansi parser and run Note: Normally this would be tested by importing the ansi parser and run
@ -999,6 +1062,7 @@ class TestColorMarkup(EvenniaTest):
many other modules it appears that trying to overload many other modules it appears that trying to overload
settings to test it causes issues with unrelated tests. settings to test it causes issues with unrelated tests.
""" """
def test_curly_markup(self): def test_curly_markup(self):
ansi_map = color_markups.CURLY_COLOR_ANSI_EXTRA_MAP ansi_map = color_markups.CURLY_COLOR_ANSI_EXTRA_MAP
self.assertIsNotNone(re.match(re.escape(ansi_map[7][0]), '{r')) self.assertIsNotNone(re.match(re.escape(ansi_map[7][0]), '{r'))
@ -1047,10 +1111,12 @@ class TestColorMarkup(EvenniaTest):
self.assertEqual(bright_map[0][1], '%c[500') self.assertEqual(bright_map[0][1], '%c[500')
self.assertEqual(bright_map[-1][1], '%c[222') self.assertEqual(bright_map[-1][1], '%c[222')
from evennia.contrib import random_string_generator from evennia.contrib import random_string_generator
SIMPLE_GENERATOR = random_string_generator.RandomStringGenerator("simple", "[01]{2}") SIMPLE_GENERATOR = random_string_generator.RandomStringGenerator("simple", "[01]{2}")
class TestRandomStringGenerator(EvenniaTest): class TestRandomStringGenerator(EvenniaTest):
def test_generate(self): def test_generate(self):

View file

@ -12,6 +12,7 @@ make sure to put it on yourself or you won't see any messages!
import random import random
from evennia import DefaultScript from evennia import DefaultScript
class BodyFunctions(DefaultScript): class BodyFunctions(DefaultScript):
""" """
This class defines the script itself This class defines the script itself

View file

@ -33,6 +33,7 @@ class RedButton(DefaultObject):
desc_lamp_broken - description when lamp is broken desc_lamp_broken - description when lamp is broken
""" """
def at_object_creation(self): def at_object_creation(self):
""" """
This function is called when object is created. Use this This function is called when object is created. Use this

View file

@ -26,12 +26,14 @@ from evennia.contrib.tutorial_examples import cmdset_red_button as cmdsetexample
# a bright light. The last one also has a timer component that allows it # a bright light. The last one also has a timer component that allows it
# to remove itself after a while (and the player recovers their eyesight). # to remove itself after a while (and the player recovers their eyesight).
class ClosedLidState(DefaultScript): class ClosedLidState(DefaultScript):
""" """
This manages the cmdset for the "closed" button state. What this This manages the cmdset for the "closed" button state. What this
means is that while this script is valid, we add the RedButtonClosed means is that while this script is valid, we add the RedButtonClosed
cmdset to it (with commands like open, nudge lid etc) cmdset to it (with commands like open, nudge lid etc)
""" """
def at_script_creation(self): def at_script_creation(self):
"Called when script first created." "Called when script first created."
self.desc = "Script that manages the closed-state cmdsets for red button." self.desc = "Script that manages the closed-state cmdsets for red button."
@ -67,6 +69,7 @@ class OpenLidState(DefaultScript):
This manages the cmdset for the "open" button state. This will add This manages the cmdset for the "open" button state. This will add
the RedButtonOpen the RedButtonOpen
""" """
def at_script_creation(self): def at_script_creation(self):
"Called when script first created." "Called when script first created."
self.desc = "Script that manages the opened-state cmdsets for red button." self.desc = "Script that manages the opened-state cmdsets for red button."
@ -105,6 +108,7 @@ class BlindedState(DefaultScript):
restored. It's up to the function starting the script to actually restored. It's up to the function starting the script to actually
set it on the right account object. set it on the right account object.
""" """
def at_script_creation(self): def at_script_creation(self):
""" """
We set up the script here. We set up the script here.
@ -158,6 +162,7 @@ class CloseLidEvent(DefaultScript):
script that should be started/created when the script that should be started/created when the
lid is opened. lid is opened.
""" """
def at_script_creation(self): def at_script_creation(self):
""" """
Called when script object is first created. Sets things up. Called when script object is first created. Sets things up.
@ -194,10 +199,12 @@ class CloseLidEvent(DefaultScript):
""" """
self.obj.close_lid() self.obj.close_lid()
class BlinkButtonEvent(DefaultScript): class BlinkButtonEvent(DefaultScript):
""" """
This timed script lets the button flash at regular intervals. This timed script lets the button flash at regular intervals.
""" """
def at_script_creation(self): def at_script_creation(self):
""" """
Sets things up. We want the button's lamp to blink at Sets things up. We want the button's lamp to blink at
@ -223,6 +230,7 @@ class BlinkButtonEvent(DefaultScript):
""" """
self.obj.blink() self.obj.blink()
class DeactivateButtonEvent(DefaultScript): class DeactivateButtonEvent(DefaultScript):
""" """
This deactivates the button for a short while (it won't blink, won't This deactivates the button for a short while (it won't blink, won't
@ -231,6 +239,7 @@ class DeactivateButtonEvent(DefaultScript):
in the AddBlindedCmdSet script since that script is defined on the *account* in the AddBlindedCmdSet script since that script is defined on the *account*
whereas this one must be defined on the *button*. whereas this one must be defined on the *button*.
""" """
def at_script_creation(self): def at_script_creation(self):
""" """
Sets things up. Sets things up.

View file

@ -5,4 +5,3 @@ This package holds the demo game of Evennia.
from __future__ import absolute_import from __future__ import absolute_import
from . import mob, objects, rooms from . import mob, objects, rooms

View file

@ -13,6 +13,7 @@ from evennia import Command, CmdSet
from evennia import logger from evennia import logger
from evennia.contrib.tutorial_world import objects as tut_objects from evennia.contrib.tutorial_world import objects as tut_objects
class CmdMobOnOff(Command): class CmdMobOnOff(Command):
""" """
Activates/deactivates Mob Activates/deactivates Mob
@ -51,9 +52,11 @@ class MobCmdSet(CmdSet):
""" """
Holds the admin command controlling the mob Holds the admin command controlling the mob
""" """
def at_cmdset_creation(self): def at_cmdset_creation(self):
self.add(CmdMobOnOff()) self.add(CmdMobOnOff())
class Mob(tut_objects.TutorialObject): class Mob(tut_objects.TutorialObject):
""" """
This is a state-machine AI mobile. It has several states which are This is a state-machine AI mobile. It has several states which are
@ -91,6 +94,7 @@ class Mob(tut_objects.TutorialObject):
happen to roam into a room with no exits. happen to roam into a room with no exits.
""" """
def at_init(self): def at_init(self):
""" """
When initialized from cache (after a server reboot), set up When initialized from cache (after a server reboot), set up
@ -379,7 +383,6 @@ class Mob(tut_objects.TutorialObject):
else: else:
logger.log_err("Mob: mob.db.send_defeated_to not found: %s" % self.db.send_defeated_to) logger.log_err("Mob: mob.db.send_defeated_to not found: %s" % self.db.send_defeated_to)
# response methods - called by other objects # response methods - called by other objects
def at_hit(self, weapon, attacker, damage): def at_hit(self, weapon, attacker, damage):

View file

@ -106,6 +106,7 @@ class CmdSetReadable(CmdSet):
""" """
A CmdSet for readables. A CmdSet for readables.
""" """
def at_cmdset_creation(self): def at_cmdset_creation(self):
""" """
Called when the cmdset is created. Called when the cmdset is created.
@ -117,6 +118,7 @@ class Readable(TutorialObject):
""" """
This simple object defines some attributes and This simple object defines some attributes and
""" """
def at_object_creation(self): def at_object_creation(self):
""" """
Called when object is created. We make sure to set the needed Called when object is created. We make sure to set the needed
@ -176,6 +178,7 @@ class CmdClimb(Command):
class CmdSetClimbable(CmdSet): class CmdSetClimbable(CmdSet):
"""Climbing cmdset""" """Climbing cmdset"""
def at_cmdset_creation(self): def at_cmdset_creation(self):
"""populate set""" """populate set"""
self.add(CmdClimb()) self.add(CmdClimb())
@ -303,6 +306,7 @@ class LightSource(TutorialObject):
When burned out, the object will be deleted. When burned out, the object will be deleted.
""" """
def at_init(self): def at_init(self):
""" """
If this is called with the Attribute is_giving_light already If this is called with the Attribute is_giving_light already
@ -589,6 +593,7 @@ class CrumblingWall(TutorialObject, DefaultExit):
whenever the button is pushed (this hides it as an exit whenever the button is pushed (this hides it as an exit
until it actually is) until it actually is)
""" """
def at_init(self): def at_init(self):
""" """
Called when object is recalled from cache. Called when object is recalled from cache.
@ -838,6 +843,7 @@ class CmdAttack(Command):
class CmdSetWeapon(CmdSet): class CmdSetWeapon(CmdSet):
"""Holds the attack command.""" """Holds the attack command."""
def at_cmdset_creation(self): def at_cmdset_creation(self):
"""called at first object creation.""" """called at first object creation."""
self.add(CmdAttack()) self.add(CmdAttack())
@ -854,6 +860,7 @@ class Weapon(TutorialObject):
type of attack) (0-10) type of attack) (0-10)
""" """
def at_object_creation(self): def at_object_creation(self):
"""Called at first creation of the object""" """Called at first creation of the object"""
super(Weapon, self).at_object_creation() super(Weapon, self).at_object_creation()
@ -1037,6 +1044,7 @@ class WeaponRack(TutorialObject):
grab another one. grab another one.
""" """
def at_object_creation(self): def at_object_creation(self):
""" """
called at creation called at creation

View file

@ -215,6 +215,7 @@ class TutorialRoom(DefaultRoom):
This is the base room type for all rooms in the tutorial world. This is the base room type for all rooms in the tutorial world.
It defines a cmdset on itself for reading tutorial info about the location. It defines a cmdset on itself for reading tutorial info about the location.
""" """
def at_object_creation(self): def at_object_creation(self):
"""Called when room is first created""" """Called when room is first created"""
self.db.tutorial_info = "This is a tutorial room. It allows you to use the 'tutorial' command." self.db.tutorial_info = "This is a tutorial room. It allows you to use the 'tutorial' command."
@ -300,6 +301,7 @@ class WeatherRoom(TutorialRoom):
inherit from this. inherit from this.
""" """
def at_object_creation(self): def at_object_creation(self):
""" """
Called when object is first created. Called when object is first created.
@ -355,6 +357,7 @@ class IntroRoom(TutorialRoom):
properties to customize: properties to customize:
char_health - integer > 0 (default 20) char_health - integer > 0 (default 20)
""" """
def at_object_creation(self): def at_object_creation(self):
""" """
Called when the room is first created. Called when the room is first created.
@ -625,6 +628,7 @@ class BridgeRoom(WeatherRoom):
the CmdLookBridge command). the CmdLookBridge command).
""" """
def at_object_creation(self): def at_object_creation(self):
"""Setups the room""" """Setups the room"""
# this will start the weather room's ticker and tell # this will start the weather room's ticker and tell
@ -827,6 +831,7 @@ class DarkRoom(TutorialRoom):
may have been beaten up by the ghostly apparition at this point. may have been beaten up by the ghostly apparition at this point.
""" """
def at_object_creation(self): def at_object_creation(self):
""" """
Called when object is first created. Called when object is first created.
@ -942,6 +947,7 @@ class TeleportRoom(TutorialRoom):
failure_teleport_msg - message to echo while teleporting to failure failure_teleport_msg - message to echo while teleporting to failure
""" """
def at_object_creation(self): def at_object_creation(self):
"""Called at first creation""" """Called at first creation"""
super(TeleportRoom, self).at_object_creation() super(TeleportRoom, self).at_object_creation()

View file

@ -16,6 +16,7 @@ own cmdsets by inheriting from them or directly from `evennia.CmdSet`.
from evennia import default_cmds from evennia import default_cmds
class CharacterCmdSet(default_cmds.CharacterCmdSet): class CharacterCmdSet(default_cmds.CharacterCmdSet):
""" """
The `CharacterCmdSet` contains general in-game commands like `look`, The `CharacterCmdSet` contains general in-game commands like `look`,

View file

@ -25,6 +25,7 @@ line to your settings file:
""" """
def at_search_result(matches, caller, query="", quiet=False, **kwargs): def at_search_result(matches, caller, query="", quiet=False, **kwargs):
""" """
This is a generic hook for handling all processing of a search This is a generic hook for handling all processing of a search

View file

@ -31,6 +31,7 @@ your settings file:
""" """
def cmdparser(raw_string, cmdset, caller, match_index=None): def cmdparser(raw_string, cmdset, caller, match_index=None):
""" """
This function is called by the cmdhandler once it has This function is called by the cmdhandler once it has

View file

@ -23,6 +23,7 @@ settings file:
from evennia.server.serversession import ServerSession as BaseServerSession from evennia.server.serversession import ServerSession as BaseServerSession
class ServerSession(BaseServerSession): class ServerSession(BaseServerSession):
""" """
This class represents a player's session and is a template for This class represents a player's session and is a template for

View file

@ -26,4 +26,3 @@ def at_webserver_root_creation(web_root):
""" """
return web_root return web_root

View file

@ -24,6 +24,7 @@ several more options for customizing the Guest account system.
from evennia import DefaultAccount, DefaultGuest from evennia import DefaultAccount, DefaultGuest
class Account(DefaultAccount): class Account(DefaultAccount):
""" """
This class describes the actual OOC account (i.e. the user connecting This class describes the actual OOC account (i.e. the user connecting

View file

@ -14,6 +14,7 @@ to be modified.
from evennia import DefaultChannel from evennia import DefaultChannel
class Channel(DefaultChannel): class Channel(DefaultChannel):
""" """
Working methods: Working methods:

View file

@ -9,6 +9,7 @@ creation commands.
""" """
from evennia import DefaultCharacter from evennia import DefaultCharacter
class Character(DefaultCharacter): class Character(DefaultCharacter):
""" """
The Character defaults to reimplementing some of base Object's hook methods with the The Character defaults to reimplementing some of base Object's hook methods with the

View file

@ -8,6 +8,7 @@ for allowing Characters to traverse the exit to its destination.
""" """
from evennia import DefaultExit from evennia import DefaultExit
class Exit(DefaultExit): class Exit(DefaultExit):
""" """
Exits are connectors between rooms. Exits are normal Objects except Exits are connectors between rooms. Exits are normal Objects except

View file

@ -12,6 +12,7 @@ inheritance.
""" """
from evennia import DefaultObject from evennia import DefaultObject
class Object(DefaultObject): class Object(DefaultObject):
""" """
This is the root typeclass object, implementing an in-game Evennia This is the root typeclass object, implementing an in-game Evennia

View file

@ -8,12 +8,12 @@ from django.contrib import admin
from evennia.help.models import HelpEntry from evennia.help.models import HelpEntry
from evennia.typeclasses.admin import TagInline from evennia.typeclasses.admin import TagInline
class HelpTagInline(TagInline): class HelpTagInline(TagInline):
model = HelpEntry.db_tags.through model = HelpEntry.db_tags.through
related_field = "helpentry" related_field = "helpentry"
class HelpEntryForm(forms.ModelForm): class HelpEntryForm(forms.ModelForm):
"Defines how to display the help entry" "Defines how to display the help entry"
class Meta(object): class Meta(object):
@ -25,6 +25,7 @@ class HelpEntryForm(forms.ModelForm):
db_lock_storage = forms.CharField(label="Locks", initial='view:all()', required=False, db_lock_storage = forms.CharField(label="Locks", initial='view:all()', required=False,
widget=forms.TextInput(attrs={'size': '40'}),) widget=forms.TextInput(attrs={'size': '40'}),)
class HelpEntryAdmin(admin.ModelAdmin): class HelpEntryAdmin(admin.ModelAdmin):
"Sets up the admin manaager for help entries" "Sets up the admin manaager for help entries"
inlines = [HelpTagInline] inlines = [HelpTagInline]

View file

@ -24,6 +24,7 @@ class HelpEntryManager(TypedObjectManager):
search_help (equivalent to evennia.search_helpentry) search_help (equivalent to evennia.search_helpentry)
""" """
def find_topicmatch(self, topicstr, exact=False): def find_topicmatch(self, topicstr, exact=False):
""" """
Searches for matching topics or aliases based on player's Searches for matching topics or aliases based on player's

View file

@ -346,8 +346,8 @@ def attr(accessing_obj, accessed_obj, *args, **kwargs):
# check attributes, if they exist # check attributes, if they exist
if (hasattr(accessing_obj, 'attributes') and accessing_obj.attributes.has(attrname)): if (hasattr(accessing_obj, 'attributes') and accessing_obj.attributes.has(attrname)):
if value: if value:
return (hasattr(accessing_obj, 'attributes') return (hasattr(accessing_obj, 'attributes') and
and valcompare(accessing_obj.attributes.get(attrname), value, compare)) valcompare(accessing_obj.attributes.get(attrname), value, compare))
# fails on False/None values # fails on False/None values
return bool(accessing_obj.attributes.get(attrname)) return bool(accessing_obj.attributes.get(attrname))
return False return False
@ -366,6 +366,7 @@ def objattr(accessing_obj, accessed_obj, *args, **kwargs):
""" """
return attr(accessed_obj, accessed_obj, *args, **kwargs) return attr(accessed_obj, accessed_obj, *args, **kwargs)
def locattr(accessing_obj, accessed_obj, *args, **kwargs): def locattr(accessing_obj, accessed_obj, *args, **kwargs):
""" """
Usage: Usage:
@ -386,6 +387,7 @@ def locattr(accessing_obj, accessed_obj, *args, **kwargs):
return attr(accessing_obj.location, accessed_obj, *args, **kwargs) return attr(accessing_obj.location, accessed_obj, *args, **kwargs)
return False return False
def objlocattr(accessing_obj, accessed_obj, *args, **kwargs): def objlocattr(accessing_obj, accessed_obj, *args, **kwargs):
""" """
Usage: Usage:
@ -464,6 +466,7 @@ def attr_ne(accessing_obj, accessed_obj, *args, **kwargs):
""" """
return attr(accessing_obj, accessed_obj, *args, **{'compare': 'ne'}) return attr(accessing_obj, accessed_obj, *args, **{'compare': 'ne'})
def tag(accessing_obj, accessed_obj, *args, **kwargs): def tag(accessing_obj, accessed_obj, *args, **kwargs):
""" """
Usage: Usage:
@ -481,6 +484,7 @@ def tag(accessing_obj, accessed_obj, *args, **kwargs):
category = args[1] if len(args) > 1 else None category = args[1] if len(args) > 1 else None
return accessing_obj.tags.get(tagkey, category=category) return accessing_obj.tags.get(tagkey, category=category)
def objtag(accessing_obj, accessed_obj, *args, **kwargs): def objtag(accessing_obj, accessed_obj, *args, **kwargs):
""" """
Usage: Usage:
@ -492,6 +496,7 @@ def objtag(accessing_obj, accessed_obj, *args, **kwargs):
""" """
return accessed_obj.tags.get(*args) return accessed_obj.tags.get(*args)
def inside(accessing_obj, accessed_obj, *args, **kwargs): def inside(accessing_obj, accessed_obj, *args, **kwargs):
""" """
Usage: Usage:
@ -566,6 +571,7 @@ def superuser(*args, **kwargs):
""" """
return False return False
def has_account(accessing_obj, accessed_obj, *args, **kwargs): def has_account(accessing_obj, accessed_obj, *args, **kwargs):
""" """
Only returns true if accessing_obj has_account is true, that is, Only returns true if accessing_obj has_account is true, that is,
@ -576,6 +582,7 @@ def has_account(accessing_obj, accessed_obj, *args, **kwargs):
""" """
return hasattr(accessing_obj, "has_account") and accessing_obj.has_account return hasattr(accessing_obj, "has_account") and accessing_obj.has_account
def serversetting(accessing_obj, accessed_obj, *args, **kwargs): def serversetting(accessing_obj, accessed_obj, *args, **kwargs):
""" """
Only returns true if the Evennia settings exists, alternatively has Only returns true if the Evennia settings exists, alternatively has

View file

@ -121,6 +121,7 @@ WARNING_LOG = settings.LOCKWARNING_LOG_FILE
# by errors in lock definitions. # by errors in lock definitions.
# #
class LockException(Exception): class LockException(Exception):
""" """
Raised during an error in a lock. Raised during an error in a lock.
@ -133,6 +134,8 @@ class LockException(Exception):
# #
_LOCKFUNCS = {} _LOCKFUNCS = {}
def _cache_lockfuncs(): def _cache_lockfuncs():
""" """
Updates the cache. Updates the cache.
@ -146,6 +149,7 @@ def _cache_lockfuncs():
# pre-compiled regular expressions # pre-compiled regular expressions
# #
_RE_FUNCS = re.compile(r"\w+\([^)]*\)") _RE_FUNCS = re.compile(r"\w+\([^)]*\)")
_RE_SEPS = re.compile(r"(?<=[ )])AND(?=\s)|(?<=[ )])OR(?=\s)|(?<=[ )])NOT(?=\s)") _RE_SEPS = re.compile(r"(?<=[ )])AND(?=\s)|(?<=[ )])OR(?=\s)|(?<=[ )])NOT(?=\s)")
_RE_OK = re.compile(r"%s|and|or|not") _RE_OK = re.compile(r"%s|and|or|not")
@ -229,7 +233,7 @@ class LockHandler(object):
if not callable(func): if not callable(func):
elist.append(_("Lock: lock-function '%s' is not available.") % funcstring) elist.append(_("Lock: lock-function '%s' is not available.") % funcstring)
continue continue
args = list(arg.strip() for arg in rest.split(',') if arg and not '=' in arg) args = list(arg.strip() for arg in rest.split(',') if arg and '=' not in arg)
kwargs = dict([arg.split('=', 1) for arg in rest.split(',') if arg and '=' in arg]) kwargs = dict([arg.split('=', 1) for arg in rest.split(',') if arg and '=' in arg])
lock_funcs.append((func, args, kwargs)) lock_funcs.append((func, args, kwargs))
evalstring = evalstring.replace(funcstring, '%s') evalstring = evalstring.replace(funcstring, '%s')
@ -244,7 +248,7 @@ class LockHandler(object):
continue continue
if access_type in locks: if access_type in locks:
duplicates += 1 duplicates += 1
wlist.append(_("LockHandler on %(obj)s: access type '%(access_type)s' changed from '%(source)s' to '%(goal)s' " % \ wlist.append(_("LockHandler on %(obj)s: access type '%(access_type)s' changed from '%(source)s' to '%(goal)s' " %
{"obj": self.obj, "access_type": access_type, "source": locks[access_type][2], "goal": raw_lockstring})) {"obj": self.obj, "access_type": access_type, "source": locks[access_type][2], "goal": raw_lockstring}))
locks[access_type] = (evalstring, tuple(lock_funcs), raw_lockstring) locks[access_type] = (evalstring, tuple(lock_funcs), raw_lockstring)
if wlist and WARNING_LOG: if wlist and WARNING_LOG:
@ -300,7 +304,7 @@ class LockHandler(object):
""" """
# sanity checks # sanity checks
for lockdef in lockstring.split(';'): for lockdef in lockstring.split(';'):
if not ':' in lockstring: if ':' not in lockstring:
self._log_error(_("Lock: '%s' contains no colon (:).") % lockdef) self._log_error(_("Lock: '%s' contains no colon (:).") % lockdef)
return False return False
access_type, rhs = [part.strip() for part in lockdef.split(':', 1)] access_type, rhs = [part.strip() for part in lockdef.split(':', 1)]
@ -449,9 +453,9 @@ class LockHandler(object):
return True return True
except AttributeError: except AttributeError:
# happens before session is initiated. # happens before session is initiated.
if not no_superuser_bypass and ((hasattr(accessing_obj, 'is_superuser') and accessing_obj.is_superuser) if not no_superuser_bypass and ((hasattr(accessing_obj, 'is_superuser') and accessing_obj.is_superuser) or
or (hasattr(accessing_obj, 'account') and hasattr(accessing_obj.account, 'is_superuser') and accessing_obj.account.is_superuser) (hasattr(accessing_obj, 'account') and hasattr(accessing_obj.account, 'is_superuser') and accessing_obj.account.is_superuser) or
or (hasattr(accessing_obj, 'get_account') and (not accessing_obj.get_account() or accessing_obj.get_account().is_superuser))): (hasattr(accessing_obj, 'get_account') and (not accessing_obj.get_account() or accessing_obj.get_account().is_superuser))):
return True return True
# no superuser or bypass -> normal lock operation # no superuser or bypass -> normal lock operation
@ -510,17 +514,17 @@ class LockHandler(object):
if accessing_obj.locks.lock_bypass and not no_superuser_bypass: if accessing_obj.locks.lock_bypass and not no_superuser_bypass:
return True return True
except AttributeError: except AttributeError:
if no_superuser_bypass and ((hasattr(accessing_obj, 'is_superuser') and accessing_obj.is_superuser) if no_superuser_bypass and ((hasattr(accessing_obj, 'is_superuser') and accessing_obj.is_superuser) or
or (hasattr(accessing_obj, 'account') and hasattr(accessing_obj.account, 'is_superuser') and accessing_obj.account.is_superuser) (hasattr(accessing_obj, 'account') and hasattr(accessing_obj.account, 'is_superuser') and accessing_obj.account.is_superuser) or
or (hasattr(accessing_obj, 'get_account') and (not accessing_obj.get_account() or accessing_obj.get_account().is_superuser))): (hasattr(accessing_obj, 'get_account') and (not accessing_obj.get_account() or accessing_obj.get_account().is_superuser))):
return True return True
if not ":" in lockstring: if ":" not in lockstring:
lockstring = "%s:%s" % ("_dummy", lockstring) lockstring = "%s:%s" % ("_dummy", lockstring)
locks = self._parse_lockstring(lockstring) locks = self._parse_lockstring(lockstring)
if access_type: if access_type:
if not access_type in locks: if access_type not in locks:
return default return default
else: else:
return self._eval_access_type( return self._eval_access_type(

View file

@ -3,12 +3,14 @@ from __future__ import unicode_literals
from django.db import models, migrations from django.db import models, migrations
def convert_defaults(apps, schema_editor): def convert_defaults(apps, schema_editor):
ObjectDB = apps.get_model("objects", "ObjectDB") ObjectDB = apps.get_model("objects", "ObjectDB")
for obj in ObjectDB.objects.filter(db_typeclass_path="src.objects.objects.Object"): for obj in ObjectDB.objects.filter(db_typeclass_path="src.objects.objects.Object"):
obj.db_typeclass_path = "typeclasses.objects.Object" obj.db_typeclass_path = "typeclasses.objects.Object"
obj.save() obj.save()
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [

View file

@ -21,6 +21,7 @@ def forwards(apps, schema_editor):
object.db_account = account object.db_account = account
object.save(update_fields=['db_account']) object.save(update_fields=['db_account'])
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [

View file

@ -33,6 +33,7 @@ class ContentsHandler(object):
for object-cmdsets). It is stored on the 'contents_cache' property for object-cmdsets). It is stored on the 'contents_cache' property
of the ObjectDB. of the ObjectDB.
""" """
def __init__(self, obj): def __init__(self, obj):
""" """
Sets up the contents handler. Sets up the contents handler.

View file

@ -39,6 +39,7 @@ class ObjectSessionHandler(object):
Handles the get/setting of the sessid Handles the get/setting of the sessid
comma-separated integer field comma-separated integer field
""" """
def __init__(self, obj): def __init__(self, obj):
""" """
Initializes the handler. Initializes the handler.
@ -1778,6 +1779,7 @@ class DefaultRoom(DefaultObject):
This is the base room object. It's just like any Object except its This is the base room object. It's just like any Object except its
location is always `None`. location is always `None`.
""" """
def basetype_setup(self): def basetype_setup(self):
""" """
Simple room setup setting locks to make sure the room Simple room setup setting locks to make sure the room

View file

@ -34,6 +34,7 @@ class ScriptDBManager(TypedObjectManager):
copy_script copy_script
""" """
def get_all_scripts_on_obj(self, obj, key=None): def get_all_scripts_on_obj(self, obj, key=None):
""" """
Find all Scripts related to a particular object. Find all Scripts related to a particular object.

View file

@ -3,6 +3,7 @@ from __future__ import unicode_literals
from django.db import models, migrations from django.db import models, migrations
def convert_defaults(apps, schema_editor): def convert_defaults(apps, schema_editor):
ScriptDB = apps.get_model("scripts", "ScriptDB") ScriptDB = apps.get_model("scripts", "ScriptDB")
for script in ScriptDB.objects.filter(db_typeclass_path="src.scripts.scripts.Script"): for script in ScriptDB.objects.filter(db_typeclass_path="src.scripts.scripts.Script"):
@ -12,6 +13,7 @@ def convert_defaults(apps, schema_editor):
script.db_typeclass_path = "evennia.utils.gametime.GameTime" script.db_typeclass_path = "evennia.utils.gametime.GameTime"
script.save() script.save()
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [

View file

@ -3,6 +3,7 @@ from __future__ import unicode_literals
from django.db import models, migrations from django.db import models, migrations
def remove_manage_scripts(apps, schema_editor): def remove_manage_scripts(apps, schema_editor):
ScriptDB = apps.get_model("scripts", "ScriptDB") ScriptDB = apps.get_model("scripts", "ScriptDB")
for script in ScriptDB.objects.filter(db_typeclass_path__in=(u'evennia.scripts.scripts.CheckSessions', for script in ScriptDB.objects.filter(db_typeclass_path__in=(u'evennia.scripts.scripts.CheckSessions',
@ -12,6 +13,7 @@ def remove_manage_scripts(apps, schema_editor):
u'evennia.utils.gametime.GameTime')): u'evennia.utils.gametime.GameTime')):
script.delete() script.delete()
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [

View file

@ -3,6 +3,7 @@ from __future__ import unicode_literals
from django.db import models, migrations from django.db import models, migrations
def remove_manage_scripts(apps, schema_editor): def remove_manage_scripts(apps, schema_editor):
ScriptDB = apps.get_model("scripts", "ScriptDB") ScriptDB = apps.get_model("scripts", "ScriptDB")
for script in ScriptDB.objects.filter(db_typeclass_path__in=(u'src.scripts.scripts.CheckSessions', for script in ScriptDB.objects.filter(db_typeclass_path__in=(u'src.scripts.scripts.CheckSessions',
@ -12,6 +13,7 @@ def remove_manage_scripts(apps, schema_editor):
u'src.utils.gametime.GameTime')): u'src.utils.gametime.GameTime')):
script.delete() script.delete()
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [

View file

@ -71,7 +71,6 @@ class ScriptDB(TypedObject):
""" """
# #
# ScriptDB Database Model setup # ScriptDB Database Model setup
# #

View file

@ -23,11 +23,13 @@ _SA = object.__setattr__
_GA = object.__getattribute__ _GA = object.__getattribute__
_DA = object.__delattr__ _DA = object.__delattr__
class MonitorHandler(object): class MonitorHandler(object):
""" """
This is a resource singleton that allows for registering This is a resource singleton that allows for registering
callbacks for when a field or Attribute is updated (saved). callbacks for when a field or Attribute is updated (saved).
""" """
def __init__(self): def __init__(self):
""" """
Initialize the handler. Initialize the handler.
@ -149,7 +151,6 @@ class MonitorHandler(object):
else: else:
self.monitors[obj][fieldname][idstring] = (callback, persistent, kwargs) self.monitors[obj][fieldname][idstring] = (callback, persistent, kwargs)
def remove(self, obj, fieldname, idstring=""): def remove(self, obj, fieldname, idstring=""):
""" """
Remove a monitor. Remove a monitor.

View file

@ -13,11 +13,13 @@ from evennia.utils import logger
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
class ScriptHandler(object): class ScriptHandler(object):
""" """
Implements the handler. This sits on each game object. Implements the handler. This sits on each game object.
""" """
def __init__(self, obj): def __init__(self, obj):
""" """
Set up internal state. Set up internal state.

View file

@ -596,6 +596,7 @@ class DoNothing(DefaultScript):
""" """
A script that does nothing. Used as default fallback. A script that does nothing. Used as default fallback.
""" """
def at_script_creation(self): def at_script_creation(self):
""" """
Setup the script Setup the script
@ -608,6 +609,7 @@ class Store(DefaultScript):
""" """
Simple storage script Simple storage script
""" """
def at_script_creation(self): def at_script_creation(self):
""" """
Setup the script Setup the script

View file

@ -11,6 +11,7 @@ from evennia.utils.dbserialize import dbserialize, dbunserialize
TASK_HANDLER = None TASK_HANDLER = None
class TaskHandler(object): class TaskHandler(object):
""" """
@ -71,8 +72,8 @@ class TaskHandler(object):
try: try:
dbserialize(callback) dbserialize(callback)
except (TypeError, AttributeError): except (TypeError, AttributeError):
raise ValueError("the specified callback {} cannot be pickled. " \ raise ValueError("the specified callback {} cannot be pickled. "
"It must be a top-level function in a module or an " \ "It must be a top-level function in a module or an "
"instance method.".format(callback)) "instance method.".format(callback))
else: else:
safe_callback = callback safe_callback = callback
@ -112,8 +113,8 @@ class TaskHandler(object):
try: try:
dbserialize(arg) dbserialize(arg)
except (TypeError, AttributeError): except (TypeError, AttributeError):
logger.log_err("The positional argument {} cannot be " \ logger.log_err("The positional argument {} cannot be "
"pickled and will not be present in the arguments " \ "pickled and will not be present in the arguments "
"fed to the callback {}".format(arg, callback)) "fed to the callback {}".format(arg, callback))
else: else:
safe_args.append(arg) safe_args.append(arg)
@ -122,8 +123,8 @@ class TaskHandler(object):
try: try:
dbserialize(value) dbserialize(value)
except (TypeError, AttributeError): except (TypeError, AttributeError):
logger.log_err("The {} keyword argument {} cannot be " \ logger.log_err("The {} keyword argument {} cannot be "
"pickled and will not be present in the arguments " \ "pickled and will not be present in the arguments "
"fed to the callback {}".format(key, value, callback)) "fed to the callback {}".format(key, value, callback))
else: else:
safe_kwargs[key] = value safe_kwargs[key] = value
@ -185,4 +186,3 @@ class TaskHandler(object):
# Create the soft singleton # Create the soft singleton
TASK_HANDLER = TaskHandler() TASK_HANDLER = TaskHandler()

View file

@ -7,6 +7,7 @@ from evennia.scripts.scripts import DoNothing
class TestScriptDB(TestCase): class TestScriptDB(TestCase):
"Check the singleton/static ScriptDB object works correctly" "Check the singleton/static ScriptDB object works correctly"
def setUp(self): def setUp(self):
self.scr = create_script(DoNothing) self.scr = create_script(DoNothing)

View file

@ -85,6 +85,7 @@ _ERROR_ADD_TICKER = \
{storekey} {storekey}
Ticker was not added.""" Ticker was not added."""
class Ticker(object): class Ticker(object):
""" """
Represents a repeatedly running task that calls Represents a repeatedly running task that calls
@ -145,7 +146,6 @@ class Ticker(object):
self._to_remove = [] self._to_remove = []
self._to_add = [] self._to_add = []
def __init__(self, interval): def __init__(self, interval):
""" """
Set up the ticker Set up the ticker
@ -584,5 +584,6 @@ class TickerHandler(object):
store_keys.append((kwargs.get("_obj", None), callfunc, path, interval, idstring, persistent)) store_keys.append((kwargs.get("_obj", None), callfunc, path, interval, idstring, persistent))
return store_keys return store_keys
# main tickerhandler # main tickerhandler
TICKER_HANDLER = TickerHandler() TICKER_HANDLER = TickerHandler()

View file

@ -19,4 +19,6 @@ class ServerConfigAdmin(admin.ModelAdmin):
save_as = True save_as = True
save_on_top = True save_on_top = True
list_select_related = True list_select_related = True
admin.site.register(ServerConfig, ServerConfigAdmin) admin.site.register(ServerConfig, ServerConfigAdmin)

View file

@ -319,8 +319,12 @@ class FunctionCall(amp.Command):
# Helper functions for pickling. # Helper functions for pickling.
dumps = lambda data: to_str(pickle.dumps(to_str(data), pickle.HIGHEST_PROTOCOL)) def dumps(data):
loads = lambda data: pickle.loads(to_str(data)) return to_str(pickle.dumps(to_str(data), pickle.HIGHEST_PROTOCOL))
def loads(data):
return pickle.loads(to_str(data))
# ------------------------------------------------------------- # -------------------------------------------------------------

View file

@ -5,6 +5,7 @@ checks for.
These all print to the terminal. These all print to the terminal.
""" """
def check_errors(settings): def check_errors(settings):
""" """
Check for deprecations that are critical errors and should stop Check for deprecations that are critical errors and should stop

View file

@ -419,6 +419,7 @@ def evennia_version():
pass pass
return version return version
EVENNIA_VERSION = evennia_version() EVENNIA_VERSION = evennia_version()
@ -434,7 +435,7 @@ def check_main_evennia_dependencies():
error = False error = False
# Python # Python
pversion = ".".join(str(num) for num in sys.version_info if type(num) == int) pversion = ".".join(str(num) for num in sys.version_info if isinstance(num, int))
if LooseVersion(pversion) < LooseVersion(PYTHON_MIN): if LooseVersion(pversion) < LooseVersion(PYTHON_MIN):
print(ERROR_PYTHON_VERSION.format(pversion=pversion, python_min=PYTHON_MIN)) print(ERROR_PYTHON_VERSION.format(pversion=pversion, python_min=PYTHON_MIN))
error = True error = True
@ -451,7 +452,7 @@ def check_main_evennia_dependencies():
error = True error = True
# Django # Django
try: try:
dversion = ".".join(str(num) for num in django.VERSION if type(num) == int) dversion = ".".join(str(num) for num in django.VERSION if isinstance(num, int))
# only the main version (1.5, not 1.5.4.0) # only the main version (1.5, not 1.5.4.0)
dversion_main = ".".join(dversion.split(".")[:2]) dversion_main = ".".join(dversion.split(".")[:2])
if LooseVersion(dversion) < LooseVersion(DJANGO_MIN): if LooseVersion(dversion) < LooseVersion(DJANGO_MIN):
@ -502,7 +503,7 @@ def create_secret_key():
import random import random
import string import string
secret_key = list((string.letters + secret_key = list((string.letters +
string.digits + string.punctuation).replace("\\", "")\ string.digits + string.punctuation).replace("\\", "")
.replace("'", '"').replace("{", "_").replace("}", "-")) .replace("'", '"').replace("{", "_").replace("}", "-"))
random.shuffle(secret_key) random.shuffle(secret_key)
secret_key = "".join(secret_key[:40]) secret_key = "".join(secret_key[:40])
@ -741,8 +742,8 @@ def kill(pidfile, killsignal=SIG, succmsg="", errmsg="",
os.kill(int(pid), killsignal) os.kill(int(pid), killsignal)
except OSError: except OSError:
print("Process %(pid)s cannot be stopped. "\ print("Process %(pid)s cannot be stopped. "
"The PID file 'server/%(pidfile)s' seems stale. "\ "The PID file 'server/%(pidfile)s' seems stale. "
"Try removing it." % {'pid': pid, 'pidfile': pidfile}) "Try removing it." % {'pid': pid, 'pidfile': pidfile})
return return
print("Evennia:", succmsg) print("Evennia:", succmsg)
@ -782,6 +783,7 @@ def error_check_python_modules():
""" """
from django.conf import settings from django.conf import settings
def _imp(path, split=True): def _imp(path, split=True):
"helper method" "helper method"
mod, fromlist = path, "None" mod, fromlist = path, "None"
@ -821,6 +823,7 @@ def error_check_python_modules():
_imp(settings.BASE_EXIT_TYPECLASS) _imp(settings.BASE_EXIT_TYPECLASS)
_imp(settings.BASE_SCRIPT_TYPECLASS) _imp(settings.BASE_SCRIPT_TYPECLASS)
def init_game_directory(path, check_db=True): def init_game_directory(path, check_db=True):
""" """
Try to analyze the given path to find settings.py - this defines Try to analyze the given path to find settings.py - this defines
@ -1275,7 +1278,6 @@ def main():
print("Using settings file '%s' (%s)." % ( print("Using settings file '%s' (%s)." % (
SETTINGSFILE, SETTINGS_DOTPATH)) SETTINGSFILE, SETTINGS_DOTPATH))
if args.initsettings: if args.initsettings:
# create new settings file # create new settings file
global GAMEDIR global GAMEDIR

View file

@ -19,7 +19,8 @@ import os
import sys import sys
from argparse import ArgumentParser from argparse import ArgumentParser
from subprocess import Popen from subprocess import Popen
import Queue, thread import Queue
import thread
import evennia import evennia
try: try:
@ -79,6 +80,7 @@ PROCESS_DOEXIT = "Deferring to external runner."
# Functions # Functions
def set_restart_mode(restart_file, flag="reload"): def set_restart_mode(restart_file, flag="reload"):
""" """
This sets a flag file for the restart mode. This sets a flag file for the restart mode.
@ -350,5 +352,6 @@ def main():
# Start processes # Start processes
start_services(server_argv, portal_argv, doexit=args.doexit) start_services(server_argv, portal_argv, doexit=args.doexit)
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View file

@ -35,7 +35,11 @@ _IDLE_COMMAND = settings.IDLE_COMMAND
_IDLE_COMMAND = (_IDLE_COMMAND, ) if _IDLE_COMMAND == "idle" else (_IDLE_COMMAND, "idle") _IDLE_COMMAND = (_IDLE_COMMAND, ) if _IDLE_COMMAND == "idle" else (_IDLE_COMMAND, "idle")
_GA = object.__getattribute__ _GA = object.__getattribute__
_SA = object.__setattr__ _SA = object.__setattr__
_NA = lambda o: "N/A"
def _NA(o):
return "N/A"
_ERROR_INPUT = "Inputfunc {name}({session}): Wrong/unrecognized input: {inp}" _ERROR_INPUT = "Inputfunc {name}({session}): Wrong/unrecognized input: {inp}"
@ -159,9 +163,6 @@ def browser_sessid(session, *args, **kwargs):
session.sessionhandler.login(session, account) session.sessionhandler.login(session, account)
def client_options(session, *args, **kwargs): def client_options(session, *args, **kwargs):
""" """
This allows the client an OOB way to inform us about its name and capabilities. This allows the client an OOB way to inform us about its name and capabilities.
@ -251,7 +252,7 @@ def client_options(session, *args, **kwargs):
'Room 1', 'IRE.Rift 1', 'IRE.Composer 1'): 'Room 1', 'IRE.Rift 1', 'IRE.Composer 1'):
# ignore mudlet's default send (aimed at IRE games) # ignore mudlet's default send (aimed at IRE games)
pass pass
elif not key in ("options", "cmdid"): elif key not in ("options", "cmdid"):
err = _ERROR_INPUT.format( err = _ERROR_INPUT.format(
name="client_settings", session=session, inp=key) name="client_settings", session=session, inp=key)
session.msg(text=err) session.msg(text=err)
@ -259,6 +260,7 @@ def client_options(session, *args, **kwargs):
# we must update the portal as well # we must update the portal as well
session.sessionhandler.session_portal_sync(session) session.sessionhandler.session_portal_sync(session)
# GMCP alias # GMCP alias
hello = client_options hello = client_options
supports_set = client_options supports_set = client_options
@ -298,6 +300,7 @@ def login(session, *args, **kwargs):
if account: if account:
session.sessionhandler.login(session, account) session.sessionhandler.login(session, account)
_gettable = { _gettable = {
"name": lambda obj: obj.key, "name": lambda obj: obj.key,
"key": lambda obj: obj.key, "key": lambda obj: obj.key,
@ -305,6 +308,7 @@ _gettable = {
"servername": lambda obj: settings.SERVERNAME "servername": lambda obj: settings.SERVERNAME
} }
def get_value(session, *args, **kwargs): def get_value(session, *args, **kwargs):
""" """
Return the value of a given attribute or db_property on the Return the value of a given attribute or db_property on the
@ -368,7 +372,6 @@ def repeat(session, *args, **kwargs):
session.msg("Allowed repeating functions are: %s" % (", ".join(_repeatable))) session.msg("Allowed repeating functions are: %s" % (", ".join(_repeatable)))
def unrepeat(session, *args, **kwargs): def unrepeat(session, *args, **kwargs):
"Wrapper for OOB use" "Wrapper for OOB use"
kwargs["stop"] = True kwargs["stop"] = True

View file

@ -16,6 +16,7 @@ class ServerConfigManager(models.Manager):
the server at run-time. the server at run-time.
""" """
def conf(self, key=None, value=None, delete=False, default=None): def conf(self, key=None, value=None, delete=False, default=None):
""" """
Add, retrieve and manipulate config values. Add, retrieve and manipulate config values.

View file

@ -22,12 +22,14 @@ MSSP_VAL = chr(2)
# try to get the customized mssp info, if it exists. # try to get the customized mssp info, if it exists.
MSSPTable_CUSTOM = utils.variable_from_module(settings.MSSP_META_MODULE, "MSSPTable", default={}) MSSPTable_CUSTOM = utils.variable_from_module(settings.MSSP_META_MODULE, "MSSPTable", default={})
class Mssp(object): class Mssp(object):
""" """
Implements the MSSP protocol. Add this to a variable on the telnet Implements the MSSP protocol. Add this to a variable on the telnet
protocol to set it up. protocol to set it up.
""" """
def __init__(self, protocol): def __init__(self, protocol):
""" """
initialize MSSP by storing protocol on ourselves and calling initialize MSSP by storing protocol on ourselves and calling

View file

@ -26,6 +26,7 @@ MXP_SEND = MXP_TEMPSECURE + \
MXP_TEMPSECURE + \ MXP_TEMPSECURE + \
"</SEND>" "</SEND>"
def mxp_parse(text): def mxp_parse(text):
""" """
Replaces links to the correct format for MXP. Replaces links to the correct format for MXP.
@ -44,6 +45,7 @@ def mxp_parse(text):
text = LINKS_SUB.sub(MXP_SEND, text) text = LINKS_SUB.sub(MXP_SEND, text)
return text return text
class Mxp(object): class Mxp(object):
""" """
Implements the MXP protocol. Implements the MXP protocol.

Some files were not shown because too many files have changed in this diff Show more