Aliasing API

So you want to write aliases for your commonly used commands - cool! This cheatsheet details some of the nitty-gritty syntactical shenanigans that you can use to make your aliases very powerful.

When placed inline in an alias, any syntax in the syntax table will have the listed effect. For a list of built-in cvars, see the Cvar Table.

For a list of user-created aliases, plus help aliasing, join the Avrae Discord!

Draconic

The language used in Avrae aliases is a custom modified version of Python, called Draconic. In most cases, Draconic uses the same syntax and base types as Python - any exceptions will be documented here!

Note

It is highly recommended to be familiar with the Python language before diving into Draconic, as the two use the same syntax and types.

As Draconic is meant to both be an operational and templating language, there are multiple ways to use Draconic inside your alias.

Syntax

This section details the special syntax used in the Draconic language. Note that these syntaxes are only evaluated in an alias, the test command, or the tembed command.

Rolls

Syntax: {diceexpr}

Description: Rolls the expression inside the curly braces and is replaced by the result. If an error occurs, is replaced by 0. Variables are allowed inside the expression.

Examples

>>> !test Rolling 1d20: {1d20}
Rolling 1d20: 7
>>> !test Strength check: {1d20 + strengthMod}
Strength check: 21

Values

Syntax: <var>

Description: Replaced by the value of the variable, implicitly cast to str. The variable can be a user variable, character variable, or a local variable set in a Draconic script.

Examples

>>> !test My strength modifier is: <strengthMod>
My strength modifier is: 2

Draconic Expressions

Syntax: {{code}}

Description: Runs the Draconic code inside the braces and is replaced by the value the code evaluates to. If the code evaluates to None, is removed from the output, otherwise it is cast to str.

See below for a list of builtin Draconic functions.

Examples

>>> !test 1 more than my strength score is {{strength + 1}}!
1 more than my strength score is 15!
>>> !test My roll was {{"greater than" if roll("1d20") > 10 else "less than"}} 10!
My roll was less than 10!

Draconic Blocks

Syntax

<drac2>
code
</drac2>

Description: Runs the multi-line Draconic code between the delimiters. If a non-None value is returned (via the return keyword), is replaced by the returned value, cast to str.

Examples

>>> !test <drac2>
... out = []
... for i in range(5):
...   out.append(i * 2)
...   if i == 2:
...     break
... return out
... </drac2>
[0, 2, 4]
>>> !test <drac2>
... out = []
... for stat in ['strength', 'dexterity', 'constitution']:
...   out.append(get(stat))
... </drac2>
... My STR, DEX, and CON scores are {{out}}!
My STR, DEX, and CON scores are [12, 18, 14]!

Argument Parsing

Often times when writing aliases, you will need to access user input. These special strings will be replaced with user arguments (if applicable)!

Non-Code, Space-Aware

Syntax: %1%, %2%, …, %N%

Description: Replaced with the Nth argument passed to the alias. If the argument contains spaces, the replacement will contain quotes around the argument.

Non-Code, Preserving All

Syntax: %*%

Description: Replaced with the unmodified string following the alias.

In Code, Quote-Escaping

Syntax: &1&, &2&, etc.

Description: Replaced with the Nth argument passed to the alias. If the argument contains spaces, the replacement will not contain quotes around the argument. Additionally, any quotes in the argument will be backslash-escaped.

In Code, Quote-Escaping All

Syntax: &*&

Description: Replaced with the string following the alias. Any quotes will be backslash-escaped.

In Code, List Literal

Syntax: &ARGS&

Description: Replaced with a list representation of all arguments - usually you’ll want to put this in Draconic code.

Examples

>>> !alias asdf echo %2% %1%
>>> !asdf first "second arg"
"second arg" first
>>> !alias asdf echo %*% first
>>> !asdf second "third word"
second "third word" first
>>> !alias asdf echo &1& was the first arg
>>> !asdf "hello world"
hello world was the first arg
>>> !alias asdf echo &*& words
>>> !asdf second "third word"
second \"third word\" words
>>> !alias asdf echo &ARGS&
>>> !asdf first "second arg"
['first', 'second arg']

Cvar Table

This table lists the available cvars when a character is active.

Name

Description

Type

charisma

Charisma score.

int

charismaMod

Charisma modifier.

int

charismaSave

Charisma saving throw modifier.

int

constitution

Constitution score.

int

constitutionMod

Constitution modifier.

int

constitutionSave

Constitution saving throw modifier.

int

dexterity

Dexterity score.

int

dexterityMod

Dexterity modifier.

int

dexteritySave

Dexterity saving throw modifier.

int

intelligence

Intelligence score.

int

intelligenceMod

Intelligence modifier.

int

intelligenceSave

Intelligence saving throw modifier.

int

strength

Strength score.

int

strengthMod

Strength modifier.

int

strengthSave

Strength saving throw modifier.

int

wisdom

Wisdom score.

int

wisdomMod

Wisdom modifier.

int

wisdomSave

Wisdom saving throw modifier.

int

armor

Armor Class.

int

color

The CSettings color for the character

str

description

Full character description.

str

hp

Maximum hit points.

int

image

Character image URL.

str

level

Character level.

int

name

The character’s name.

str

proficiencyBonus

Proficiency bonus.

int

spell

The character’s spellcasting ability mod.

int

XLevel

How many levels a character has in class X.

int

Note

XLevel is not guaranteed to exist for any given X, and may not exist for GSheet 1.3/1.4 characters. It is recommended to use AliasCharacter.levels.get() to access arbitrary levels instead.

Function Reference

Warning

It may be possible to corrupt your character data by incorrectly calling functions. Script at your own risk.

Python Builtins

abs(x)

Takes a number (float or int) and returns the absolute value of that number.

Parameters

x (float or int) – The number to find the absolute value of.

Returns

The absolute value of x.

Return type

float or int

all(iterable)

Return True if all elements of the iterable are true, or if the iterable is empty.

any(iterable)

Return True if any element of the iterable is true. If the iterable is empty, return False.

ceil(x)

Rounds a number up to the nearest integer. See math.ceil().

Parameters

x (float or int) – The number to round.

Returns

The smallest integer >= x.

Return type

int

enumerate(x)

Returns a iterable of tuples containing a count and the values from the iterable.

Parameters

x (iterable) – The value to convert.

Returns

enumerate of count and objects.

Return type

iterable[tuple[int, any]]

float(x)

Converts x to a floating point number.

Parameters

x (str, int, or float) – The value to convert.

Returns

The float.

Return type

float

floor(x)

Rounds a number down to the nearest integer. See math.floor().

Parameters

x (float or int) – The number to round.

Returns

The largest integer <= x.

Return type

int

int(x)

Converts x to an integer.

Parameters

x (str, int, or float) – The value to convert.

Returns

The integer.

Return type

int

len(s)

Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

Returns

The length of the argument.

Return type

int

max(iterable, *[, key, default])
max(arg1, arg2, *args[, key])

Return the largest item in an iterable or the largest of two or more arguments.

If one positional argument is provided, it should be an iterable. The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.

There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised.

If multiple items are maximal, the function returns the first one encountered.

min(iterable, *[, key, default])
min(arg1, arg2, *args[, key])

Return the smallest item in an iterable or the smallest of two or more arguments.

If one positional argument is provided, it should be an iterable. The smallest item in the iterable is returned. If two or more positional arguments are provided, the smallest of the positional arguments is returned.

There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised.

If multiple items are minimal, the function returns the first one encountered.

range(stop)
range(start, stop[, step])

Returns a list of numbers in the specified range.

If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. If step is zero, ValueError is raised.

For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.

For a negative step, the contents of the range are still determined by the formula r[i] = start + step*i, but the constraints are i >= 0 and r[i] > stop.

A range object will be empty if r[0] does not meet the value constraint. Ranges do support negative indices, but these are interpreted as indexing from the end of the sequence determined by the positive indices.

Parameters
  • start (int) – The start of the range (inclusive).

  • stop (int) – The end of the range (exclusive).

  • step (int) – The step value.

Returns

The range of numbers.

Return type

list

round(number[, ndigits])

Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.

Parameters
  • number (float or int) – The number to round.

  • ndigits (int) – The number of digits after the decimal point to keep.

Returns

The rounded number.

Return type

float

sqrt(x)

See math.sqrt().

Returns

The square root of x.

Return type

float

str(x)

Converts x to a string.

Parameters

x (Any) – The value to convert.

Returns

The string.

Return type

str

sum(iterable[, start])

Sums start and the items of an iterable from left to right and returns the total. start defaults to 0. The iterable’s items are normally numbers, and the start value is not allowed to be a string.

time()

Return the time in seconds since the UNIX epoch (Jan 1, 1970, midnight UTC) as a floating point number. See time.time().

