evennia.server package

This sub-package holds the Server and Portal programs - the “core” of Evennia. It also contains the SessionHandler that manages all connected users as well as defines all the connection protocols used to connect to the game.

Subpackages

Submodules

evennia.server.admin module

class evennia.server.admin.ServerConfigAdmin(model, admin_site)[source]

Bases: django.contrib.admin.options.ModelAdmin

Custom admin for server configs

list_display = ('db_key', 'db_value')
property media
ordering = ['db_key', 'db_value']
save_as = True
save_on_top = True
search_fields = ['db_key']

evennia.server.amp_client module

The Evennia Server service acts as an AMP-client when talking to the Portal. This module sets up the Client-side communication.

class evennia.server.amp_client.AMPClientFactory(server)[source]

Bases: twisted.internet.protocol.ReconnectingClientFactory

This factory creates an instance of an AMP client connection. This handles communication from the be the Evennia ‘Server’ service to the ‘Portal’. The client will try to auto-reconnect on a connection error.

__init__(server)[source]

Initializes the client factory.

Parameters

server (server) – server instance.

buildProtocol(addr)[source]

Creates an AMPProtocol instance when connecting to the AMP server.

Parameters

addr (str) – Connection address. Not used.

clientConnectionFailed(connector, reason)[source]

Called when an AMP connection attempt to the MUD server fails.

Parameters
  • connector (Connector) – Twisted Connector instance representing this connection.

  • reason (str) – Eventual text describing why connection failed.

clientConnectionLost(connector, reason)[source]

Called when the AMP connection to the MUD server is lost.

Parameters
  • connector (Connector) – Twisted Connector instance representing this connection.

  • reason (str) – Eventual text describing why connection was lost.

factor = 1.5
initialDelay = 1
maxDelay = 1
noisy = False
startedConnecting(connector)[source]

Called when starting to try to connect to the Portal AMP server.

Parameters

connector (Connector) – Twisted Connector instance representing this connection.

class evennia.server.amp_client.AMPServerClientProtocol(*args, **kwargs)[source]

Bases: evennia.server.portal.amp.AMPMultiConnectionProtocol

This protocol describes the Server service (acting as an AMP-client)’s communication with the Portal (which acts as the AMP-server)

_commandDispatch = {b'AdminPortal2Server': (<class 'evennia.server.portal.amp.AdminPortal2Server'>, <function catch_traceback>), b'FunctionCall': (<class 'evennia.server.portal.amp.FunctionCall'>, <function catch_traceback>), b'MsgPortal2Server': (<class 'evennia.server.portal.amp.MsgPortal2Server'>, <function catch_traceback>), b'MsgStatus': (<class 'evennia.server.portal.amp.MsgStatus'>, <function AMPServerClientProtocol.server_receive_status>), b'StartTLS': (<class 'twisted.protocols.amp.StartTLS'>, <function BinaryBoxProtocol._defaultStartTLSResponder>)}
connectionMade()[source]

Called when a new connection is established.

data_to_portal(command, sessid, **kwargs)[source]

Send data across the wire to the Portal

Parameters
  • command (AMP Command) – A protocol send command.

  • sessid (int) – A unique Session id.

  • kwargs (any) – Any data to pickle into the command.

Returns

A deferred with an errback.

Return type

deferred (deferred or None)

Notes

Data will be sent across the wire pickled as a tuple (sessid, kwargs).

send_AdminServer2Portal(session, operation='', **kwargs)[source]

Administrative access method called by the Server to send an instruction to the Portal.

Parameters
  • session (Session) – Session.

  • operation (char, optional) – Identifier for the server operation, as defined by the global variables in evennia/server/amp.py.

  • kwargs (dict, optional) – Data going into the adminstrative.

send_MsgServer2Portal(session, **kwargs)[source]
Access method - executed on the Server for sending data

to Portal.

Parameters
  • session (Session) – Unique Session.

  • kwargs (any, optiona) – Extra data.

server_receive_adminportal2server()

Helper decorator

server_receive_msgportal2server()

Helper decorator

server_receive_status(question)[source]

evennia.server.connection_wizard module

Link Evennia to external resources (wizard plugin for evennia_launcher)

class evennia.server.connection_wizard.ConnectionWizard[source]

Bases: object

__init__()[source]

Initialize self. See help(type(self)) for accurate signature.

ask_choice(prompt=' > ', options=None, default=None)[source]

Ask multiple-choice question, get response inline.

Kwargs:

prompt (str): Input prompt. options (list): List of options. Will be indexable by sequence number 1… default (int): The list index+1 of the default choice, if any

Returns

The answered reply.

Return type

reply (str)

ask_continue()[source]

‘Press return to continue’-prompt

ask_input(prompt=' > ', default=None, validator=None)[source]

Get arbitrary input inline.

Kwargs:

prompt (str): The display prompt. default (str): If empty input, use this. validator (callable): If given, the input will be passed

into this callable. It should return True unless validation fails (and is expected to echo why if so).

Returns

The input given, or default.

Return type

inp (str)

ask_node(options, prompt='Enter choice: ', default=None)[source]

Retrieve options and jump to different menu nodes

Parameters
  • options (dict) – Node options on the form {key: (desc, callback), }

  • prompt (str, optional) – Question to ask

  • default (str, optional) – Default value to use if user hits return.

ask_yesno(prompt, default='yes')[source]

Ask a yes/no question inline.

Kwargs:

prompt (str): The prompt to ask. default (str): “yes” or “no”, used if pressing return.

Returns

Either ‘yes’ or ‘no’.

Return type

reply (str)

display(text)[source]

Show text

evennia.server.connection_wizard._save_changes(wizard)[source]

Perform the save

evennia.server.connection_wizard.node_game_index_fields(wizard, status=None)[source]
evennia.server.connection_wizard.node_game_index_start(wizard, **kwargs)[source]
evennia.server.connection_wizard.node_mssp_start(wizard)[source]
evennia.server.connection_wizard.node_start(wizard)[source]
evennia.server.connection_wizard.node_view_and_apply_settings(wizard)[source]

Inspect and save the data gathered in the other nodes

evennia.server.deprecations module

This module contains historical deprecations that the Evennia launcher checks for.

These all print to the terminal.

evennia.server.deprecations.check_errors(settings)[source]

Check for deprecations that are critical errors and should stop the launcher.

Parameters

settings (Settings) – The Django settings file

Raises

DeprecationWarning if a critical deprecation is found.

evennia.server.deprecations.check_warnings(settings)[source]

Check conditions and deprecations that should produce warnings but which does not stop launch.

evennia.server.evennia_launcher module

Evennia launcher program

This is the start point for running Evennia.

Sets the appropriate environmental variables for managing an Evennia game. It will start and connect to the Portal, through which the Server is also controlled. This pprogram

Run the script with the -h flag to see usage information.

class evennia.server.evennia_launcher.AMPLauncherProtocol[source]