Returns

The epoch time.

Return type

float

Draconic Functions

argparse(args, parse_ephem=True)

Given an argument string or list, returns the parsed arguments using the argument nondeterministic finite automaton.

If parse_ephem is False, arguments like -d1 are saved literally rather than as an ephemeral argument.

Note

Arguments must begin with a letter and not end with a number (e.g. d, e12s, a!!). Values immediately following a flag argument (i.e. one that starts with -) will not be parsed as arguments unless they are also a flag argument.

There are three exceptions to this rule: -i, -h, and -v, none of which take additional values.

Parameters
  • args – A list or string of arguments.

  • parse_ephem (bool) – Whether to treat args like -d1 as ephemeral arguments or literal ones.

Returns

The parsed arguments

Return type

ParsedArguments()

>>> args = argparse("adv -rr 2 -b 1d4[bless]")
>>> args.adv()
1
>>> args.last('rr')
'2'
>>> args.get('b')
['1d4[bless]']
character()

Returns the active character if one is. Otherwise, raises a FunctionRequiresCharacter error.

Return type

AliasCharacter

combat()

Returns the combat active in the channel if one is. Otherwise, returns None.

Return type

SimpleCombat

Note

If called outside of a character context, combat().me will be None.

ctx

The context the alias was invoked in. See AliasContext for more details.

Note that this is an automatically bound name and not a function.

Type

AliasContext

delete_uvar(name)

Deletes a user variable. Does nothing if the variable does not exist.

Parameters

name (str) – The name of the variable to delete.

load_yaml(self, yamlstr)

Loads an object from a YAML string. See yaml.safe_load.

dump_yaml(self, obj, indent=2)

Serializes an object to a YAML string. See yaml.safe_dump.

load_json(self, jsonstr)

Loads an object from a JSON string. See json.loads().

dump_json(self, obj)

Serializes an object to a JSON string. See json.dumps().

err(reason, pm_user=False)

Stops evaluation of an alias and shows the user an error.

Parameters
  • reason (str) – The error to show.

  • pm_user (bool) – Whether or not to PM the user the error traceback.

Raises

AliasException

exists(name)

Returns whether or not a name is set in the current evaluation context.

Return type

bool

get(name, default=None)

Gets the value of a name, or returns default if the name is not set.

Retrieves names in the order of local > cvar > uvar. Does not interact with svars.

Parameters
  • name (str) – The name to retrieve.

  • default – What to return if the name is not set.

get_gvar(address)

Retrieves and returns the value of a gvar (global variable).

Parameters

address (str) – The gvar address.

Returns

The value of the gvar.

Return type

str

get_svar(name)

Retrieves and returns the value of a svar (server variable).

Parameters
  • name (str) – The name of the svar.

  • default – What to return if the name is not set.

Returns

The value of the svar, or the default value if it does not exist.

Return type

str or None

get_uvars()

Retrieves and returns the dict of uvars.

Returns

A dict of all uvars.

Return type

dict

get_uvar()

Retrieves and returns the value of a uvar (user variable).

Parameters
  • name (str) – The name of the uvar.

  • default – What to return if the name is not set.

Returns

The value of the uvar, or the default value if it does not exist.

Return type

str or None

randint(stop)
randint(start, stop[, step])

Returns a random integer in the range [start..stop).

If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. If step is zero, ValueError is raised.

For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.

For a negative step, the contents of the range are still determined by the formula r[i] = start + step*i, but the constraints are i >= 0 and r[i] > stop.

Parameters
  • start (int) – The lower limit (inclusive).

  • stop (int) – The upper limit (non-inclusive).

  • step (int) – The step value.

Returns

A random integer.

Return type

int

randchoice(seq)

Returns a random item from seq.

Parameters

seq (iterable.) – The itterable to choose a random item from.

Returns

A random item from the iterable.

Return type

Any.

randchoices(population, weights=None, cum_weights=None, k=1)

Returns a list of random items from population of k length with either weighted or cumulatively weighted odds. The weights [2,1,1] are equal to cum_weights [2,3,4]. If no weights or cum_weights are input, the items in population will have equal odds of being chosen. If no k is input, the output length will be 1.

Parameters
  • population (iterable.) – The itterable to choose random items from.

  • weights (list of ints) – The odds for each item in the population iterable.

  • cum_weights (list of ints) – The cumulative odds for each item in the population itterable.

  • k (int) – The length of the output.

Returns

A list of random items from the iterable.

Return type

list

roll(dice)

Rolls dice and returns the total.

Parameters

dice (str) – The dice to roll.

Returns

The roll’s total, or 0 if an error was encountered.

Return type

int

set_uvar(name, value)

Sets a user variable.

Parameters
  • name (str) – The name of the variable to set.

  • value (str) – The value to set it to.

set_uvar_nx(name, value)

Sets a user variable if there is not already an existing name.

Parameters
  • name (str) – The name of the variable to set.

  • value (str) – The value to set it to.

signature(data=0)

Returns a unique signature encoding the time the alias was invoked, the channel it was invoked in, the invoker, the id of the workshop collection the alias originates from (if applicable), and whether the caller was a personal/server alias/snippet.

This signature is signed with a secret that guarantees that valid signatures cannot be spoofed; use this when it is necessary to audit the invocations of an alias (e.g. to ensure that a server version of the alias is being used over a personal version).

Use verify_signature() in a separate alias to verify the integrity of a generated signature and unpack the encoded data.

Parameters

data (int) – Some user-supplied data to encode in the signature. This must be an unsigned integer that fits within 5 bits (i.e. a value [0..31]). Default 0.

Return type

str

verify_signature(data)

Verifies that a given signature is valid. The signature should have been generated by signature().

If the signature is not valid, raises a ValueError. Otherwise, returns a dict with the following keys representing the context the given signature was generated in:

{
    "message_id": int,
    "channel_id": int,
    "author_id": int,
    "timestamp": float,
    "workshop_collection_id": str?,  # None if the caller was not a workshop object
    "scope": str,  # one of UNKNOWN, PERSONAL_ALIAS, SERVER_ALIAS, PERSONAL_SNIPPET, SERVER_SNIPPET, COMMAND_TEST
    "user_data": int,
    "guild_id": int?,  # may be None
    "guild": AliasGuild?,  # may be None
    "channel": AliasChannel?,  # may be None
    "author": AliasAuthor?,  # may be None
}
Parameters

data (str) – The signature to verify.

Return type

dict

If you are building your own application and want to verify these signatures yourself, we provide an API endpoint you can use to verify signatures!

Below is an example of Python code to verify a signature using the httpx (requests-like) library:

signature = "Dc3SEuDEMKIJZ0qbasAAAQKZ2xjlQgAAAAAAAAAAAAAAAAAABQ==.B5RLdufsD9utKaDou+94LEfOgpA="
async with httpx.AsyncClient() as client:
    r = await client.post(
        "https://api.avrae.io/bot/signature/verify",
        json={"signature": signature}
    )
print(r.json(indent=2))

The endpoint’s response model is the same as verify_signature() sans the guild, channel, and author keys (IDs are still present).

typeof(inst)

Returns the name of the type of an object.

Parameters

inst – The object to find the type of.

Returns

The type of the object.

Return type

str

using(self, **imports)

Imports Draconic global variables as modules in the current namespace. See Using Imports for details.

Usually this should be the first statement in a code block if imports are used.

Warning

Only import modules from trusted sources! The entire contents of an imported module is executed once upon import, and can do bad things like delete all of your variables.

>>> using(
...     hello="50943a96-381b-427e-adb9-eea8ebf61f27"
... )
>>> hello.hello()
"Hello world!"
uvar_exists(name)

Returns whether a uvar exists.

Return type

bool

vroll(rollStr, multiply=1, add=0)

Rolls dice and returns a detailed roll result.

Parameters
  • dice (str) – The dice to roll.

  • multiply (int) – How many times to multiply each set of dice by.

  • add (int) – How many dice to add to each set of dice.

Returns

The result of the roll.

Return type

SimpleRollResult

parse_coins(args: str) dict

Parses a coin string into a representation of each currency. If the user input is a decimal number, assumes gold pieces. Otherwise, allows the user to specify currencies in the form ‘+1gp -2sp 3cp’

Parameters
  • args (str) – The coin string to parse

  • include_total (bool) – Whether to include the “total” key

Returns

A dict of the coin changes, e.g. {"pp":0, "gp":1, "ep":0, "sp":-2, "cp":3, "total": 0.83}

Return type

dict

Variable Scopes

In addition to Python’s normal variable scoping rules, Avrae introduces 4 new scopes in the form of character variables, user variables, server variables, and global variables. The intended purpose and binding rules of each are detailed below.