Bases: twisted.protocols.amp.AMP

Defines callbacks to the launcher

__init__()[source]

Initialize self. See help(type(self)) for accurate signature.

_commandDispatch = {b'MsgStatus': (<class 'evennia.server.evennia_launcher.MsgStatus'>, <function AMPLauncherProtocol.receive_status_from_portal>), b'StartTLS': (<class 'twisted.protocols.amp.StartTLS'>, <function BinaryBoxProtocol._defaultStartTLSResponder>)}
receive_status_from_portal(status)[source]

Get a status signal from portal - fire next queued callback

wait_for_status(callback)[source]

Register a waiter for a status return.

class evennia.server.evennia_launcher.MsgLauncher2Portal(**kw)[source]

Bases: twisted.protocols.amp.Command

Message Launcher -> Portal

allErrors = {<class 'Exception'>: b'EXCEPTION'}
arguments = [(b'operation', <twisted.protocols.amp.String object>), (b'arguments', <twisted.protocols.amp.String object>)]
commandName = b'MsgLauncher2Portal'
errors = {<class 'Exception'>: b'EXCEPTION'}
key = 'MsgLauncher2Portal'
response = []
reverseErrors = {b'EXCEPTION': <class 'Exception'>}
class evennia.server.evennia_launcher.MsgStatus(**kw)[source]

Bases: twisted.protocols.amp.Command

Ping between AMP services

allErrors = {<class 'Exception'>: b'EXCEPTION'}
arguments = [(b'status', <twisted.protocols.amp.String object>)]
commandName = b'MsgStatus'
errors = {<class 'Exception'>: b'EXCEPTION'}
key = 'MsgStatus'
response = [(b'status', <twisted.protocols.amp.String object>)]
reverseErrors = {b'EXCEPTION': <class 'Exception'>}
evennia.server.evennia_launcher._file_names_compact(filepath1, filepath2)[source]

Compact the output of filenames with same base dir

evennia.server.evennia_launcher._get_twistd_cmdline(pprofiler, sprofiler)[source]

Compile the command line for starting a Twisted application using the ‘twistd’ executable.

evennia.server.evennia_launcher._is_windows()[source]
evennia.server.evennia_launcher._parse_status(response)[source]

Unpack the status information

evennia.server.evennia_launcher._print_info(portal_info_dict, server_info_dict)[source]

Format info dicts from the Portal/Server for display

evennia.server.evennia_launcher._reactor_stop()[source]
evennia.server.evennia_launcher.check_database(always_return=False)[source]

Check so the database exists.

Parameters

always_return (bool, optional) – If set, will always return True/False also on critical errors. No output will be printed.

Returns

True if the database exists, otherwise False.

Return type

exists (bool)

evennia.server.evennia_launcher.check_main_evennia_dependencies()[source]

Checks and imports the Evennia dependencies. This must be done already before the paths are set up.

Returns

True if no dependency error was found.

Return type

not_error (bool)

evennia.server.evennia_launcher.collectstatic()[source]

Run the collectstatic django command

evennia.server.evennia_launcher.create_game_directory(dirname)[source]

Initialize a new game directory named dirname at the current path. This means copying the template directory from evennia’s root.

Parameters

dirname (str) – The directory name to create.

evennia.server.evennia_launcher.create_secret_key()[source]

Randomly create the secret key for the settings file

evennia.server.evennia_launcher.create_settings_file(init=True, secret_settings=False)[source]

Uses the template settings file to build a working settings file.

Parameters
  • init (bool) – This is part of the normal evennia –init operation. If false, this function will copy a fresh template file in (asking if it already exists).

  • secret_settings (bool, optional) – If False, create settings.py, otherwise create the secret_settings.py file.

evennia.server.evennia_launcher.create_superuser()[source]

Create the superuser account

evennia.server.evennia_launcher.del_pid(pidfile)[source]

The pidfile should normally be removed after a process has finished, but when sending certain signals they remain, so we need to clean them manually.

Parameters

pidfile (str) – The path of the pid file.

evennia.server.evennia_launcher.error_check_python_modules(show_warnings=False)[source]

Import settings modules in settings. This will raise exceptions on pure python-syntax issues which are hard to catch gracefully with exceptions in the engine (since they are formatting errors in the python source files themselves). Best they fail already here before we get any further.

Kwargs:

show_warnings (bool): If non-fatal warning messages should be shown.

evennia.server.evennia_launcher.evennia_version()[source]

Get the Evennia version info from the main package.

evennia.server.evennia_launcher.get_pid(pidfile, default=None)[source]

Get the PID (Process ID) by trying to access an PID file.

Parameters
  • pidfile (str) – The path of the pid file.

  • default (int, optional) – What to return if file does not exist.

Returns

The process id or default.

Return type

pid (str)

evennia.server.evennia_launcher.getenv()[source]

Get current environment and add PYTHONPATH.

Returns

Environment global dict.

Return type

env (dict)

evennia.server.evennia_launcher.init_game_directory(path, check_db=True, need_gamedir=True)[source]

Try to analyze the given path to find settings.py - this defines the game directory and also sets PYTHONPATH as well as the django path.

Parameters
  • path (str) – Path to new game directory, including its name.

  • check_db (bool, optional) – Check if the databae exists.

  • need_gamedir (bool, optional) – set to False if Evennia doesn’t require to be run in a valid game directory.

evennia.server.evennia_launcher.kill(pidfile, component='Server', callback=None, errback=None, killsignal=<Signals.SIGINT: 2>)[source]

Send a kill signal to a process based on PID. A customized success/error message will be returned. If clean=True, the system will attempt to manually remove the pid file. On Windows, no arguments are useful since Windows has no ability to direct signals except to all children of a console.

Parameters
  • pidfile (str) – The path of the pidfile to get the PID from. This is ignored on Windows.

  • component (str, optional) – Usually one of ‘Server’ or ‘Portal’. This is ignored on Windows.

  • errback (callable, optional) – Called if signal failed to send. This is ignored on Windows.

  • callback (callable, optional) – Called if kill signal was sent successfully. This is ignored on Windows.

  • killsignal (int, optional) – Signal identifier for signal to send. This is ignored on Windows.

evennia.server.evennia_launcher.list_settings(keys)[source]

Display the server settings. We only display the Evennia specific settings here. The result will be printed to the terminal.

Parameters

keys (str or list) – Setting key or keys to inspect.

evennia.server.evennia_launcher.main()[source]

Run the evennia launcher main program.

evennia.server.evennia_launcher.query_info()[source]

Display the info strings from the running Evennia

evennia.server.evennia_launcher.query_status(callback=None)[source]

Send status ping to portal

evennia.server.evennia_launcher.reboot_evennia(pprofiler=False, sprofiler=False)[source]

This is essentially an evennia stop && evennia start except we make sure the system has successfully shut down before starting it again.

If evennia was not running, start it.

evennia.server.evennia_launcher.reload_evennia(sprofiler=False, reset=False)[source]