Variable Type

Read

Write

Binding

Scope

Who

Cvar

Yes

Yes

Implicit

Character

User

Uvar

Yes

Yes

Implicit

User

User

Svar

Yes

No

Explicit

Server

Anyone on server

Gvar

Yes

No

Explicit

Everywhere

Anyone

Init Metadata

Yes

Yes

Explicit

Initiative

Anyone in channel

Character Variables

aka cvars

Character variables are variables bound to a character. These are usually used to set character-specific defaults or options for aliases and snippets (e.g. a character’s familiar type/name). When running an alias or snippet, cvars are implicitly bound as local variables in the runtime at the runtime’s instantiation.

Cvars can be written or deleted in Draconic using AliasCharacter.set_cvar() and AliasCharacter.delete_cvar(), respectively.

All characters contain some built-in character variables (see Cvar Table). These cannot be overwritten.

User Variables

aka uvars

User variables are bound per Discord user, and will go with you regardless of what server or character you are on. These variables are usually used for user-specific options (e.g. a user’s timezone, favorite color, etc.). When running an alias or snippet, uvars are implicitly bound as local variables in the runtime at the runtime’s instantiation. If a cvar and uvar have the same name, the cvar takes priority.

Uvars can be written or deleted in Draconic using set_uvar() or delete_uvar(), respectively.

Server Variables

aka svars

Server variables are named variables bound per Discord server, and can only be accessed in the Discord server they are bound in. These variables are usually used for server-specific options for server aliases (e.g. stat rolling methods, server calendar, etc.). Unlike cvars and uvars, svars must be explicitly retrieved in an alias by calling get_svar(). Svars can be listed and read by anyone on the server, so be careful what data you store!

Svars can only be written or deleted using !svar <name> <value> and !svar delete <name>, respectively. These commands can only be issued by a member who has Administrator Discord permissions or a Discord role named “Server Aliaser” or “Dragonspeaker”.

Global Variables

aka gvars

Global variables are uniquely named variables that are accessible by anyone, anywhere in Avrae. These variables are usually used for storing large amounts of read-only data (e.g. an alias’ help message, a JSON file containing cards, etc.). These variables are automatically assigned a unique name on creation (in the form of a 36 character UUID), and must be explicitly retrieved in an alias by calling get_gvar(). Gvars can be read by anyone, so be careful what data you store!

Gvars can only be created using !gvar create <value>, and by default can only be edited by its creator. See !help gvar for more information.

Honorable Mention: Initiative Metadata

Initiative metadata is a form of key-value pair storage attached to an ongoing initiative in a given channel. This storage is usually used for storing a medium-sized amount of programmatic information about an ongoing initiative (e.g. an alias’ metadata on each combatant).

Metadata can be created, retrieved, and deleted using the SimpleCombat.set_metadata(), SimpleCombat.get_metadata(), and SimpleCombat.delete_metadata() methods, respectively.

Using Imports

Imports are a way for alias authors to share common code across multiple aliases, provide common libraries of code for other authors to write code compatible with your alias, and more!

If you already have the address of a module to import, use using() at the top of your code block in order to import the module into your namespace. For example:

!alias hello-world echo <drac2>
using(
    hello="50943a96-381b-427e-adb9-eea8ebf61f27"
)
return hello.hello()
</drac2>

Use !gvar 50943a96-381b-427e-adb9-eea8ebf61f27 to take a peek at the hello module!

You can also import multiple modules in the same expression:

!alias hello-world echo <drac2>
using(
    hello="50943a96-381b-427e-adb9-eea8ebf61f27",
    hello_utils="0bbddb9f-c86f-4af8-9e04-1964425b1554"
)
return f"{hello.hello('you')}\n{hello_utils.hello_to_my_character()}"
</drac2>

The hello_utils module (!gvar 0bbddb9f-c86f-4af8-9e04-1964425b1554) also demonstrates how modules can import other modules!

Each imported module is bound to a namespace that contains each of the names (constants, functions, etc) defined in the module. For example, the hello module (50943a96-381b-427e-adb9-eea8ebf61f27) defines the HELLO_WORLD constant and hello() function, so a consumer could access these with hello.HELLO_WORLD and hello.hello(), respectively.

Warning

Only import modules from trusted sources! The entire contents of an imported module is executed once upon import, and can do bad things like delete all of your variables.

All gvar modules are open-source by default, so it is encouraged to view the imported module using !gvar.

Note

Modules do not have access to the argument parsing special syntax (i.e. &ARGS&, %1%, etc), and the variables listed in the Cvar Table are not implicitly bound in a module’s execution.

Writing Modules

Modules are easy to publish and update! Simply create a gvar that contains valid Draconic code (without wrapping it in any delimiters such as <drac2>).

We encourage modules to follow the following format to make them easy to read:

# recommended_module_name
# This is a short description about what the module does.
#
# SOME_CONSTANT: some documentation about what this constant is
# some_function(show, the, args): some short documentation about what this function does
#     and how to call it
#     wow, this is long! use indentation if you need multiple lines
#     but otherwise longer documentation should go in the function's """docstring"""

SOME_CONSTANT = 3.141592

def some_function(show, the, args):
    """Here is where the longer documentation about the function can go."""
    pass

Use !gvar 50943a96-381b-427e-adb9-eea8ebf61f27 and !gvar 0bbddb9f-c86f-4af8-9e04-1964425b1554 to view the hello and hello_utils example modules used above for an example!

Note

Because all gvars are public to anyone who knows the address, modules are open-source by default.

Catching Exceptions

Draconic supports a modified version of Python’s exception handling (“try-except”) syntax, the most significant difference being that exceptions must be caught explicitly by passing the exact name of the exception type to the except clause as a string or tuple of strings. A bare except may also be used to catch any exception in the try block.

For example, to cast an arbitrary string to an integer and catch errors raised by int():

!test <drac2>
some_string = "123"
try:
    return int(some_string)
except ("ValueError", "TypeError"):
    return "I couldn't parse an int!"
</drac2>

Note

Unlike Python, only the exact exception type given by a string will be matched, without subclass checking.

Draconic try statements also support else and finally blocks, similar to Python.

See Also

Draconic’s syntax is very similar to Python. Other Python features supported in Draconic include:

Initiative Models

SimpleCombat

class SimpleCombat
combatants

A list of all SimpleCombatant in combat.

current

The SimpleCombatant or SimpleGroup representing the combatant whose turn it is.

groups

A list of all SimpleGroup in combat.

me

The SimpleCombatant representing the active character in combat, or None if the character is not in the combat.

name

The name of the combat (str), or None if no custom name is set.

round_num

An int representing the round number of the combat.

turn_num

An int representing the initiative score of the current turn.

delete_metadata(k: str) Optional[str]

Removes a key from the metadata.

Parameters

k (str) – The metadata key to remove

Returns

The removed value or None if the key is not found.

Return type

str or None

>>> delete_metadata("Test")
'{"Status": ["Mario", 1, 2]}'
end_round()

Moves initiative to just before the next round (no active combatant or group). Ending the round will not tick any events with durations.

get_combatant(name, strict=None)

Gets a combatant by its name or ID.

Parameters
  • name (str) – The name or id of the combatant or group to get.

  • strict – Whether combatant name must be a full case insensitive match. If this is None (default), attempts a strict match with fallback to partial match. If this is False, it returns the first partial match. If this is True, it will only return a strict match.

Returns

The combatant or group or None.

Return type

SimpleCombatant or ~aliasing.api.combat.SimpleGroup

get_group(name, strict=None)

Gets a SimpleGroup that matches on name.

Parameters
  • name (str) – The name of the group to get.

  • strict – Whether combatant name must be a full case insensitive match. If this is None (default), attempts a strict match with fallback to partial match. If this is False, it returns the first partial match. If this is True, it will only return a strict match.

Returns

The group or None.

Return type

SimpleGroup

get_metadata(k: str, default=None) str

Gets a metadata value for the passed key or returns default if the name is not set.

Parameters
  • k (str) – The metadata key to get

  • default – What to return if the name is not set.

>>> get_metadata("Test")
'{"Status": ["Mario", 1, 2]}'
set_metadata(k: str, v: str)

Assigns a metadata key to the passed value. Maximum size of the metadata is 100k characters, key and item inclusive.

Parameters
  • k (str) – The metadata key to set

  • v (str) – The metadata value to set

>>> set_metadata("Test", dump_json({"Status": ["Mario", 1, 2]}))
set_round(round_num: int)

Sets the current round. Setting the round will not tick any events with durations.

Parameters

round_num (int) – the new round number

SimpleCombatant

class SimpleCombatant(AliasStatBlock)

Represents a combatant in combat.

effects

A list of SimpleEffect active on the combatant.

Type

list of SimpleEffect

init

What the combatant rolled for initiative.

Type

int

initmod

An int representing the combatant’s initiative modifier.

Type

int

type

The type of the object ("combatant"), to determine whether this is a group or not.

Type

str

property ac

The armor class of the creature.

Return type

int or None

add_effect(name: str, args: Optional[str] = None, duration: Optional[int] = None, concentration: bool = False, parent: Optional[aliasing.api.combat.SimpleEffect] = None, end: bool = False, desc: Optional[str] = None, passive_effects: Optional[dict] = None, attacks: Optional[list[dict]] = None, buttons: Optional[list[dict]] = None, tick_on_combatant_id: Optional[str] = None)

Adds an effect to the combatant. Returns the added effect.

Note

It is recommended to pass all arguments other than name to this method as keyword arguments (i.e. add_effect("On Fire", duration=10)). This is not strictly enforced for backwards-compatibility.

Warning

The args argument is deprecated as of v4.1.0. Use passive_effects instead.

Parameters
  • name (str) – The name of the effect to add.

  • args (str) – The effect arguments to add (same syntax as !init effect).

  • duration (int) – The duration of the effect, in rounds. Pass None for indefinite.

  • concentration (bool) – Whether the effect requires concentration.

  • parent (SimpleEffect) – The parent of the effect.

  • end (bool) – Whether the effect ends on the end of turn.

  • desc (str) – A description of the effect.

  • passive_effects – The passive effects this effect should grant. See Initiative Effect Args.

  • attacks – The attacks granted by this effect. See Initiative Effect Args.

  • buttons – The buttons granted by this effect. See Initiative Effect Args.

  • tick_on_combatant_id – The ID of the combatant whose turn the effect duration ticks on (defaults to the combatant who the effect is on).

Return type

SimpleEffect

property attacks

The attacks of the creature.

Return type

AliasAttackList

property controller

The ID of the combatant’s controller.

Return type

int

property creature_type

The creature type of the creature. Will return None for players or creatures with no creature type.

Return type

str or None

damage(dice_str, crit=False, d=None, c=None, critdice=0, overheal=False)

Does damage to a combatant, and returns the rolled result and total, accounting for resistances.

Parameters
  • dice_str (str) – The damage to do (e.g. "1d6[acid]").

  • crit (bool) – Whether or not the damage should be rolled as a crit.

  • d (str) – Any additional damage to add (equivalent of -d).

  • c (str) – Any additional damage to add to crits (equivalent of -c).

  • critdice (int) – How many extra weapon dice to roll on a crit (in addition to normal dice).

  • overheal (bool) – Whether or not to allow this damage to exceed a target’s HP max.

Returns

Dictionary representing the results of the Damage Automation.

Return type

dict

get_effect(name: str)

Gets a SimpleEffect, fuzzy searching (partial match) for a match.

Parameters

name (str) – The name of the effect to get.

Returns

The effect.

Return type

SimpleEffect

property group

The name of the group the combatant is in, or None if the combatant is not in a group.

Return type

str or None

property hp

The current HP of the creature.

Return type

int or None

hp_str()

Returns a string describing the creature’s current, max, and temp HP.

Return type

str

property id

The combatant’s unique identifier.

Return type

str

property is_hidden

Whether the HP, AC, Resists, etc are hidden.

Return type

bool

property levels

The levels of the creature.

Return type

AliasLevels

property max_hp

The maximum HP of the creature.

Return type

int or None

modify_hp(amount, ignore_temp=False, overflow=True)

Modifies the creature’s remaining HP by a given amount.

Parameters
  • amount (int) – The amount of HP to add/remove.

  • ignore_temp (bool) – If amount is negative, whether to damage temp HP first or ignore temp.

  • overflow (bool) – If amount is positive, whether to allow overhealing or cap at the creature’s max HP.

Returns

A string describing the creature’s current, max, and temp HP after the change.

Return type

str

property monster_name

The monster name of the combatant. Will return None for players.

Return type

str or None

property name

The name of the creature.

Return type

str

property note

The note on the combatant. None if not set.

Return type

str or None

property race

The race of the combatant. Will return None for monsters or combatants with no race.

Return type

str or None

remove_effect(name: str)

Removes an effect from the combatant, fuzzy searching on name. If not found, does nothing.

Parameters

name (str) – The name of the effect to remove.

reset_hp()

Heals a creature to max and removes any temp HP.

property resistances

The resistances, immunities, and vulnerabilities of the creature.

Return type

AliasResistances

save(ability: str, adv: Optional[bool] = None)

Rolls a combatant’s saving throw.

Parameters
  • ability (str) – The type of save (“str”, “dexterity”, etc).

  • adv (bool) – Whether to roll the save with advantage. Rolls with advantage if True, disadvantage if False, or normally if None.

Returns

A SimpleRollResult describing the rolled save.

Return type

SimpleRollResult

property saves

The saves of the creature.

Return type

AliasSaves

set_ac(ac: int)

Sets the combatant’s armor class.

Parameters

ac (int) – The new AC.

set_group(group)

Sets the combatant’s group

Parameters

group (str) – The name of the group. None to remove from group.

Returns

The combatant’s new group, or None if the combatant was removed from a group.

Return type

SimpleGroup or None

set_hp(new_hp)

Sets the creature’s remaining HP.

Parameters

new_hp (int) – The amount of remaining HP (a nonnegative integer).

set_init(init: int)

Sets the combatant’s initiative roll.

Parameters

init (int) – The new initiative.

set_maxhp(maxhp: int)

Sets the combatant’s max HP.

Parameters

maxhp (int) – The new max HP.

set_name(name: str)

Sets the combatant’s name.

Parameters

name (str) – The new name.

set_note(note: str)

Sets the combatant’s note.

Parameters

note (str) – The new note.

set_temp_hp(new_temp)

Sets a creature’s temp HP.

Parameters

new_temp (int) – The new temp HP (a non-negative integer).

property skills

The skills of the creature.

Return type

AliasSkills

property spellbook

The creature’s spellcasting information.

Return type

AliasSpellbook

property stats

The stats of the creature.

Return type

AliasBaseStats

property temp_hp

The current temp HP of the creature.

Return type

int

SimpleGroup

class SimpleGroup
combatants

A list of all SimpleCombatant in this group.

Type

list of SimpleCombatant

type

The type of the object ("group"), to determine whether this is a group or not.

Type

str

init

What the group rolled for initiative.

Type

int

get_combatant(name, strict=None)

Gets a SimpleCombatant from the group.

param str name

The name of the combatant to get.

param strict

Whether combatant name must be a full case insensitive match. If this is None (default), attempts a strict match with fallback to partial match. If this is False, it returns the first partial match. If this is True, it will only return a strict match.

return

The combatant or None.

rtype

SimpleCombatant

property id

The group’s unique identifier.

Return type

str

property name

The name of the group.

Return type

str

set_init(init: int)

Sets the group’s initiative roll.

Parameters

init (int) – The new initiative.

SimpleEffect

class SimpleEffect
combatant_name

The name of the combatant this effect is on.

Type

str

conc

Whether the effect requires concentration.

Type

bool

desc

The description of the effect.

Type

str

duration

The initial duration of the effect, in rounds. None if the effect has indefinite duration.

Type

int or None

effect

The applied passive effects of the object:

{
    attack_advantage: int
    to_hit_bonus: str
    damage_bonus: str
    magical_damage: bool
    silvered_damage: bool
    resistances: List[Resistance]
    immunities: List[Resistance]
    vulnerabilities: List[Resistance]
    ignored_resistances: List[Resistance]
    ac_value: int
    ac_bonus: int
    max_hp_value: int
    max_hp_bonus: int
    save_bonus: str
    save_adv: List[str]
    save_dis: List[str]
    check_bonus: str
}

Each attribute in the dictionary is optional and may not be present.

Type

dict

name

The name of the effect.

Type

str

remaining

The remaining duration of the effect, in rounds. None if the effect has indefinite duration.

Type

int or None

ticks_on_end

Whether the effect duration ticks at the end of the combatant’s turn or at the start.

Type

bool

attacks

A list of the attacks granted by the effect.

Type

list

buttons

A list of the buttons granted by the effect.

Type

list

property children

Gets the child effects of this effect.

Return type

list of SimpleEffect

property parent

Gets the parent effect of this effect, or None if this effect has no parent.

Return type

SimpleEffect or None

set_parent(parent)

Sets the parent effect of this effect.

Parameters

parent (SimpleEffect) – The parent.

Initiative Effect Args

The passive_effects, attacks, and buttons arguments to SimpleCombatant.add_effect() should be a dict/list that follows the schema below, respectively.