This will instruct the Portal to reboot the Server component. We do this manually by telling the server to shutdown (in reload mode) and wait for the portal to report back, at which point we start the server again. This way we control the process exactly.

evennia.server.evennia_launcher.run_connect_wizard()[source]

Run the linking wizard, for adding new external connections.

evennia.server.evennia_launcher.run_dummyrunner(number_of_dummies)[source]

Start an instance of the dummyrunner

Parameters

number_of_dummies (int) – The number of dummy accounts to start.

Notes

The dummy accounts’ behavior can be customized by adding a dummyrunner_settings.py config file in the game’s conf/ directory.

evennia.server.evennia_launcher.run_menu()[source]

This launches an interactive menu.

evennia.server.evennia_launcher.send_instruction(operation, arguments, callback=None, errback=None)[source]

Send instruction and handle the response.

evennia.server.evennia_launcher.set_gamedir(path)[source]

Set GAMEDIR based on path, by figuring out where the setting file is inside the directory tree. This allows for running the launcher from elsewhere than the top of the gamedir folder.

evennia.server.evennia_launcher.show_version_info(about=False)[source]

Display version info.

Parameters

about (bool) – Include ABOUT info as well as version numbers.

Returns

A complete version info string.

Return type

version_info (str)

evennia.server.evennia_launcher.start_evennia(pprofiler=False, sprofiler=False)[source]

This will start Evennia anew by launching the Evennia Portal (which in turn will start the Server)

evennia.server.evennia_launcher.start_only_server()[source]

Tell portal to start server (debug)

evennia.server.evennia_launcher.start_portal_interactive()[source]

Start the Portal under control of the launcher process (foreground)

Notes

In a normal start, the launcher waits for the Portal to start, then tells it to start the Server. Since we can’t do this here, we instead start the Server first and then starts the Portal - the Server will auto-reconnect to the Portal. To allow the Server to be reloaded, this relies on a fixed server server-cmdline stored as a fallback on the portal application in evennia/server/portal/portal.py.

evennia.server.evennia_launcher.start_server_interactive()[source]

Start the Server under control of the launcher process (foreground)

evennia.server.evennia_launcher.stop_evennia()[source]

This instructs the Portal to stop the Server and then itself.

evennia.server.evennia_launcher.stop_server_only(when_stopped=None, interactive=False)[source]

Only stop the Server-component of Evennia (this is not useful except for debug)

Parameters
  • when_stopped (callable) – This will be called with no arguments when Server has stopped (or if it had already stopped when this is called).

  • interactive (bool, optional) – Set if this is called as part of the interactive reload mechanism.

evennia.server.evennia_launcher.tail_log_files(filename1, filename2, start_lines1=20, start_lines2=20, rate=1)[source]

Tail two logfiles interactively, combining their output to stdout

When first starting, this will display the tail of the log files. After that it will poll the log files repeatedly and display changes.

Parameters
  • filename1 (str) – Path to first log file.

  • filename2 (str) – Path to second log file.

  • start_lines1 (int) – How many lines to show from existing first log.

  • start_lines2 (int) – How many lines to show from existing second log.

  • rate (int, optional) – How often to poll the log file.

evennia.server.evennia_launcher.wait_for_status(portal_running=True, server_running=True, callback=None, errback=None, rate=0.5, retries=20)[source]

Repeat the status ping until the desired state combination is achieved.

Parameters
  • portal_running (bool or None) – Desired portal run-state. If None, any state is accepted.

  • server_running (bool or None) – Desired server run-state. If None, any state is accepted. The portal must be running.

  • callback (callable) – Will be called with portal_state, server_state when condition is fulfilled.

  • errback (callable) – Will be called with portal_state, server_state if the request is timed out.

  • rate (float) – How often to retry.

  • retries (int) – How many times to retry before timing out and calling errback.

evennia.server.evennia_launcher.wait_for_status_reply(callback)[source]

Wait for an explicit STATUS signal to be sent back from Evennia.

evennia.server.initial_setup module

This module handles initial database propagation, which is only run the first time the game starts. It will create some default channels, objects, and other things.

Everything starts at handle_setup()

evennia.server.initial_setup.at_initial_setup()[source]

Custom hook for users to overload some or all parts of the initial setup. Called very last in the sequence. It tries to import and srun a module settings.AT_INITIAL_SETUP_HOOK_MODULE and will fail silently if this does not exist or fails to load.

evennia.server.initial_setup.collectstatic()[source]

Run collectstatic to make sure all web assets are loaded.

evennia.server.initial_setup.create_channels()[source]

Creates some sensible default channels.

evennia.server.initial_setup.create_objects()[source]

Creates the #1 account and Limbo room.

evennia.server.initial_setup.get_god_account()[source]

Creates the god user and don’t take no for an answer.

evennia.server.initial_setup.handle_setup(last_step)[source]

Main logic for the module. It allows for restarting the initialization at any point if one of the modules should crash.

Parameters

last_step (int) – The last stored successful step, for starting over on errors. If < 0, initialization has finished and no steps need to be redone.

evennia.server.initial_setup.reset_server()[source]

We end the initialization by resetting the server. This makes sure the first login is the same as all the following ones, particularly it cleans all caches for the special objects. It also checks so the warm-reset mechanism works as it should.

evennia.server.inputfuncs module

Functions for processing input commands.

All global functions in this module whose name does not start with “_” is considered an inputfunc. Each function must have the following callsign (where inputfunc name is always lower-case, no matter what the OOB input name looked like):

inputfunc(session, *args, **kwargs)

Where “options” is always one of the kwargs, containing eventual protocol-options. There is one special function, the “default” function, which is called on a no-match. It has this callsign:

default(session, cmdname, *args, **kwargs)

Evennia knows which modules to use for inputfuncs by settings.INPUT_FUNC_MODULES.

evennia.server.inputfuncs._GA()

Return getattr(self, name).

evennia.server.inputfuncs._NA(o)[source]
evennia.server.inputfuncs._SA()

Implement setattr(self, name, value).

evennia.server.inputfuncs._on_monitor_change(**kwargs)[source]
evennia.server.inputfuncs._on_webclient_options_change(**kwargs)[source]

Called when the webclient options stored on the account changes. Inform the interested clients of this change.

evennia.server.inputfuncs._testrepeat(**kwargs)[source]

This is a test function for using with the repeat inputfunc.

Kwargs:

session (Session): Session to return to.

evennia.server.inputfuncs.bot_data_in(session, *args, **kwargs)[source]

Text input from the IRC and RSS bots. This will trigger the execute_cmd method on the bots in-game counterpart.

Parameters
  • session (Session) – The active Session to receive the input.

  • text (str) – First arg is text input. Other arguments are ignored.

evennia.server.inputfuncs.client_options(session, *args, **kwargs)[source]

This allows the client an OOB way to inform us about its name and capabilities. This will be integrated into the session settings