Some examples are provided below.

class PassiveEffects:
    attack_advantage: Optional[enums.AdvantageType]
    to_hit_bonus: Optional[str255]
    damage_bonus: Optional[str255]
    magical_damage: Optional[bool]
    silvered_damage: Optional[bool]
    resistances: Optional[List[str255]]
    immunities: Optional[List[str255]]
    vulnerabilities: Optional[List[str255]]
    ignored_resistances: Optional[List[str255]]
    ac_value: Optional[int]
    ac_bonus: Optional[int]
    max_hp_value: Optional[int]
    max_hp_bonus: Optional[int]
    save_bonus: Optional[str255]
    save_adv: Optional[Set[str]]
    save_dis: Optional[Set[str]]
    check_bonus: Optional[str255]
    check_adv: Optional[Set[str]]
    check_dis: Optional[Set[str]]

class AttackInteraction:
    attack: AttackModel  # this can be any attack built on the Avrae Dashboard
    override_default_dc: Optional[int]
    override_default_attack_bonus: Optional[int]
    override_default_casting_mod: Optional[int]

class ButtonInteraction:
    automation: Automation  # this can be any automation built on the Avrae Dashboard
    label: str
    verb: Optional[str255]
    style: Optional[conint(ge=1, le=4)]
    override_default_dc: Optional[int]
    override_default_attack_bonus: Optional[int]
    override_default_casting_mod: Optional[int]

Example: Passive Effects

Also see PassiveEffects for more information.

combatant.add_effect(
    "Some Magical Effect",
    passive_effects={
        "attack_advantage": 1,
        "damage_bonus": "1d4 [fire]",
        "magical_damage": True,
        "resistances": ["fire", "nonmagical slashing"],
        "ac_bonus": 2,
        "save_adv": ["dexterity"]
    }
)

Example: Granting Attacks

Also see AttackInteraction for more information. Note that the Automation schema differs slightly from the aliasing API.

combatant.add_effect(
    "Some Magical Effect",
    attacks=[{
        "attack": {
            "_v": 2,
            "name": "Magical Attack",
            "verb": "shows off the power of",
            "automation": [
                {
                    "type": "target",
                    "target": "each",
                    "effects": [
                        {
                            "type": "attack",
                            "hit": [
                                {
                                    "type": "damage",
                                    "damage": "1d10[fire]"
                                }
                            ],
                            "miss": []
                        }
                    ]
                }
            ]
        }
    }]
)

Example: Granting Buttons

Also see ButtonInteraction for more information. Note that the Automation schema differs slightly from the aliasing API.

combatant.add_effect(
    "Some Magical Effect",
    buttons=[{
        "label": "On Fire",
        "verb": "is burning",
        "style": 4,
        "automation": [
            {
                "type": "target",
                "target": "self",
                "effects": [
                    {
                        "type": "damage",
                        "damage": "1d6 [fire]"
                    }
                ]
            }
        ]
    }]
)

SimpleRollResult

class SimpleRollResult
dice

The rolled dice (e.g. 1d20 (5)).

Type

str

total

The total of the roll.

Type

int

full

The string representing the roll.

Type

str

result

The RollResult object returned by the roll.

Type

d20.RollResult

raw

The Expression object returned by the roll. Equivalent to SimpleRollResult.result.expr.

Type

d20.Expression

consolidated()

Gets the most simplified version of the roll string. Consolidates totals and damage types together.

Note that this modifies the result expression in place!

>>> result = vroll("3d6[fire]+1d4[cold]")
>>> str(result)
'3d6 (3, 3, 2) [fire] + 1d4 (2) [cold] = `10`'
>>> result.consolidated()
'8 [fire] + 2 [cold]'
Return type

str

__str__()

Equivalent to result.full.

ParsedArguments

class ParsedArguments
add_context(context, args)

Adds contextual parsed arguments (arguments that only apply in a given context)

Parameters
  • context – The context to add arguments to.

  • args (ParsedArguments, or dict[str, list[str]]) – The arguments to add.

adv(eadv=False, boolwise=False, ephem=False, custom: Optional[dict] = None)

Determines whether to roll with advantage, disadvantage, Elven Accuracy, or no special effect.

Parameters
  • eadv – Whether to parse for elven accuracy.

  • boolwise – Whether to return an integer or tribool representation.

  • ephem – Whether to return an ephemeral argument if such exists.

  • custom – Dictionary of custom values to parse for. There should be a key for each value you want to overwrite. custom={'adv': 'custom_adv'} would allow you to parse for advantage if the custom_adv argument is found.

Returns

-1 for dis, 0 for normal, 1 for adv, 2 for eadv

get(arg, default=None, type_=<class 'str'>, ephem=False)

Gets a list of all values of an argument.

Parameters
  • arg (str) – The name of the arg to get.

  • default – The default value to return if the arg is not found. Not cast to type.

  • type_ (type) – The type that each value in the list should be returned as.

  • ephem (bool) – Whether to add applicable ephemeral arguments to the returned list.

Returns

The relevant argument list.

Return type

list

ignore(arg)

Removes any instances of an argument from the result in all contexts (ephemeral included).

Parameters

arg – The argument to ignore.

join(arg, connector: str, default=None, ephem=False)

Returns a str formed from all of one arg, joined by a connector.

Parameters
  • arg – The arg to join.

  • connector – What to join the arg by.

  • default – What to return if the arg does not exist.

  • ephem – Whether to return an ephemeral argument if such exists.

Returns

The joined str, or default.

last(arg, default=None, type_=<class 'str'>, ephem=False)

Gets the last value of an arg.

Parameters
  • arg (str) – The name of the arg to get.

  • default – The default value to return if the arg is not found. Not cast to type.

  • type_ (type) – The type that the arg should be returned as.

  • ephem (bool) – Whether to return an ephemeral argument if such exists.

Raises

InvalidArgument if the arg cannot be cast to the type

Returns

The relevant argument.

set_context(context)

Sets the current argument parsing context.

Parameters

context – Any hashable context.

update(new)

Updates the arguments in this argument list from a dict.

Parameters

new (dict[str, str] or dict[str, list[str]]) – The new values for each argument.

update_nx(new)

Like .update(), but only fills in arguments that were not already parsed. Ignores the argument if the value is None.

Parameters

new (dict[str, str] or dict[str, list[str]] or dict[str, None]) – The new values for each argument.

Context Models

AliasContext

class AliasContext

Used to expose some information about the context, like the guild name, channel name, author name, and current prefix to alias authors.

You can access this in an alias by using the ctx local.

property alias

The name the alias was invoked with. Note: When used in a base command, this will return the deepest sub-command, but when used in an alias it will return the base command.

>>> !test {{ctx.alias}}
'test'
Return type

str

property author

The user that ran the alias.

Return type

AliasAuthor

property channel

The channel the alias was run in.

Return type

AliasChannel

property guild

The discord guild (server) the alias was run in, or None if the alias was run in DMs.

Return type

AliasGuild or None

property message_id

The ID of the message the alias was invoked with.

>>> !test {{ctx.message_id}}
982495360129847306
Return type

int

property prefix

The prefix used to run the alias.

Return type

str

AliasGuild

class AliasGuild

Represents the Discord guild (server) an alias was invoked in.

property id

The ID of the guild.

Return type

int

property name

The name of the guild.

Return type

str

AliasChannel

class AliasChannel

Represents the Discord channel an alias was invoked in.

property category

The category of the channel the alias was run in

Return type

AliasCategory or None

property id

The ID of the channel.

Return type

int

property name

The name of the channel, not including the preceding hash (#).

Return type

str

property parent

If this channel is a thread, the thread’s parent channel, or None otherwise.

Return type

AliasChannel or None

property topic

The channel topic. This will be None if the channel is a direct message or thread.

Return type

str or None

AliasCategory

class AliasCategory

Represents the category of the Discord channel an alias was invoked in.

property id

The ID of the category.

Return type

int

property name

The name of the category

Return type

str

AliasAuthor

class AliasAuthor

Represents the Discord user who invoked an alias.

property discriminator

The user’s discriminator (number after the hash).

Return type

str

property display_name

The user’s display name - nickname if applicable, otherwise same as their name.

Return type

str

property id

The user’s ID.

Return type

int

property name

The user’s username (not including the discriminator).

Return type

str

AliasCharacter

class AliasCharacter(AliasStatBlock)
property ac

The armor class of the creature.

Return type

int or None

property actions

The character’s actions. These do not include attacks - see the attacks property.

Return type

list[AliasAction]

property attacks

The attacks of the creature.

Return type

AliasAttackList

property background

Gets the character’s background.

Return type

str or None

cc(name)

Gets the AliasCustomCounter with the name name

Parameters

name (str) – The name of the custom counter to get.

Returns

The custom counter.

Return type

AliasCustomCounter

Raises

ConsumableException if the counter does not exist.

cc_exists(name)

Returns whether a custom counter exists.

Parameters

name (str) – The name of the custom counter to check.

Returns

Whether the counter exists.

cc_str(name)

Returns a string representing a custom counter.

Parameters

name (str) – The name of the custom counter to get.

Returns

A string representing the current value, maximum, and minimum of the counter.

Return type

str

Raises

ConsumableException if the counter does not exist.

Example:

>>> cc_str("Ki")
'11/17'
>>> cc_str("Bardic Inspiration")
'◉◉◉〇〇'
property coinpurse

The coinpurse of the character.

Return type

AliasCoinpurse

property consumables

Returns a list of custom counters on the character.

Return type

list[AliasCustomCounter]

create_cc(name: str, *args, **kwargs)

Creates a custom counter. If a counter with the same name already exists, it will replace it.

Parameters
  • name (str) – The name of the counter to create.

  • minVal (str) – The minimum value of the counter. Supports Cvar Table parsing.

  • maxVal (str) – The maximum value of the counter. Supports Cvar Table parsing.

  • reset (str) – One of 'short', 'long', 'hp', 'none', or None.

  • dispType (str) – Either None, 'bubble', 'square', 'hex', or 'star'.

  • reset_to (str) – The value the counter should reset to. Supports Cvar Table parsing.

  • reset_by (str) – How much the counter should change by on a reset. Supports dice but not cvars.

  • title (str) – The title of the counter.

  • desc (str) – The description of the counter.

  • initial_value (str) – The initial value of the counter.

Return type

AliasCustomCounter

Returns

The newly created counter.

create_cc_nx(name: str, minVal: Optional[str] = None, maxVal: Optional[str] = None, reset: Optional[str] = None, dispType: Optional[str] = None, reset_to: Optional[str] = None, reset_by: Optional[str] = None, title: Optional[str] = None, desc: Optional[str] = None, initial_value: Optional[str] = None)

Creates a custom counter if one with the given name does not already exist. Equivalent to:

>>> if not cc_exists(name):
>>>     create_cc(name, minVal, maxVal, reset, dispType, reset_to, reset_by, title, desc)
property creature_type

The creature type of the creature. Will return None for players or creatures with no creature type.

Return type

str or None

property csettings

Gets a copy of the character’s settings dict.

Return type

dict

property cvars

Returns a dict of cvars bound on this character.

Return type

dict

property death_saves

Returns the character’s death saves.

Return type

AliasDeathSaves

delete_cc(name)

Deletes a custom counter.

Parameters

name (str) – The name of the custom counter to delete.

Raises

ConsumableException if the counter does not exist.

delete_cvar(name)

Deletes a custom character variable. Does nothing if the cvar does not exist.

Note

This method does not unbind the name in the current runtime.

Parameters

name (str) – The name of the variable to delete.

property description

The description of the character.

Return type

str or None

edit_cc(name: str, minVal: str = <object object>, maxVal: str = <object object>, reset: str = <object object>, dispType: str = <object object>, reset_to: str = <object object>, reset_by: str = <object object>, title: str = <object object>, desc: str = <object object>, new_name: Optional[str] = None)

Edits an existing custom counter.

Pass None to remove an argument entirely. Will clamp counter value to new limits if needed.

Parameters
  • name (str) – The name of the counter to edit.

  • minVal (str) – The minimum value of the counter. Supports Cvar Table parsing.

  • maxVal (str) – The maximum value of the counter. Supports Cvar Table parsing.

  • reset (str) – One of 'short', 'long', 'hp', 'none', or None.

  • dispType (str) – Either None, 'bubble', 'square', 'hex', or 'star'.

  • reset_to (str) – The value the counter should reset to. Supports Cvar Table parsing.

  • reset_by (str) – How much the counter should change by on a reset. Supports dice but not cvars.

  • title (str) – The title of the counter.

  • desc (str) – The description of the counter.

  • new_name (str) – The new name of the counter.

Return type

AliasCustomCounter

Raises

ConsumableException if the counter does not exist.

Returns

The edited counter

get_cc(name)

Gets the value of a custom counter.

Parameters

name (str) – The name of the custom counter to get.

Returns

The current value of the counter.

Return type

int

Raises

ConsumableException if the counter does not exist.

get_cc_max(name)

Gets the maximum value of a custom counter.

Parameters

name (str) – The name of the custom counter maximum to get.

Returns

The maximum value of the counter. If a counter has no maximum, it will return INT_MAX (2^31-1).

Return type

int

Raises

ConsumableException if the counter does not exist.

get_cc_min(name)

Gets the minimum value of a custom counter.

Parameters

name (str) – The name of the custom counter minimum to get.

Returns

The minimum value of the counter. If a counter has no minimum, it will return INT_MIN (-2^31).

Return type

int

Raises

ConsumableException if the counter does not exist.

get_cvar(name, default=None)

Retrieves and returns the value of a cvar (character variable).

Parameters
  • name (str) – The name of the cvar.

  • default – What to return if the name is not set.

Returns

The value of the cvar, or the default value if it does not exist.

Return type

str or None

property hp

The current HP of the creature.

Return type

int or None

hp_str()

Returns a string describing the creature’s current, max, and temp HP.

Return type

str

property image

The image url for the character.

Return type

str

property levels

The levels of the creature.

Return type

AliasLevels

property max_hp

The maximum HP of the creature.

Return type

int or None

mod_cc(name, val: int, strict=False)

Modifies the value of a custom counter. Equivalent to set_cc(name, get_cc(name) + value, strict).

modify_hp(amount, ignore_temp=False, overflow=True)

Modifies the creature’s remaining HP by a given amount.

Parameters
  • amount (int) – The amount of HP to add/remove.

  • ignore_temp (bool) – If amount is negative, whether to damage temp HP first or ignore temp.

  • overflow (bool) – If amount is positive, whether to allow overhealing or cap at the creature’s max HP.

Returns

A string describing the creature’s current, max, and temp HP after the change.

Return type

str

property name

The name of the creature.

Return type

str

property owner

Returns the id of this character’s owner.

Return type

int

property race

Gets the character’s race.

Return type

str or None

reset_hp()

Heals a creature to max and removes any temp HP.

property resistances

The resistances, immunities, and vulnerabilities of the creature.

Return type

AliasResistances

property saves

The saves of the creature.

Return type

AliasSaves

set_cc(name, value: int, strict=False)

Sets the value of a custom counter.

Parameters
  • name (str) – The name of the custom counter to set.

  • value (int) – The value to set the counter to.

  • strict (bool) – If True, will raise a CounterOutOfBounds if the new value is out of bounds, otherwise silently clips to bounds.

Raises

ConsumableException if the counter does not exist.

Returns

The cc’s new value.

Return type

int

set_cvar(name, val: str)

Sets a custom character variable, which will be available in all scripting contexts using this character. Binds the value to the given name in the current runtime.

Parameters
  • name (str) – The name of the variable to set. Must be a valid identifier and not be in the Cvar Table.

  • val (str) – The value to set it to.

set_cvar_nx(name, val: str)

Sets a custom character variable if it is not already set.

Parameters
  • name (str) – The name of the variable to set. Must be a valid identifier and not be in the Cvar Table.

  • val (str) – The value to set it to.

set_hp(new_hp)

Sets the creature’s remaining HP.

Parameters

new_hp (int) – The amount of remaining HP (a nonnegative integer).

set_temp_hp(new_temp)

Sets a creature’s temp HP.

Parameters

new_temp (int) – The new temp HP (a non-negative integer).

property sheet_type

Returns the sheet type of this character (beyond, dicecloud, dicecloudv2, google).

Return type

str

property skills

The skills of the creature.

Return type

AliasSkills

property spellbook

The creature’s spellcasting information.

Return type

AliasSpellbook

property stats

The stats of the creature.

Return type

AliasBaseStats

property temp_hp

The current temp HP of the creature.

Return type

int

property upstream

Returns the upstream key for this character.

Return type

str

AliasCustomCounter

class AliasCustomCounter
property desc

Returns the cc’s description.

Return type

str or None

property display_type

Returns the cc’s display type. (None, ‘bubble’, ‘square’, ‘hex’, or ‘star’)

Return type

str

full_str(include_name: bool = False)

Returns a string representing the full custom counter.

Parameters

include_name (bool) – If the name of the counter should be included. Defaults to False.

Returns

A string representing all components of the counter.

Return type

str

Example:

>>> full_str()
"◉◉◉◉\n"
"**Resets On**: Long Rest"
>>> full_str(True)
"**Bardic Inspiration**\n"
"◉◉◉◉\n"
"**Resets On**: Long Rest"
property max

Returns the maximum value of the cc, or 2^31-1 if the cc has no max.

Return type

int

property min

Returns the minimum value of the cc, or -2^31 if the cc has no min.

Return type

int

mod(value, strict=False)

Modifies the value of the custom counter.

Parameters
  • value (int) – The value to modify the custom counter by.

  • strict (bool) – Whether to error when going out of bounds (true) or to clip silently (false).

Returns

The cc’s new value.

Return type

int

property name

Returns the cc’s name.

Return type

str

reset()

Resets the cc to its reset value. Errors if the cc has no reset value or no reset.

The reset value is calculated in 3 steps: - if the cc has a reset_to value, it is reset to that - else if the cc has a reset_by value, it is modified by that much - else the reset value is its max

Return CustomCounterResetResult

(new_value: int, old_value: int, target_value: int, delta: str)

property reset_by

Returns the amount the cc changes by on a reset, if it was created with an explicit resetby.

Returns

The amount the cc changes by. Guaranteed to be a rollable string.

Return type

str or None

property reset_on

Returns the condition on which the cc resets. (‘long’, ‘short’, ‘none’, None)

Return type

str or None

property reset_to

Returns the value the cc resets to, if it was created with an explicit resetto.

Return type

int or None

set(new_value, strict=False)

Sets the cc’s value to a new value.

Parameters
  • new_value (int) – The new value to set.

  • strict (bool) – Whether to error when going out of bounds (true) or to clip silently (false).

Returns

The cc’s new value.

Return type

int

property title

Returns the cc’s title.

Return type

str or None

property value

Returns the current value of the cc.

Return type

int

AliasDeathSaves

class AliasDeathSaves
fail(num=1)

Adds one or more failed death saves.

Parameters

num (int) – The number of failed death saves to add.

property fails

Returns the number of failed death saves.

Return type

int

is_dead()

Returns whether or not the character is dead.

Return type

bool

is_stable()

Returns whether or not the character is stable.

Return type

bool

reset()

Resets all death saves.

succeed(num=1)

Adds one or more successful death saves.

Parameters

num (int) – The number of successful death saves to add.

property successes

Returns the number of successful death saves.

Return type

int

AliasAction

class AliasAction

An action.

property activation_type

The activation type of the action (e.g. action, bonus, etc).

Action Type

Value

Action

1

No Action

2

Bonus Action

3

Reaction

4

Minute

6

Hour

7

Special

8

Legendary Action

9

Mythic Action

10

Lair Action

11

Return type

int or None

property activation_type_name

The name of the activation type of the action. Will be one of: “ACTION”, “NO_ACTION”, “BONUS_ACTION”, “REACTION”, “MINUTE”, “HOUR”, “SPECIAL”. This list of options may expand in the future.

Return type

str

property description

The description of the action as it appears in a non-verbose action list.

Return type

str

property name

The name of the action.

Return type

str

property snippet

The description of the action as it appears in a verbose action list.

Return type

str

AliasCoinpurse

class AliasCoinpurse

An object holding the coinpurse for the active character.

str(AliasCoinpurse)

Returns a string representation of the entire coinpurse. If the character setting for Compact Coins is enabled, this will only return your float gold, otherwise will return all 5 coin types.

Type

str

pp
gp
ep
sp
cp

The value of the given coin type.

Type

int

AliasCoinpurse[cointype]

Gets the value of the given coin type.

Type

int

autoconvert()

Converts all of your coins into the highest value coins possible. 100cp turns into 1gp, 5sp turns into 1ep, etc.

coin_str(cointype: str) str

Returns a string representation of the chosen coin type.

Parameters

cointype (str) – The type of coin to return. "pp", "gp", "ep", "sp", and "cp"

Returns

The string representation of the chosen coin type.

Return type

str

compact_str() str

Returns a string representation of the compacted coin value.

Returns

The string representation of the compacted coin value.

Return type

str

get_coins() dict

Returns a dict of your current coinpurse.

Returns

A dict of your current coinpurse, e.g. {"pp":0, "gp":1, "ep":0, "sp":2, "cp":3, "total": 1.23}

Return type

dict

modify_coins(pp: int = 0, gp: int = 0, ep: int = 0, sp: int = 0, cp: int = 0, autoconvert: bool = True)

Modifies your coinpurse based on the provided values. If autoconvert is enabled, it will convert down higher value coins if necessary to handle the transaction. Returns a dict representation of the deltas.

Parameters
  • pp (int) – Platinum Pieces. Defaults to 0.

  • gp (int) – Gold Pieces. Defaults to 0.

  • ep (int) – Electrum Pieces. Defaults to 0.

  • sp (int) – Silver Pieces. Defaults to 0.

  • cp (int) – Copper Pieces. Defaults to 0.

  • autoconvert (bool) – Whether it should attempt to convert down higher value coins. Defaults to True

Returns

A dict representation of the delta changes for each coin type.

Return type

dict

set_coins(pp: int, gp: int, ep: int, sp: int, cp: int)

Sets your coinpurse to the provided values.

Parameters
  • pp (int) – Platinum Pieces

  • gp (int) – Gold Pieces

  • ep (int) – Electrum Pieces

  • sp (int) – Silver Pieces

  • cp (int) – Copper Pieces

property total: float

Returns the total amount of coins in your bag, converted to float gold.

Return type

float

StatBlock Models

AliasStatBlock

class AliasStatBlock

A base class representing any creature (player or otherwise) that has stats.

Generally, these are never directly used - notable subclasses are SimpleCombatant and AliasCharacter.

property ac

The armor class of the creature.

Return type

int or None

property attacks

The attacks of the creature.

Return type

AliasAttackList

property creature_type

The creature type of the creature. Will return None for players or creatures with no creature type.

Return type

str or None

property hp

The current HP of the creature.

Return type

int or None

hp_str()

Returns a string describing the creature’s current, max, and temp HP.

Return type

str

property levels

The levels of the creature.

Return type

AliasLevels

property max_hp

The maximum HP of the creature.

Return type

int or None

modify_hp(amount, ignore_temp=False, overflow=True)

Modifies the creature’s remaining HP by a given amount.

Parameters
  • amount (int) – The amount of HP to add/remove.

  • ignore_temp (bool) – If amount is negative, whether to damage temp HP first or ignore temp.

  • overflow (bool) – If amount is positive, whether to allow overhealing or cap at the creature’s max HP.

Returns

A string describing the creature’s current, max, and temp HP after the change.

Return type

str

property name

The name of the creature.

Return type

str

reset_hp()

Heals a creature to max and removes any temp HP.

property resistances

The resistances, immunities, and vulnerabilities of the creature.

Return type

AliasResistances

property saves

The saves of the creature.

Return type

AliasSaves

set_hp(new_hp)

Sets the creature’s remaining HP.

Parameters

new_hp (int) – The amount of remaining HP (a nonnegative integer).

set_temp_hp(new_temp)

Sets a creature’s temp HP.

Parameters

new_temp (int) – The new temp HP (a non-negative integer).

property skills

The skills of the creature.

Return type

AliasSkills

property spellbook

The creature’s spellcasting information.

Return type

AliasSpellbook

property stats

The stats of the creature.

Return type

AliasBaseStats

property temp_hp

The current temp HP of the creature.

Return type

int

AliasBaseStats

class AliasBaseStats

Represents a statblock’s 6 base ability scores and proficiency bonus.

property charisma

Charisma score.

Return type

int

property constitution

Constitution score.

Return type

int

property dexterity

Dexterity score.

Return type

int

get(stat)

Get the integer value of a stat (case sensitive, lowercase. strength, dexterity, etc).

Parameters

stat (str) – The stat to look up

Returns

The integer value of the stat.

Return type

int

get_mod(stat: str)

Gets the modifier for a base stat (str, dex, con, etc). Does not take skill check bonuses into account.

For the skill check modifier, use StatBlock.skills.strength etc.

Parameters

stat (str) – The stat to get the modifier for.

Return type

int

property intelligence

Intelligence score.

Return type

int

property prof_bonus

The proficiency bonus.

Return type

int

property strength

Strength score.

Return type

int

property wisdom

Wisdom score.

Return type

int

AliasLevels

class AliasLevels

Represents a statblock’s class levels.

for (cls, level) in AliasLevels:

Iterates over pairs of class names and the number of levels in that class.

Type

Iterable[tuple[str, int]]

get(cls_name, default=0)

Gets the levels in a given class, or default if there are none.

Parameters
  • cls_name (str) – The name of the class to get the levels of.

  • default (int) – What to return if the statblock does not have levels in the given class.

Return type

float or int

property total_level

The total level.

Return type

float or int

AliasAttackList

class AliasAttackList

A container of a statblock’s attacks.

str(AliasAttackList)

Returns a string representation of all attacks in this attack list.

Type

str

len(AliasAttackList)

Returns the number of attacks in this attack list.

Type

int

for attack in AliasAttackList:

Iterates over attacks in this attack list.

Type

Iterable[AliasAttack]

AliasAttackList[i]

Gets the i-th indexed attack.

Type

AliasAttack

AliasAttack

class AliasAttack

An attack.

str(AliasAttack)

Returns a string representation of this attack.

Type

str

property activation_type

The activation type of the action (e.g. action, bonus, etc).

Action Type

Value

Action

1

No Action

2

Bonus Action

3

Reaction

4

Minute

6

Hour

7

Special

8

Legendary Action

9

Mythic Action

10

Lair Action

11

Return type

int

property name

The name of the attack.

Return type

str

property proper

Whether or not this attack is a proper noun.

Return type

bool

property raw

A dict representing the raw value of this attack.

Return type

dict

property verb

The custom verb used for this attack, if applicable.

Return type

str or None

AliasSkill

class AliasSkill

A skill modifier.

property adv

The guaranteed advantage or disadvantage on this skill modifier. True = adv, False = dis, None = normal.

Return type

bool or None

property bonus

The miscellaneous bonus to the skill modifier.

Return type

int

d20(base_adv=None, reroll=None, min_val=None, mod_override=None)

Gets a dice string representing the roll for this skill.

Parameters
  • base_adv (bool) – Whether this roll should be made at adv (True), dis (False), or normally (None).

  • reroll (int) – If the roll lands on this number, reroll it once (Halfling Luck).

  • min_val (int) – The minimum value of the dice roll (Reliable Talent, Glibness).

  • mod_override (int) – Overrides the skill modifier.

Return type

str

property prof

The proficiency multiplier in this skill. 0 = no proficiency, 0.5 = JoAT, 1 = proficiency, 2 = expertise.

Return type

float or int

property value

The final modifier. Generally, value = (base stat mod) + (profBonus) * prof + bonus.

Return type

int

AliasSkills

class AliasSkills

An object holding the skill modifiers for all skills.

for (skill_name, skill) in AliasSkills:

Iterates over pairs of skill names and corresponding skills.

Type

Iterable[tuple[str, AliasSkill]]

acrobatics
animalHandling
arcana
athletics
deception
history
initiative
insight
intimidation
investigation
medicine
nature
perception
performance
persuasion
religion
sleightOfHand
stealth
survival
strength
dexterity
constitution
intelligence
wisdom
charisma

The skill modifier for the given skill.

Type

AliasSkill

AliasSaves

class AliasSaves

An objecting holding the modifiers of all saves.

for (save_name, skill) in AliasSaves:

Iterates over pairs of save names and corresponding save.

Type

Iterable[tuple[str, AliasSkill]]

get(base_stat)

Gets the save skill for a given stat (str, dex, etc).

Parameters

base_stat (str) – The stat to get the save for.

Return type

AliasSkill

AliasResistances

class AliasResistances

A statblock’s resistances, immunities, vulnerabilities, and explicit neural damage types.

property immune

A list of damage types that the stat block is immune to.

Return type

list[Resistance]

is_immune(damage_type: str) bool

Whether or not this AliasResistances contains any immunities that apply to the given damage type string.

If the AliasResistances contains both a neutral and an immunity that applies, returns False.

is_neutral(damage_type: str) bool

Whether or not this AliasResistances contains any neutrals that apply to the given damage type string.

is_resistant(damage_type: str) bool

Whether or not this AliasResistances contains any resistances that apply to the given damage type string.

If the AliasResistances contains both a neutral and a resistance that applies, returns False.

is_vulnerable(damage_type: str) bool

Whether or not this AliasResistances contains any vulnerabilities that apply to the given damage type string.

If the AliasResistances contains both a neutral and a vulnerability that applies, returns False.

property neutral

A list of damage types that the stat block ignores in damage calculations. (i.e. will not handle resistances/ vulnerabilities/immunities)

Return type

list[Resistance]

property resist

A list of damage types that the stat block is resistant to.

Return type

list[Resistance]

property vuln

A list of damage types that the stat block is vulnerable to.

Return type

list[Resistance]

Resistance

class Resistance

Represents a conditional resistance to a damage type.

Only applied to a type token set T if \(dtype \in T \land \lnot (unless \cap T) \land only \subset T\).

Note: transforms all damage types given to lowercase.

dtype

The damage type.

Type

str

unless

A set of tokens that if present, this resistance will not apply.

Type

set[str]

only

A set of tokens that unless present, this resistance will not apply.

Type

set[str]

applies_to(tokens)

Note that tokens should be a set of lowercase strings.

Parameters

tokens (set[str]) – A set of strings to test against.

Return type

bool

applies_to_str(dtype)

Returns whether or not this resistance is applicable to a damage type.

Parameters

dtype (str) – The damage type to test.

Return type

bool

property is_complex

Whether or not the resistance has some more complex conditional beyond just a dtype.

AliasSpellbook

class AliasSpellbook

A statblock’s spellcasting information.

spell in AliasSpellbook

Returns whether the spell named spell (str) is known.

Type

bool

can_cast(spell, level)

Returns whether or not the given spell can currently be cast at the given level.

Parameters
  • spell (str) – The name of the spell.

  • level (int) – The level the spell is being cast at.

Return type

bool

cast(spell, level)

Uses all resources to cast a given spell at a given level.

Parameters
  • spell (str) – The name of the spell.

  • level (int) – The level the spell is being cast at.

property caster_level

The caster’s caster level.

Return type

int

property dc

The spellcasting DC.

Return type

int

find(spell_name: str)

Returns a list of the spells of the given name in the spellbook, case-insensitive.

Return type

List[AliasSpellbookSpell]

get_max_slots(level)

Gets the maximum number of level level spell slots available.

Parameters

level (int) – The spell level [1..9].

Returns int

The maximum number of spell slots, including pact slots.

get_slots(level)

Gets the remaining number of slots of a given level. Always returns 1 if level is 0.

Parameters

level (int) – The spell level to get the remaining slots of.

Returns int

The number of slots remaining, including pact slots.

property max_pact_slots

The maximum number of pact slots the spellcaster has remaining. If the spellcaster has no pact slots, returns None.

Note

Only D&D Beyond character sheets support the explicit distinction between pact and non-pact slots.

Return type

int or None

property num_pact_slots

The number of pact slots the spellcaster has remaining. If the spellcaster has no pact slots, returns None.

Note

Only D&D Beyond character sheets support the explicit distinction between pact and non-pact slots.

Return type

int or None

property pact_slot_level

The spellcaster’s pact slot level. If the spellcaster has no pact slots, returns None.

Note

Only D&D Beyond character sheets support the explicit distinction between pact and non-pact slots.

Return type

int or None

remaining_casts_of(spell, level)

Gets a string representing the remaining casts of a given spell at a given level.

Parameters
  • spell (str) – The name of the spell (case-sensitive).

  • level (int) – The level the spell is being cast at.

Return type

str

reset_pact_slots()

Resets the number of remaining pact slots to the max, leaving non-pact slots untouched.

reset_slots()

Resets the number of remaining spell slots of all levels to the max.

property sab

The spell attack bonus.

Return type

int

set_slots(level, value, pact=True)

Sets the remaining number of spell slots of a given level.

Parameters
  • level (int) – The spell level to set [1..9].

  • value (int) – The remaining number of slots.

  • pact (bool) – Whether to prefer modifying Pact Magic slots (if applicable) or normal spell slots.

slots_str(level)
Parameters

level (int) – The level of spell slot to return.

Returns str

A string representing the caster’s remaining spell slots, including pact slots.

property spell_mod

The spellcasting modifier.

Return type

int

property spells

The list of spells in this spellbook.

Return type

list[AliasSpellbookSpell]

use_slot(level)

Uses one spell slot of a given level. Equivalent to set_slots(level, get_slots(level) - 1).

Parameters

level (int) – The level of spell slot to use.

AliasSpellbookSpell

class AliasSpellbookSpell
property dc

The spell’s overridden DC. None if this spell uses the default caster DC.

Return type

int or None

property mod

The spell’s overridden spellcasting modifier. None if this spell uses the default caster spellcasting modifier.

Return type

int or None

property name

The name of the spell.

Return type

str

property prepared

Whether or not the spell is prepared. If the spell is always prepared, the caster is not a prepared caster (e.g. Sorcerer), or the spell is a cantrip, this will be True.

Return type

bool

property sab

The spell’s overridden spell attack bonus. None if this spell uses the default caster spell attack bonus.

Return type

int or None