Kwargs:
get (bool): If this is true, return the settings as a dict

(ignore all other kwargs).

client (str): A client identifier, like “mushclient”. version (str): A client version ansi (bool): Supports ansi colors xterm256 (bool): Supports xterm256 colors or not mxp (bool): Supports MXP or not utf-8 (bool): Supports UTF-8 or not screenreader (bool): Screen-reader mode on/off mccp (bool): MCCP compression on/off screenheight (int): Screen height in lines screenwidth (int): Screen width in characters inputdebug (bool): Debug input functions nocolor (bool): Strip color raw (bool): Turn off parsing

evennia.server.inputfuncs.default(session, cmdname, *args, **kwargs)[source]

Default catch-function. This is like all other input functions except it will get cmdname as the first argument.

evennia.server.inputfuncs.echo(session, *args, **kwargs)[source]

Echo test function

evennia.server.inputfuncs.external_discord_hello(session, *args, **kwargs)[source]

Sent by Mudlet as a greeting; added here to avoid logging a missing inputfunc for it.

evennia.server.inputfuncs.get_client_options(session, *args, **kwargs)[source]

Alias wrapper for getting options.

evennia.server.inputfuncs.get_inputfuncs(session, *args, **kwargs)[source]

Get the keys of all available inputfuncs. Note that we don’t get it from this module alone since multiple modules could be added. So we get it from the sessionhandler.

evennia.server.inputfuncs.get_value(session, *args, **kwargs)[source]

Return the value of a given attribute or db_property on the session’s current account or character.

Kwargs:
name (str): Name of info value to return. Only names

in the _gettable dictionary earlier in this module are accepted.

evennia.server.inputfuncs.hello(session, *args, **kwargs)

This allows the client an OOB way to inform us about its name and capabilities. This will be integrated into the session settings

Kwargs:
get (bool): If this is true, return the settings as a dict

(ignore all other kwargs).

client (str): A client identifier, like “mushclient”. version (str): A client version ansi (bool): Supports ansi colors xterm256 (bool): Supports xterm256 colors or not mxp (bool): Supports MXP or not utf-8 (bool): Supports UTF-8 or not screenreader (bool): Screen-reader mode on/off mccp (bool): MCCP compression on/off screenheight (int): Screen height in lines screenwidth (int): Screen width in characters inputdebug (bool): Debug input functions nocolor (bool): Strip color raw (bool): Turn off parsing

evennia.server.inputfuncs.login(session, *args, **kwargs)[source]

Peform a login. This only works if session is currently not logged in. This will also automatically throttle too quick attempts.

Kwargs:

name (str): Account name password (str): Plain-text password

evennia.server.inputfuncs.monitor(session, *args, **kwargs)[source]

Adds monitoring to a given property or Attribute.

Kwargs:
name (str): The name of the property or Attribute

to report. No db_* prefix is needed. Only names in the _monitorable dict earlier in this module are accepted.

stop (bool): Stop monitoring the above name. outputfunc_name (str, optional): Change the name of

the outputfunc name. This is used e.g. by MSDP which has its own specific output format.

evennia.server.inputfuncs.monitored(session, *args, **kwargs)[source]

Report on what is being monitored

evennia.server.inputfuncs.msdp_list(session, *args, **kwargs)[source]

MSDP LIST command

evennia.server.inputfuncs.msdp_report(session, *args, **kwargs)[source]

MSDP REPORT command

evennia.server.inputfuncs.msdp_send(session, *args, **kwargs)[source]

MSDP SEND command

evennia.server.inputfuncs.msdp_unreport(session, *args, **kwargs)[source]

MSDP UNREPORT command

evennia.server.inputfuncs.repeat(session, *args, **kwargs)[source]

Call a named function repeatedly. Note that this is meant as an example of limiting the number of possible call functions.

Kwargs:
callback (str): The function to call. Only functions

from the _repeatable dictionary earlier in this module are available.

interval (int): How often to call function (s).
Defaults to once every 60 seconds with a minimum

of 5 seconds.

stop (bool): Stop a previously assigned ticker with

the above settings.

evennia.server.inputfuncs.supports_set(session, *args, **kwargs)

This allows the client an OOB way to inform us about its name and capabilities. This will be integrated into the session settings

Kwargs:
get (bool): If this is true, return the settings as a dict

(ignore all other kwargs).

client (str): A client identifier, like “mushclient”. version (str): A client version ansi (bool): Supports ansi colors xterm256 (bool): Supports xterm256 colors or not mxp (bool): Supports MXP or not utf-8 (bool): Supports UTF-8 or not screenreader (bool): Screen-reader mode on/off mccp (bool): MCCP compression on/off screenheight (int): Screen height in lines screenwidth (int): Screen width in characters inputdebug (bool): Debug input functions nocolor (bool): Strip color raw (bool): Turn off parsing

evennia.server.inputfuncs.text(session, *args, **kwargs)[source]

Main text input from the client. This will execute a command string on the server.

Parameters
  • session (Session) – The active Session to receive the input.

  • text (str) – First arg is used as text-command input. Other arguments are ignored.

evennia.server.inputfuncs.unmonitor(session, *args, **kwargs)[source]

Wrapper for turning off monitoring

evennia.server.inputfuncs.unrepeat(session, *args, **kwargs)[source]

Wrapper for OOB use

evennia.server.inputfuncs.webclient_options(session, *args, **kwargs)[source]

Handles retrieving and changing of options related to the webclient.

If kwargs is empty (or contains just a “cmdid”), the saved options will be sent back to the session. A monitor handler will be created to inform the client of any future options that changes.

If kwargs is not empty, the key/values stored in there will be persisted to the account object.

Kwargs:

<option name>: an option to save

evennia.server.manager module

Custom manager for ServerConfig objects.

class evennia.server.manager.ServerConfigManager[source]

Bases: django.db.models.manager.Manager

This ServerConfigManager implements methods for searching and manipulating ServerConfigs directly from the database.

These methods will all return database objects (or QuerySets) directly.

ServerConfigs are used to store certain persistent settings for the server at run-time.

conf(key=None, value=None, delete=False, default=None)[source]

Add, retrieve and manipulate config values.

Parameters
  • key (str, optional) – Name of config.

  • value (str, optional) – Data to store in this config value.

  • delete (bool, optional) – If True, delete config with key.

  • default (str, optional) – Use when retrieving a config value by a key that does not exist.

Returns

If key was not given - all stored config values. value (str): If key was given, this is the stored value, or

default if no matching key was found.

Return type

all (list)

evennia.server.models module

Server Configuration flags

This holds persistent server configuration flags.

Config values should usually be set through the manager’s conf() method.

class evennia.server.models.ServerConfig(*args, **kwargs)[source]

Bases: evennia.utils.idmapper.models.WeakSharedMemoryModel

On-the fly storage of global settings.

Properties defined on ServerConfig:

  • key: Main identifier

  • value: Value stored in key. This is a pickled storage.

exception DoesNotExist

Bases: django.core.exceptions.ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: django.core.exceptions.MultipleObjectsReturned

_ServerConfig__key_del()

Deleter. Allows for del self.key. Deletes entry.

_ServerConfig__key_get()

Getter. Allows for value = self.key

_ServerConfig__key_set(value)

Setter. Allows for self.key = value

_ServerConfig__value_del()

Deleter. Allows for del self.value. Deletes entry.

_ServerConfig__value_get()

Getter. Allows for value = self.value

_ServerConfig__value_set(value)

Setter. Allows for self.value = value

_is_deleted = False
_meta = <Options for ServerConfig>
db_key

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

db_value

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

id

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

property key

Getter. Allows for value = self.key

objects = <evennia.server.manager.ServerConfigManager object>
path = 'evennia.server.models.ServerConfig'
store(key, value)[source]

Wrap the storage.

Parameters
  • key (str) – The name of this store.

  • value (str) – The data to store with this key.

typename = 'WeakSharedMemoryModelBase'
property value

Getter. Allows for value = self.value

evennia.server.server module

This module implements the main Evennia server process, the core of the game engine.

This module should be started with the ‘twistd’ executable since it sets up all the networking features. (this is done automatically by evennia/server/server_runner.py).

class evennia.server.server.Evennia(application)[source]

Bases: object

The main Evennia server handler. This object sets up the database and tracks and interlinks all the twisted network services that make up evennia.

__init__(application)[source]

Setup the server.

application - an instantiated Twisted application

at_post_portal_sync(mode)[source]

This is called just after the portal has finished syncing back data to the server after reconnecting.

Parameters

mode (str) – One of reload, reset or shutdown.

at_server_cold_start()[source]

This is called only when the server starts “cold”, i.e. after a shutdown or a reset.

at_server_cold_stop()[source]

This is called only when the server goes down due to a shutdown or reset.

at_server_reload_start()[source]

This is called only when server starts back up after a reload.

at_server_reload_stop()[source]

This is called only time the server stops before a reload.

at_server_start()[source]

This is called every time the server starts up, regardless of how it was shut down.

at_server_stop()[source]

This is called just before a server is shut down, regardless of it is fore a reload, reset or shutdown.

get_info_dict()[source]

Return the server info, for display.

run_init_hooks(mode)[source]

Called by the amp client once receiving sync back from Portal

Parameters

mode (str) – One of shutdown, reload or reset

run_initial_setup()[source]

This is triggered by the amp protocol when the connection to the portal has been established. This attempts to run the initial_setup script of the server. It returns if this is not the first time the server starts. Once finished the last_initial_setup_step is set to -1.

shutdown(mode='reload', _reactor_stopping=False)[source]

Shuts down the server from inside it.

mode - sets the server restart mode.
‘reload’ - server restarts, no “persistent” scripts

are stopped, at_reload hooks called.

‘reset’ - server restarts, non-persistent scripts stopped,

at_shutdown hooks called but sessions will not be disconnected.

‘shutdown’ - like reset, but server will not auto-restart.

_reactor_stopping - this is set if server is stopped by a kill
command OR this method was already called

once - in both cases the reactor is dead/stopping already.

sqlite3_prep()[source]

Optimize some SQLite stuff at startup since we can’t save it to the database.

update_defaults()[source]

We make sure to store the most important object defaults here, so we can catch if they change and update them on-objects automatically. This allows for changing default cmdset locations and default typeclasses in the settings file and have them auto-update all already existing objects.

evennia.server.server._SA()

Implement setattr(self, name, value).

evennia.server.server._server_maintenance()[source]

This maintenance function handles repeated checks and updates that the server needs to do. It is called every minute.

evennia.server.serversession module

This defines a the Server’s generic session object. This object represents a connection to the outside world but don’t know any details about how the connection actually happens (so it’s the same for telnet, web, ssh etc).

It is stored on the Server side (as opposed to protocol-specific sessions which are stored on the Portal side)

class evennia.server.serversession.ServerSession[source]

Bases: evennia.server.session.Session

This class represents an account’s session and is a template for individual protocols to communicate with Evennia.

Each account gets a session assigned to them whenever they connect to the game server. All communication between game and account goes through their session.

_ServerSession__cmdset_storage_get()
_ServerSession__cmdset_storage_set(value)
__init__()[source]

Initiate to avoid AttributeErrors down the line

access(*args, **kwargs)[source]

Dummy method to mimic the logged-in API.

at_cmdset_get(**kwargs)[source]

A dummy hook all objects with cmdsets need to have

at_disconnect(reason=None)[source]

Hook called by sessionhandler when disconnecting this session.

at_login(account)[source]

Hook called by sessionhandler when the session becomes authenticated.

Parameters

account (Account) – The account associated with the session.

at_sync()[source]

This is called whenever a session has been resynced with the portal. At this point all relevant attributes have already been set and self.account been assigned (if applicable).

Since this is often called after a server restart we need to set up the session as it was.

attributes[source]
property cmdset_storage
data_in(**kwargs)[source]

Receiving data from the client, sending it off to the respective inputfuncs.

Kwargs:
kwargs (any): Incoming data from protocol on

the form {“commandname”: ((args), {kwargs}),…}

Notes

This method is here in order to give the user a single place to catch and possibly process all incoming data from the client. It should usually always end by sending this data off to self.sessionhandler.call_inputfuncs(self, **kwargs).

data_out(**kwargs)[source]

Sending data from Evennia->Client

Kwargs:

text (str or tuple) any (str or tuple): Send-commands identified

by their keys. Or “options”, carrying options for the protocol(s).

property db

NonDataBase). Everything stored to this is guaranteed to be cleared when a server is shutdown. Syntax is same as for the _get_db_holder() method and property, e.g. obj.ndb.attr = value etc.

Type

A non-persistent store (ndb

execute_cmd(raw_string, session=None, **kwargs)[source]

Do something as this object. This method is normally never called directly, instead incoming command instructions are sent to the appropriate inputfunc already at the sessionhandler level. This method allows Python code to inject commands into this stream, and will lead to the text inputfunc be called.

Parameters
  • raw_string (string) – Raw command input

  • session (Session) – This is here to make API consistent with Account/Object.execute_cmd. If given, data is passed to that Session, otherwise use self.

Kwargs:

Other keyword arguments will be added to the found command object instace as variables before it executes. This is unused by default Evennia but may be used to set flags and change operating paramaters for commands at run-time.

get_account()[source]

Get the account associated with this session

Returns

The associated Account.

Return type

account (Account)

get_character()

Get the in-game character associated with this session.

Returns

The puppeted object, if any.

Return type

puppet (Object)

get_client_size()[source]

Return eventual eventual width and height reported by the client. Note that this currently only deals with a single client window (windowID==0) as in a traditional telnet session.

get_puppet()[source]

Get the in-game character associated with this session.

Returns

The puppeted object, if any.

Return type

puppet (Object)

get_puppet_or_account()[source]

Get puppet or account.

Returns

The puppet if one exists,

otherwise return the account.

Return type

controller (Object or Account)

property id
log(message, channel=True)[source]

Emits session info to the appropriate outputs and info channels.

Parameters
  • message (str) – The message to log.

  • channel (bool, optional) – Log to the CHANNEL_CONNECTINFO channel in addition to the server log.

msg(text=None, **kwargs)[source]

Wrapper to mimic msg() functionality of Objects and Accounts.

Parameters

text (str) – String input.

Kwargs:
any (str or tuple): Send-commands identified

by their keys. Or “options”, carrying options for the protocol(s).

nattributes[source]
property ndb

NonDataBase). Everything stored to this is guaranteed to be cleared when a server is shutdown. Syntax is same as for the _get_db_holder() method and property, e.g. obj.ndb.attr = value etc.

Type

A non-persistent store (ndb

ndb_del()[source]

Stop accidental deletion.

ndb_get()[source]

A non-persistent store (ndb: NonDataBase). Everything stored to this is guaranteed to be cleared when a server is shutdown. Syntax is same as for the _get_db_holder() method and property, e.g. obj.ndb.attr = value etc.

ndb_set(value)[source]

Stop accidentally replacing the db object

Parameters

value (any) – A value to store in the ndb.

update_flags(**kwargs)[source]

Update the protocol_flags and sync them with Portal.

Kwargs:
key, value - A key:value pair to set in the

protocol_flags dictionary.

Notes

Since protocols can vary, no checking is done as to the existene of the flag or not. The input data should have been validated before this call.

update_session_counters(idle=False)[source]

Hit this when the user enters a command in order to update idle timers and command counters.

evennia.server.serversession._GA()

Return getattr(self, name).

evennia.server.serversession._SA()

Implement setattr(self, name, value).

evennia.server.session module

This module defines a generic session class. All connection instances (both on Portal and Server side) should inherit from this class.

class evennia.server.session.Session[source]

Bases: object

This class represents a player’s session and is a template for both portal- and server-side sessions.

Each connection will see two session instances created:

  1. A Portal session. This is customized for the respective connection protocols that Evennia supports, like Telnet, SSH etc. The Portal session must call init_session() as part of its initialization. The respective hook methods should be connected to the methods unique for the respective protocol so that there is a unified interface to Evennia.

  2. A Server session. This is the same for all connected accounts, regardless of how they connect.

The Portal and Server have their own respective sessionhandlers. These are synced whenever new connections happen or the Server restarts etc, which means much of the same information must be stored in both places e.g. the portal can re-sync with the server when the server reboots.

at_sync()[source]

Called after a session has been fully synced (including secondary operations such as setting self.account based on uid etc).

data_in(**kwargs)[source]

Hook for protocols to send incoming data to the engine.

Kwargs:

kwargs (any): Other data from the protocol.

data_out(**kwargs)[source]

Generic hook for sending data out through the protocol. Server protocols can use this right away. Portal sessions should overload this to format/handle the outgoing data as needed.

Kwargs:

kwargs (any): Other data to the protocol.

disconnect(reason=None)[source]

generic hook called from the outside to disconnect this session should be connected to the protocols actual disconnect mechanism.

Parameters

reason (str) – Eventual text motivating the disconnect.

get_sync_data()[source]

Get all data relevant to sync the session.

Parameters

syncdata (dict) – All syncdata values, based on the keys given by self._attrs_to_sync.

init_session(protocol_key, address, sessionhandler)[source]

Initialize the Session. This should be called by the protocol when a new session is established.

Parameters
  • protocol_key (str) – By default, one of ‘telnet’, ‘telnet/ssl’, ‘ssh’, ‘webclient/websocket’ or ‘webclient/ajax’.

  • address (str) – Client address.

  • sessionhandler (SessionHandler) – Reference to the main sessionhandler instance.

load_sync_data(sessdata)[source]

Takes a session dictionary, as created by get_sync_data, and loads it into the correct properties of the session.

Parameters

sessdata (dict) – Session data dictionary.

evennia.server.sessionhandler module

This module defines handlers for storing sessions when handles sessions of users connecting to the server.

There are two similar but separate stores of sessions:

  • ServerSessionHandler - this stores generic game sessions

    for the game. These sessions has no knowledge about how they are connected to the world.

  • PortalSessionHandler - this stores sessions created by

    twisted protocols. These are dumb connectors that handle network communication but holds no game info.

class evennia.server.sessionhandler.DummySession[source]

Bases: object

sessid = 0
class evennia.server.sessionhandler.ServerSessionHandler(*args, **kwargs)[source]

Bases: evennia.server.sessionhandler.SessionHandler

This object holds the stack of sessions active in the game at any time.

A session register with the handler in two steps, first by registering itself with the connect() method. This indicates an non-authenticated session. Whenever the session is authenticated the session together with the related account is sent to the login() method.

__init__(*args, **kwargs)[source]

Init the handler.

_run_cmd_login(session)[source]

Launch the CMD_LOGINSTART command. This is wrapped for delays.

account_count()[source]

Get the number of connected accounts (not sessions since a account may have more than one session depending on settings). Only logged-in accounts are counted here.

Returns

Number of connected accounts

Return type

naccount (int)

all_connected_accounts()[source]

Get a unique list of connected and logged-in Accounts.

Returns

All conected Accounts (which may be fewer than the

amount of Sessions due to multi-playing).

Return type

accounts (list)

all_sessions_portal_sync()[source]

This is called by the server when it reboots. It syncs all session data to the portal. Returns a deferred!

announce_all(message)[source]

Send message to all connected sessions

Parameters

message (str) – Message to send.

call_inputfuncs(session, **kwargs)[source]

Split incoming data into its inputfunc counterparts. This should be called by the serversession.data_in as sessionhandler.call_inputfunc(self, **kwargs).

We also intercept OOB communication here.

Parameters

sessions (Session) – Session.

Kwargs:
kwargs (any): Incoming data from protocol on

the form {“commandname”: ((args), {kwargs}),…}

data_in(session, **kwargs)[source]

We let the data take a “detour” to session.data_in so the user can override and see it all in one place. That method is responsible to in turn always call this class’ sessionhandler.call_inputfunc with the (possibly processed) data.

data_out(session, **kwargs)[source]

Sending data Server -> Portal

Parameters
  • session (Session) – Session to relay to.

  • text (str, optional) – text data to return

Notes

The outdata will be scrubbed for sending across the wire here.

disconnect(session, reason='', sync_portal=True)[source]

Called from server side to remove session and inform portal of this fact.

Parameters
  • session (Session) – The Session to disconnect.

  • reason (str, optional) – A motivation for the disconnect.

  • sync_portal (bool, optional) – Sync the disconnect to Portal side. This should be done unless this was called by self.portal_disconnect().

disconnect_all_sessions(reason='You have been disconnected.')[source]

Cleanly disconnect all of the connected sessions.

Parameters

reason (str, optional) – The reason for the disconnection.

disconnect_duplicate_sessions(curr_session, reason='Logged in from elsewhere. Disconnecting.')[source]

Disconnects any existing sessions with the same user.

Parameters
  • curr_session (Session) – Disconnect all Sessions matching this one.

  • reason (str, optional) – A motivation for disconnecting.

get_inputfuncs()[source]

Get all registered inputfuncs (access function)

Returns

A dict of {key:inputfunc,…}

Return type

inputfuncs (dict)

login(session, account, force=False, testmode=False)[source]

Log in the previously unloggedin session and the account we by now should know is connected to it. After this point we assume the session to be logged in one way or another.

Parameters
  • session (Session) – The Session to authenticate.

  • account (Account) – The Account identified as associated with this Session.

  • force (bool) – Login also if the session thinks it’s already logged in (this can happen for auto-authenticating protocols)

  • testmode (bool, optional) – This is used by unittesting for faking login without any AMP being actually active.

portal_connect(portalsessiondata)[source]

Called by Portal when a new session has connected. Creates a new, unlogged-in game session.

Parameters

portalsessiondata (dict) – a dictionary of all property:value keys defining the session and which is marked to be synced.

portal_disconnect(session)[source]

Called from Portal when Portal session closed from the portal side. There is no message to report in this case.

Parameters

session (Session) – The Session to disconnect

portal_disconnect_all()[source]

Called from Portal when Portal is closing down. All Sessions should die. The Portal should not be informed.

portal_reset_server()[source]

Called by server when reloading. We tell the portal to start a new server instance.

portal_restart_server()[source]

Called by server when reloading. We tell the portal to start a new server instance.

portal_session_sync(portalsessiondata)[source]

Called by Portal when it wants to update a single session (e.g. because of all negotiation protocols have finally replied)

Parameters

portalsessiondata (dict) – a dictionary of all property:value keys defining the session and which is marked to be synced.

portal_sessions_sync(portalsessionsdata)[source]

Syncing all session ids of the portal with the ones of the server. This is instantiated by the portal when reconnecting.

Parameters

portalsessionsdata (dict) – A dictionary {sessid: {property:value},…} defining each session and the properties in it which should be synced.

portal_shutdown()[source]

Called by server when it’s time to shut down (the portal will shut us down and then shut itself down)

session_from_account(account, sessid)[source]

Given an account and a session id, return the actual session object.

Parameters
  • account (Account) – The Account to get the Session from.

  • sessid (int or list) – Session id(s).

Returns

Session(s) found.

Return type

sessions (Session or list)

session_from_sessid(sessid)[source]

Get session based on sessid, or None if not found

Parameters

sessid (int or list) – Session id(s).

Returns

Session(s) found. This

is a list if input was a list.

Return type

sessions (Session or list)

session_portal_partial_sync(session_data)[source]

Call to make a partial update of the session, such as only a particular property.

Parameters

session_data (dict) – Store {sessid: {property:value}, …} defining one or more sessions in detail.

session_portal_sync(session)[source]

This is called by the server when it wants to sync a single session with the Portal for whatever reason. Returns a deferred!

sessions_from_account(account)[source]

Given an account, return all matching sessions.

Parameters

account (Account) – Account to get sessions from.

Returns

All Sessions associated with this account.

Return type

sessions (list)

sessions_from_character(puppet)

Given a puppeted object, return all controlling sessions.

Parameters

puppet (Object) – Object puppeted

Returns.
sessions (Session or list): Can be more than one of Object is controlled by

more than one Session (MULTISESSION_MODE > 1).

sessions_from_csessid(csessid)[source]

Given a client identification hash (for session types that offer them) return all sessions with a matching hash.

Args

csessid (str): The session hash.

Returns

The sessions with matching .csessid, if any.

Return type

sessions (list)

sessions_from_puppet(puppet)[source]

Given a puppeted object, return all controlling sessions.

Parameters

puppet (Object) – Object puppeted

Returns.
sessions (Session or list): Can be more than one of Object is controlled by

more than one Session (MULTISESSION_MODE > 1).

start_bot_session(protocol_path, configdict)[source]

This method allows the server-side to force the Portal to create a new bot session.

Parameters
  • protocol_path (str) – The full python path to the bot’s class.

  • configdict (dict) – This dict will be used to configure the bot (this depends on the bot protocol).

Examples

start_bot_session(“evennia.server.portal.irc.IRCClient”,
{“uid”:1, “botname”:”evbot”, “channel”:”#evennia”,

“network:”irc.freenode.net”, “port”: 6667})

Notes

The new session will use the supplied account-bot uid to initiate an already logged-in connection. The Portal will treat this as a normal connection and henceforth so will the Server.

validate_sessions()[source]

Check all currently connected sessions (logged in and not) and see if any are dead or idle.

class evennia.server.sessionhandler.SessionHandler[source]

Bases: dict

This handler holds a stack of sessions.

clean_senddata(session, kwargs)[source]

Clean up data for sending across the AMP wire. Also apply INLINEFUNCS.

Parameters
  • session (Session) – The relevant session instance.

  • kwargs (dict) –

    send-instruction, with the keyword itself being the name of the instruction (like “text”). Suitable values for each keyword are:

    • arg -> [[arg], {}]

    • [args] -> [[args], {}]

    • {kwargs} -> [[], {kwargs}]

    • [args, {kwargs}] -> [[arg], {kwargs}]

    • [[args], {kwargs}] -> [[args], {kwargs}]

Returns

A cleaned dictionary of cmdname:[[args],{kwargs}] pairs,

where the keys, args and kwargs have all been converted to send-safe entities (strings or numbers), and inlinefuncs have been applied.

Return type

kwargs (dict)

get(key, default=None)[source]

Clean out None-sessions automatically.

get_all_sync_data()[source]

Create a dictionary of sessdata dicts representing all sessions in store.

Returns

A dict of sync data.

Return type

syncdata (dict)

get_sessions(include_unloggedin=False)[source]

Returns the connected session objects.

Parameters

include_unloggedin (bool, optional) – Also list Sessions that have not yet authenticated.

Returns

A list of Session objects.

Return type

sessions (list)

evennia.server.sessionhandler._SESSION_HANDLER_CLASS

alias of evennia.server.sessionhandler.ServerSessionHandler

evennia.server.sessionhandler.delayed_import()[source]

Helper method for delayed import of all needed entities.

evennia.server.signals module

This module brings Django Signals into Evennia. These are events that can be subscribed to by importing a given Signal and using the following code.

THIS_SIGNAL.connect(callback, sender_object)

When other code calls THIS_SIGNAL.send(sender, **kwargs), the callback will be triggered.

Callbacks must be in the following format:

def my_callback(sender, **kwargs):

This is used on top of hooks to make certain features easier to add to contribs without necessitating a full takeover of hooks that may be in high demand.

evennia.server.throttle module

class evennia.server.throttle.Throttle(**kwargs)[source]

Bases: object

Keeps a running count of failed actions per IP address.

Available methods indicate whether or not the number of failures exceeds a particular threshold.

This version of the throttle is usable by both the terminal server as well as the web server, imposes limits on memory consumption by using deques with length limits instead of open-ended lists, and removes sparse keys when no recent failures have been recorded.

__init__(**kwargs)[source]

Allows setting of throttle parameters.

Kwargs:

limit (int): Max number of failures before imposing limiter timeout (int): number of timeout seconds after

max number of tries has been reached.

cache_size (int): Max number of attempts to record per IP within a

rolling window; this is NOT the same as the limit after which the throttle is imposed!

check(ip)[source]

This will check the session’s address against the storage dictionary to check they haven’t spammed too many fails recently.

Parameters

ip (str) – IP address of requestor

Returns

True if throttling is active,

False otherwise.

Return type

throttled (bool)

error_msg = 'Too many failed attempts; you must wait a few minutes before trying again.'
get(ip=None)[source]

Convenience function that returns the storage table, or part of.

Parameters

ip (str, optional) – IP address of requestor

Returns

When no IP is provided, returns a dict of all

current IPs being tracked and the timestamps of their recent failures.

timestamps (deque): When an IP is provided, returns a deque of

timestamps of recent failures only for that IP.

Return type

storage (dict)

update(ip, failmsg='Exceeded threshold.')[source]

Store the time of the latest failure.

Parameters
  • ip (str) – IP address of requestor

  • failmsg (str, optional) – Message to display in logs upon activation of throttle.

Returns

None

evennia.server.validators module

class evennia.server.validators.EvenniaPasswordValidator(regex="^[\w. @+\-',]+$", policy="Password should contain a mix of letters, spaces, digits and @/./+/-/_/'/, only.")[source]

Bases: object

__init__(regex="^[\\w. @+\\-',]+$", policy="Password should contain a mix of letters, spaces, digits and @/./+/-/_/'/, only.")[source]

Constructs a standard Django password validator.

Parameters
  • regex (str) – Regex pattern of valid characters to allow.

  • policy (str) – Brief explanation of what the defined regex permits.

get_help_text()[source]

Returns a user-facing explanation of the password policy defined by this validator.

Returns

Explanation of password policy.

Return type

text (str)

validate(password, user=None)[source]

Validates a password string to make sure it meets predefined Evennia acceptable character policy.

Parameters
  • password (str) – Password to validate

  • user (None) – Unused argument but required by Django

Returns

None if password successfully validated,

raises ValidationError otherwise.

Return type

None (None)

class evennia.server.validators.EvenniaUsernameAvailabilityValidator[source]

Bases: object

Checks to make sure a given username is not taken or otherwise reserved.

evennia.server.webserver module

This implements resources for Twisted webservers using the WSGI interface of Django. This alleviates the need of running e.g. an Apache server to serve Evennia’s web presence (although you could do that too if desired).

The actual servers are started inside server.py as part of the Evennia application.

(Lots of thanks to http://github.com/clemesha/twisted-wsgi-django for a great example/aid on how to do this.)

class evennia.server.webserver.DjangoWebRoot(pool)[source]

Bases: twisted.web.resource.Resource

This creates a web root (/) that Django understands by tweaking the way child instances are recognized.

__init__(pool)[source]

Setup the django+twisted resource.

Parameters

pool (ThreadPool) – The twisted threadpool.

_decrement_requests(*args, **kwargs)[source]
empty_threadpool()[source]

Converts our _pending_requests list of deferreds into a DeferredList

Returns

Contains all deferreds of pending requests.

Return type

deflist (DeferredList)

getChild(path, request)[source]

To make things work we nudge the url tree to make this the root.

Parameters
  • path (str) – Url path.

  • request (Request object) – Incoming request.

Notes

We make sure to save the request queue so that we can safely kill the threadpool on a server reload.

class evennia.server.webserver.EvenniaReverseProxyResource(host, port, path, reactor=<twisted.internet.epollreactor.EPollReactor object>)[source]

Bases: twisted.web.proxy.ReverseProxyResource

getChild(path, request)[source]

Create and return a proxy resource with the same proxy configuration as this one, except that its path also contains the segment given by path at the end.

Parameters
  • path (str) – Url path.

  • request (Request object) – Incoming request.

Returns

A proxy resource.

Return type

resource (EvenniaReverseProxyResource)

render(request)[source]

Render a request by forwarding it to the proxied server.

Parameters

request (Request) – Incoming request.

Returns

Indicator to note request not yet finished.

Return type

not_done (char)

class evennia.server.webserver.HTTPChannelWithXForwardedFor[source]

Bases: twisted.web.http.HTTPChannel

HTTP xforward class

allHeadersReceived()[source]

Check to see if this is a reverse proxied connection.

class evennia.server.webserver.LockableThreadPool(*args, **kwargs)[source]

Bases: twisted.python.threadpool.ThreadPool

Threadpool that can be locked from accepting new requests.

__init__(*args, **kwargs)[source]

Create a new threadpool.

@param minthreads: minimum number of threads in the pool @type minthreads: L{int}

@param maxthreads: maximum number of threads in the pool @type maxthreads: L{int}

@param name: The name to give this threadpool; visible in log messages. @type name: native L{str}

callInThread(func, *args, **kwargs)[source]

called in the main reactor thread. Makes sure the pool is not locked before continuing.

lock()[source]
class evennia.server.webserver.PrivateStaticRoot(path, defaultType='text/html', ignoredExts=(), registry=None, allowExt=0)[source]

Bases: twisted.web.static.File

This overrides the default static file resource so as to not make the directory listings public (that is, if you go to /media or /static you won’t see an index of all static/media files on the server).

directoryListing()[source]

Return a resource that generates an HTML listing of the directory this path represents.

@return: A resource that renders the directory to HTML. @rtype: L{DirectoryLister}

class evennia.server.webserver.WSGIWebServer(pool, *args, **kwargs)[source]

Bases: twisted.application.internet.TCPServer

This is a WSGI webserver. It makes sure to start the threadpool after the service itself started, so as to register correctly with the twisted daemon.

call with WSGIWebServer(threadpool, port, wsgi_resource)

__init__(pool, *args, **kwargs)[source]

This just stores the threadpool.

Parameters
  • pool (ThreadPool) – The twisted threadpool.

  • kwargs (args,) – Passed on to the TCPServer.

startService()[source]

Start the pool after the service starts.

stopService()[source]

Safely stop the pool after the service stops.

class evennia.server.webserver.Website(resource, requestFactory=None, *args, **kwargs)[source]

Bases: twisted.web.server.Site

This class will only log http requests if settings.DEBUG is True.

log(request)[source]

Conditional logging

logPrefix()[source]

How to be named in logs

noisy = False