Character Vault
Any Concept / Any System
Compendium
Your System Come To Life
Roll20 for Android
Streamlined for your Tablet
Roll20 for iPad
Streamlined for your Tablet

Personal tools

Difference between revisions of "Mod:Function"

From Roll20 Wiki

Jump to: navigation, search
(getAllObjs)
m (1223200 moved page API:Function documentation to Mod:Function)
 
(49 intermediate revisions by 10 users not shown)
Line 1: Line 1:
Roll20 makes a number of functions available that are not part of core JavaScript or some other library.
+
{{revdate}}{{HCbox| {{hc|articles/360037772833-API-Function-Documentation here}} }}
{{toclimit|3}}
+
{{cleanup-msg|add new options from [[Mod Update 2024]]|May 2024}}
 +
Roll20 makes a number of functions available that are not part of core [[JavaScript]] or some other library.
 +
 
 +
{{notebox|See also new things available from '''[[Mod Scripts Major Update 2024]]'''}}
 +
 
 +
{{apibox}}
 +
{{toclimit|3|clear=none}}
  
 
== Global variables ==
 
== Global variables ==
Line 15: Line 21:
 
|}
 
|}
  
=== <code>_</code> (Underscore) ===
+
=== <code><big><big><big>_</big></big></big></code> (Underscore) ===
 
This is the namespace object for the [http://underscorejs.org/ Underscore.js] library. Underscore has many functions for collection manipulation.
 
This is the namespace object for the [http://underscorejs.org/ Underscore.js] library. Underscore has many functions for collection manipulation.
  
=== <code>state</code> ===
+
=== <code><big><big><big>state</big></big></big></code> ===
 
Properties of the state object will persist between game sessions. The same state object is also shared between all API scripts in a campaign, so it is strongly recommended that when writing values to state, you minimize your footprint as much as possible in order to avoid name collisions. ''Note: state gets serialized with JSON, so you cannot store functions or objects with cyclical references.''
 
Properties of the state object will persist between game sessions. The same state object is also shared between all API scripts in a campaign, so it is strongly recommended that when writing values to state, you minimize your footprint as much as possible in order to avoid name collisions. ''Note: state gets serialized with JSON, so you cannot store functions or objects with cyclical references.''
  
 
== Global functions ==
 
== Global functions ==
 +
{{notebox| the index is missing bunch of functions which where added recently to page [[User:1223200|1223200]] ([[User talk:1223200|talk]]) 11:41, 27 September 2021 (UTC)}}
 
{| class="wikitable"
 
{| class="wikitable"
 
|-
 
|-
Line 46: Line 53:
 
| Array of [[API:Function documentation/Roll20 object|Roll20 objects]]
 
| Array of [[API:Function documentation/Roll20 object|Roll20 objects]]
 
| <code>[[#getAllObjs|getAllObjs]]</code>
 
| <code>[[#getAllObjs|getAllObjs]]</code>
| Gets all [[API:Function documentation/Roll20 object|Roll20 objects]] in the campaign.
+
| Gets all [[API:Function documentation/Roll20 object|Roll20 objects]] in the [[campaign]].
 
|-
 
|-
 
| ''varies''
 
| ''varies''
Line 58: Line 65:
 
|
 
|
 
| <code>[[#log|log]]</code>
 
| <code>[[#log|log]]</code>
| Logs a message to the API console.
+
| Logs a message to the [[API:Use_Guide#The_API_Console|API Console]].
 
|-
 
|-
 
|
 
|
 
| <code>[[#on|on]]</code>
 
| <code>[[#on|on]]</code>
 
| Registers an event handler.
 
| Registers an event handler.
 +
|-
 +
|
 +
| <code>[[#onSheetWorkerCompleted|onSheetWorkerCompleted]]</code>
 +
| Registers a one-time event handler to run after a full stack of [[Sheet Worker Scripts]] completes.
 
|-
 
|-
 
| Boolean
 
| Boolean
 
| <code>[[#playerIsGM|playerIsGM]]</code>
 
| <code>[[#playerIsGM|playerIsGM]]</code>
| Checks whether a player currently has GM privileges.
+
| Checks whether a [[player]] currently has [[GM]] privileges.
 
|-
 
|-
 
|
 
|
 
| <code>[[#playJukeboxPlaylist|playJukeboxPlaylist]]</code>
 
| <code>[[#playJukeboxPlaylist|playJukeboxPlaylist]]</code>
| Start playing a jukebox playlist.
+
| Start playing a {{jukebox}} playlist.
 
|-
 
|-
 
| Number
 
| Number
Line 77: Line 88:
 
|-
 
|-
 
|
 
|
| <code>[[#sendChat|sendChat]]</code>
+
| <code>[[#sendChat %5BAsynchronous%5D|sendChat]]</code>
 
| Sends a chat message.
 
| Sends a chat message.
 
|-
 
|-
Line 93: Line 104:
 
|-
 
|-
 
|
 
|
| <code>[[#spawnFxWithDefinition|spawnWithDefinition]]</code>
+
| <code>[[#spawnFxWithDefinition|spawnFxWithDefinition]]</code>
 
| Spawns a particle emitter that is not represented by an FX [[API:Function documentation/Roll20 object|Roll20 object]].
 
| Spawns a particle emitter that is not represented by an FX [[API:Function documentation/Roll20 object|Roll20 object]].
 
|-
 
|-
 
|
 
|
 
| <code>[[#stopJukeboxPlaylist|stopJukeboxPlaylist]]</code>
 
| <code>[[#stopJukeboxPlaylist|stopJukeboxPlaylist]]</code>
| Stops all currently playing jukebox playlits.
+
| Stops all currently playing jukebox playlists.
 
|-
 
|-
 
|
 
|
Line 109: Line 120:
 
|}
 
|}
  
=== <code>Campaign</code> ===
+
=== <code><big><big><big>Campaign</big></big></big></code> ===
 
{{function parameters}}
 
{{function parameters}}
 
{{returns|The singleton campaign [[API:Function documentation/Roll20 object|Roll20 object]].}}
 
{{returns|The singleton campaign [[API:Function documentation/Roll20 object|Roll20 object]].}}
 
==== Examples ====
 
==== Examples ====
<pre data-language="javascript">var currentPageID = Campaign().get('playerpageid'),
+
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">var currentPageID = Campaign().get('playerpageid'),
 
     currentPage = getObj('page', currentPageID);</pre>
 
     currentPage = getObj('page', currentPageID);</pre>
  
=== <code>createObj</code> ===
+
 
 +
=== <code><big><big><big>createObj</big></big></big></code> ===
 
{{function parameters
 
{{function parameters
 
|type
 
|type
Line 125: Line 137:
 
==== Examples ====
 
==== Examples ====
 
When creating a [[API:Function documentation/Roll20 object|Roll20 object]] that has a parent object (such as creating an attribute [[API:Function documentation/Roll20 object|Roll20 object]], which is a child of a character [[API:Function documentation/Roll20 object|Roll20 object]]), you must supply the id of the parent in <code>attributes</code>.
 
When creating a [[API:Function documentation/Roll20 object|Roll20 object]] that has a parent object (such as creating an attribute [[API:Function documentation/Roll20 object|Roll20 object]], which is a child of a character [[API:Function documentation/Roll20 object|Roll20 object]]), you must supply the id of the parent in <code>attributes</code>.
<pre data-language="javascript">on('add:character', function(obj) {
+
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">on('add:character', function(obj) {
 
     createObj('attribute', {
 
     createObj('attribute', {
 
         name: 'Strength',
 
         name: 'Strength',
Line 135: Line 147:
  
 
When creating a path [[API:Function documentation/Roll20 object|Roll20 object]], you must supply a value for the read-only property <code>_path</code>. This is an exception to the rule that prevents you from setting the value of read-only properties when creating [[API:Function documentation/Roll20 object|Roll20 objects]].
 
When creating a path [[API:Function documentation/Roll20 object|Roll20 object]], you must supply a value for the read-only property <code>_path</code>. This is an exception to the rule that prevents you from setting the value of read-only properties when creating [[API:Function documentation/Roll20 object|Roll20 objects]].
<pre data-language="javascript">createObj('path', {
+
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">createObj('path', {
 
     left: 7000,
 
     left: 7000,
 
     top: 140,
 
     top: 140,
Line 145: Line 157:
  
 
When creating a handout [[API:Function documentation/Roll20 object|Roll20 object]], you cannot set the text or gmnotes at the time of creation.
 
When creating a handout [[API:Function documentation/Roll20 object|Roll20 object]], you cannot set the text or gmnotes at the time of creation.
<pre data-language="javascript">var handout = createObj('handout', {
+
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">var handout = createObj('handout', {
 
     name: 'A Letter Addressed to You',
 
     name: 'A Letter Addressed to You',
 
     inplayerjournals: 'all',
 
     inplayerjournals: 'all',
Line 155: Line 167:
 
});</pre>
 
});</pre>
  
=== <code>filterObjs</code> ===
+
=== <code><big><big><big>filterObjs</big></big></big></code> ===
 
{{function parameters
 
{{function parameters
 
|callback
 
|callback
Line 161: Line 173:
 
{{returns|An array of [[API:Function documentation/Roll20 object|Roll20 objects]] which passed the predicate test.}}
 
{{returns|An array of [[API:Function documentation/Roll20 object|Roll20 objects]] which passed the predicate test.}}
 
==== Examples ====
 
==== Examples ====
<pre data-language="javascript">var tokenName = getMyTokenName(),
+
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">var tokenName = getMyTokenName(),
 
     duplicateTokens = filterObjs(function(obj) {
 
     duplicateTokens = filterObjs(function(obj) {
 
         if (obj.get('type') !== 'graphic' || obj.get('subtype') !== 'token' || obj.get('name') === tokenName) return false;
 
         if (obj.get('type') !== 'graphic' || obj.get('subtype') !== 'token' || obj.get('name') === tokenName) return false;
Line 167: Line 179:
 
     });</pre>
 
     });</pre>
  
=== <code>findObjs</code> ===
+
=== <code><big><big><big>findObjs</big></big></big></code> ===
 
{{function parameters
 
{{function parameters
 
|attributes
 
|attributes
Line 177: Line 189:
 
<pre data-language="javascript">var npcs = findObjs({ type: 'character', controlledby: '' });</pre>
 
<pre data-language="javascript">var npcs = findObjs({ type: 'character', controlledby: '' });</pre>
  
=== <code>getAllObjs</code> ===
+
=== <code><big><big><big>getAllObjs</big></big></big></code> ===
 
{{function parameters}}
 
{{function parameters}}
 
{{returns|An array of all [[API:Function documentation/Roll20 object|Roll20 objects]] in the campaign.}}
 
{{returns|An array of all [[API:Function documentation/Roll20 object|Roll20 objects]] in the campaign.}}
 
==== Examples ====
 
==== Examples ====
<pre data-language="javascript">var everything = getAllObjs();</pre>
+
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">var everything = getAllObjs();</pre>
 +
 
 +
=== <code><big><big><big>getAttrByName</big></big></big></code> ===
 +
{{function parameters
 +
|character_id
 +
|''(String)'' The id of the character [[API:Function documentation/Roll20 object|Roll20 object]] that is the parent of the attribute [[API:Function documentation/Roll20 object|Roll20 object]] you want the value of.
 +
|attribute_name
 +
|''(String)'' The name of the attribute [[API:Function documentation/Roll20 object|Roll20 object]] you want the value of.
 +
|value_type
 +
|''(String, optional)'' Either <code>"current"</code> or <code>"max"</code> (defaults to "current" if omitted).}}
 +
{{returns|The <code>current</code> or <code>max</code> property of the appropriate attribute. If the desired property is not set, the default value specified by the character sheet (if there is a default) will be used instead.}}
 +
==== Examples ====
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">var character = getMyCharacter(),
 +
    strength = getAttrByName(character.id, 'strength'),
 +
    strength_max = getAttrByName(character.id, 'strength', 'max');</pre>
 +
 
 +
=== <code><big><big><big>getObj</big></big></big></code> ===
 +
{{function parameters
 +
|type
 +
|''(String)'' The type of [[API:Function documentation/Roll20 object|Roll20 object]] to get.
 +
|id
 +
|''(String)'' The unique id for the [[API:Function documentation/Roll20 object|Roll20 object]] to get.}}
 +
{{returns|The specified [[API:Function documentation/Roll20 object|Roll20 object]].}}
 +
==== Examples ====
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">on('chat:message', function(msg) {
 +
    var sendingPlayer = getObj('player', msg.playerid);
 +
});</pre>
 +
 
 +
=== <code><big><big><big>log</big></big></big></code> ===
 +
{{function parameters
 +
|message
 +
|''(varies)'' The message to post to the API console. The <code>message</code> parameter will be transformed into a String with <code>JSON.stringify</code>.}}
 +
{{returns}}
 +
==== Examples ====
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">on('chat:message', function(msg) {
 +
    log('Message received from:');
 +
    log(getObj('player', msg.playerid));
 +
});</pre>
 +
<div style="margin:1em;margin-bottom:20px;padding:6px 10px;font-family:Consolas, 'Liberation Mono', Courier, monospace;font-size:13px;border:1px solid #ccc;border-radius:3px;background-color:#272822;color:#e6db74">"Message received from:"<br>
 +
<span style="color:#f8f8f2">{</span>"_d20userid"<span style="color:#f8f8f2">:</span>"123456"<span style="color:#f8f8f2">,</span>"_displayname"<span style="color:#f8f8f2">:</span>"John Doe"<span style="color:#f8f8f2">,</span>"speakingas"<span style="color:#f8f8f2">:</span>""<span style="color:#f8f8f2">,</span>"_online"<span style="color:#f8f8f2">:</span><span style="color:#ae81ff">true</span><span style="color:#f8f8f2">,</span>"color"<span style="color:#f8f8f2">:</span>"#885b68"<span style="color:#f8f8f2">,</span>"_macrobar"<span style="color:#f8f8f2">:</span>"-J16Z-dRU5tleKiKOg0X|-K3F_4q_b1p-Vdiwgn1t"<span style="color:#f8f8f2">,</span>"showmacrobar"<span style="color:#f8f8f2">:</span><span style="color:#ae81ff">true</span><span style="color:#f8f8f2">,</span>"_id"<span style="color:#f8f8f2">:</span>"-J16Z-dRU5tleKiKOc0X"<span style="color:#f8f8f2">,</span>"_type"<span style="color:#f8f8f2">:</span>"player"<span style="color:#f8f8f2">,</span>"_lastpage"<span style="color:#f8f8f2">:</span>""<span style="color:#f8f8f2">}</span></div>
 +
 
 +
=== <code><big><big><big>on</big></big></big></code> ===
 +
{{function parameters
 +
|event
 +
|''(String)'' There are five types of event:
 +
:* ready
 +
:* change
 +
:* add
 +
:* destroy
 +
:* chat
 +
: With the exception of ''ready'', all event types must also be paired with an object type. For ''chat'', this is always ''message''. For everything else, this is the <code>type</code> property of a [[API:Function documentation/Roll20 object|Roll20 object]]. In addition to the object type, ''change'' events can also optionally specify a property of the specified [[API:Function documentation/Roll20 object|Roll20 object]] to watch.
 +
: The 2-3 parts of the event (type, object, and optionally property) are separated by colons. So, valid <code>event</code> strings include but are not limited to "ready", "chat:message", "change:graphic", "change:campaign:playerpageid", "add:character", and "destroy:handout".
 +
|callback
 +
|''(Function)'' The function that will be called when the specified event fires. The parameters passed depend on the event type:
 +
:* ''ready'' events have no callback parameters.
 +
:* ''change'' events have an <code>obj</code> parameter, which is a reference to the [[API:Function documentation/Roll20 object|Roll20 object]] as it exists after the change, and a <code>prev</code> parameter, which is a plain old JavaScript object with properties matching the [[API:Function documentation/Roll20 object|Roll20 object]] prior to the change event.
 +
:* ''add'' events have an <code>obj</code> parameter, which is a reference to the new [[API:Function documentation/Roll20 object|Roll20 object]].
 +
:* ''destroy'' events have an <code>obj</code> parameter, which is a reference to the no-longer existing [[API:Function documentation/Roll20 object|Roll20 object]].
 +
:* ''chat'' events have a <code>msg</code> parameter, which contains the details of the message that was sent to the chat.}}
 +
{{returns}}
 +
==== Examples ====
 +
Events are fired in the order they were registered, and from most to least specific. In this example, a change to a graphic [[API:Function documentation/Roll20 object|Roll20 object's]] <code>left</code> property will result in <code>function3</code> getting called, followed by <code>function1</code> and then <code>function2</code>.
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">on('change:graphic', function1);
 +
on('change:graphic', function2);
 +
on('change:graphic:left', function3);</pre>
 +
 
 +
''add'' events will attempt to fire for [[API:Function documentation/Roll20 object|Roll20 objects]] that are already in the campaign when a new session starts. In order to prevent this behavior, you can wait to register your ''add'' event until the ''ready'' event fires.
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">on('add:graphic', function(obj) {
 +
    // When the session begins, this function will be called for every graphic in the campaign
 +
    // This function will also be called whenever a new graphic Roll20 object is created
 +
});
 +
 
 +
on('ready', function() {
 +
    on('add:graphic', function(obj) {
 +
        // This function will *only* be called when a new graphic Roll20 object is created, not for ones that already exist
 +
    });
 +
});</pre>
 +
 
 +
The <code>prev</code> parameter for ''change'' events is not a [[API:Function documentation/Roll20 object|Roll20 object]], it is a plain old JavaScript object. As such, you cannot use the <code>get</code> or <code>set</code> functions, and you cannot omit the leading underscores on read-only properties.
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">on('change:graphic', function(obj, prev) {
 +
    var id1 = obj.id,        // all three are equivalent
 +
        id2 = obj.get('id'),
 +
        id3 = obj.get('_id'),
 +
 
 +
        id4 = prev.id,        // undefined
 +
        id5 = prev.get('id'), // undefined is not a function
 +
        id6 = prev._id;      // correct
 +
 
 +
    // both are equivalent
 +
    obj.set('left', 70);
 +
    obj.set({
 +
        left: 70
 +
    });
 +
 
 +
    prev.set('left', 70); // undefined is not a function
 +
    prev.set({            // undefined is not a function
 +
        left: 70
 +
    });
 +
    prev.left = 70;      // correct, although it won't change anything on the tabletop
 +
});</pre>
 +
 
 +
For the async fields of character and handout [[API:Function documentation/Roll20 object|Roll20 objects]] (<code>notes</code>, <code>gmnotes</code>, and <code>bio</code>), the <code>prev</code> parameter will not hold the data you need. (It will have a numeric identifier used by the system instead.) If you need to access the previous value of one of these fields, you will have to keep track of it yourself:
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">on('ready', function() {
 +
    if (!state.example) state.example = { bioCache: {} };
 +
});
 +
 
 +
on('change:character:bio', function(obj, prev) {
 +
    obj.get('bio', function(text) {
 +
        state.example.bioCache[obj.id] = text;
 +
 
 +
        // do stuff...
 +
 
 +
        if (shouldRevertBio()) {
 +
            obj.set('bio', state.example.bioCache[obj.id]);
 +
        }
 +
    });
 +
});</pre>
 +
 
 +
 
 +
 
 +
=== <code><big><big><big>playerIsGM</big></big></big></code> ===
 +
{{function parameters
 +
|player_id
 +
|''(String)'' The id of the player [[API:Function documentation/Roll20 object|Roll20 object]] to check.}}
 +
{{returns|<code>true</code> if the [[player]] currently has [[GM]] permissions, or <code>false</code> otherwise..}}
 +
==== Examples ====
 +
This function is especially useful for limiting API commands to [[GM]] use.
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">on('chat:message', function(msg) {
 +
    if (msg.type !== 'api') return;
 +
 
 +
    if (msg.content.indexOf('!playercommand') === 0) {
 +
        // ...
 +
    } else if (msg.content.indexOf('!gmcommand') === 0) {
 +
        if (!playerIsGM(msg.playerid)) return;
 +
        // ...
 +
    }
 +
});</pre>
 +
 
 +
 
 +
=== <code><big><big><big>randomInteger</big></big></big></code> ===
 +
{{function parameters
 +
|max
 +
|''(Number)'' The maximum number to return, inclusive.}}
 +
{{returns|A random integer between 1 (inclusive) and <code>max</code> (inclusive). This function has better distribution than <code>Math.random()</code>, and is recommended over it. This function doesn't make use of the [[Quantum Roll]] feature used by the dice engine, but it does use the same pseudorandom algorithm that the dice engine will fall back on if Quantum Roll is unavailable.}}
 +
==== Examples ====
 +
Because this function returns an integer from 1 to <code>max</code>, it is ideal for quickly generating a dice roll outcome if you don't need the full strength of Roll20's [[Dice Reference|dice engine]].
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">var d20Result = randomInteger(20); // roughly equivalent to rolling a 20-sided die</pre>
 +
 
 +
 
 +
=== <code><big><big><big>sendChat</big></big></big></code> {{asynchronous}} ===
 +
{{function parameters
 +
|speakingAs
 +
|''(String)'' The name to attach to the message being sent. If <code>speakingAs</code> is in the format <code>player{{!}}player_id</code> or <code>character{{!}}character_id</code>, the message will be sent as that player or character. Otherwise, the message will use the given name as though a GM had used the '''/as''' command.
 +
|message
 +
|''(String)'' The message to send to the chat.
 +
|callback
 +
|''(Function, optional)'' If <code>callback</code> is specified, the result of the chat message will be passed to it instead of appearing in the chat. The parameter of the callback method is an array of message objects.
 +
|options
 +
|''(Object, optional)'' If <code>options.noarchive</code> is <code>true</code>, the message will not be added to the chat archive. If <code>options.use3d</code> is <code>true</code>, dice rolls in the message will use the 3D dice feature. Options are not applicable if <code>callback</code> is specified.}}
 +
{{returns}}
 +
==== Examples ====
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">sendChat('Example', 'This is a simple example.');</pre>
 +
 
 +
You can easily write code to send a message as the same player or character that triggered a ''chat:message'' event.
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">on('chat:message', function(msg) {
 +
    var character = findObjs({ type: 'character', name: msg.who })[0],
 +
        player = getObj('player', msg.playerid),
 +
        message = ' said something';
 +
 
 +
    if (character) sendChat('character|'+character.id, character.get('name')+message);
 +
    else sendChat('player|'+player.id, player.get('displayname')+message);
 +
});</pre>
 +
 
 +
The <code>callback</code> parameter is useful if you need to leverage Roll20's [[Dice Reference|dice engine]]. There is no particular need for a <code>speakingAs</code> value when using the <code>callback</code>, since the message won't appear in the chat anyway.
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">sendChat('', '/r 2d20k1+'+strengthMod, function(ops) {
 +
    var msg = ops[0];
 +
    // ...
 +
});</pre>
 +
 
 +
<code>options.noarchive</code> is primarily designed for sending players menus made from [[API:Chat#API Command Buttons|API Command buttons]] without clogging their chat history.
 +
<pre data-language="javascript">sendChat('System', '[Clear changes](!clear)\n[Add tile](!add)\n[View sample](!view)\n[Save layout](!save)', null, { noarchive: true });</pre>
 +
 
 +
 
 +
 
 +
 
 +
=== <code><big><big><big>sendPing</big></big></big></code> ===
 +
{{function parameters
 +
|left
 +
|''(Number)'' The x-coordinate to place the ping at.
 +
|top
 +
|''(Number)'' The y-coordinate to place the ping at.
 +
|page_id
 +
|''(String)'' The id of the page [[API:Function documentation/Roll20 object|Roll20 object]] to place the ping on.
 +
|player_id
 +
|''(String, optional)'' The ping will use the specified player's color. If <code>player_id</code> is omitted, the ping will be yellow.
 +
|moveAll
 +
|''(Boolean, optional)'' If <code>moveAll</code> is <code>true</code>, all of the players on the appropriate page will have their views centered on the ping. If no value is provided for moveAll, it defaults to false; when it is false, no players are moved, but the ping is visible to everyone.
 +
|visibleTo
 +
|''(String, Array, Variable, optional)'' Specifies one or more  [[players]] that will receive the ping. If at least one player is specified, no other players will see the ping or be moved.
 +
 
 +
Note: If sending to a single player, you can include their player ID as a string or variable.
 +
 
 +
If sending multiple IDs, they can be included either as an array, or as a comma-delimited text string.
 +
 
 +
The [[player]] ID [[API:Utility_Functions|can be obtained using the findObjs() function]] and you can then use playerIsGM(playerID) to determine if an individual player ID is a [[GM]]. In this way, you should be able to find and pass in the player IDs of GMs into the sendPing function.
 +
 
 +
 
 +
}}
 +
{{returns}}
 +
 
 +
==== Examples ====
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">on('chat:message', function(msg) {
 +
    var obj;
 +
    if (msg.type === 'api' && msg.content.indexOf('!ping') === 0) {
 +
        if (!msg.selected) return;
 +
        obj = getObj(msg.selected[0]._type, msg.selected[0]._id);
 +
        sendPing(obj.get('left'), obj.get('top'), obj.get('pageid'), msg.playerid, true); // center everyone on the selected token
 +
    }
 +
});</pre>
 +
 
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">const getGMPlayers = (pageid) => findObjs({type:'player'})
 +
    .filter((p)=>playerIsGM(p.id))
 +
    .filter((p)=>undefined === pageid || p.get('lastpage') === pageid)
 +
    .map(p=>p.id)
 +
    ;
 +
 
 +
const sendGMPing = (left, top, pageid, playerid=null, moveAll=false) => {
 +
    let players = getGMPlayers(pageid);
 +
    if(players.length){
 +
        sendPing(left,top,pageid,playerid,moveAll,players);
 +
    }
 +
};</pre>
 +
 
 +
==Cards==
 +
{{source|https://app.roll20.net/forum/permalink/6223396/ API Updates - 3/27/2018}}
 +
These functions were structured so that playing a card mimics how you would do that in real life. You first must pick up a card, by taking a card from the deck, table or from another player (drawCard, pickUpCard, and takeCardFromPlayer, respectively). With the card now in hand, you can now either play it to the table (playCardToTable) or give it to a player (giveCardToPlayer).
 +
 
 +
Using any of the 'take' functions will remove the card from play and return the id for that card, and also add the card to the discard pile. This is to prevent unpredictable behavior that may result from having a card completely unaccounted for. However, if you immediately use a 'play' function using the returned card id, the card will be put back in play before the discard pile is updated, so that the players will not see the card get added to the discard pile. If you wish to hold on to a card before playing it and you do not wish for it to end up in the discard pile, consider playing the card to the table on the GM layer, or perhaps to a page that the players aren't currently on.
 +
 
 +
Playing a card without first using a 'take' function could lead to duplicates that may not behave as you expect. Depending on deck settings and where the duplicates are in play, the game may (or may not) remove one of the duplicates automatically. Regardless, when cards are recalled and the deck is shuffled, the game will ensure there are no duplicate cards in the deck.
 +
 
 +
It's worth noting that the 'take' functions are also the best way to discard a card. You can simply call 'destroy' on a card played to the table, or manually remove a cardid from a player's currentHand, and these cards will eventually end up in the discard pile. However, it would be difficult to predict when the discard pile will be updated, and if multiple cards are removed this way, they may not wind up in the discard pile in the correct order for this reason. Using one of the 'take' functions will automatically update the discard pile each time one is called, ensuring that cards are discarded in the order they are removed.
 +
 
 +
=== <code><big><big><big>cardInfo</big></big></big></code> ===
 +
 
 +
<pre style="overflow:auto;white-space:pre-wrap;">cardInfo( { options } )</pre>
 +
 
 +
Returns information about a group of cards, or one specific card. This function accepts the following options:
 +
 
 +
<pre style="overflow:auto;white-space:pre-wrap;">{
 +
  type: "hand", "graphic", "discard", "play", "deck", "all", "card" //Required. Determines what kind of results are returned.
 +
  deckid: deckid //Required for all types except 'card'. Determines which deck to return information about.
 +
  cardid: cardid //Required for type 'card'. Determines which card to return information about.
 +
  discard: true/false //Optional. Determines whether result will include cards in the discard pile. Ignored for types 'card', 'all', and 'discard'. Defaults to 'false' if omitted.
 +
}</pre>
 +
 
 +
As noted above, the type will determine what results are returned. "card" returns a single object containing information about the card corresponding to cardid, with the following format:
 +
 
 +
<pre style="overflow:auto;white-space:pre-wrap;">{
 +
  type: "graphic", "hand", "deck", or "discard",
 +
  id: The id of the graphic, hand, or deck containing the card. Omitted for type "discard",
 +
  cardid: The id of the card,
 +
  pageid: The id of the page containing the graphic. Omitted for other types,
 +
  playerid: The id of the player holding the card. Omitted for other types,
 +
  index: The position of the card in the hand or discard pile. Omitted for types "graphic" and "deck"
 +
}</pre>
 +
 
 +
The other types return an array of these objects. "hand" will return info on all cards in that deck that are currently in player's hands. "graphic" returns info on the cards of that deck currently on the table. "discard" returns only the cards that are in the discard pile, and "deck" returns the cards that are still in the deck. "play" returns a combination of "hand" and "graphic", and "all" returns all cards belonging to that deck. You can also include the setting discard: true to include the cards in the discard pile in the results. This has no effect on the types "discard" and "all".
 +
 
 +
If the function fails, it will return false. If no information is retrieved, it will return an empty array.
 +
 
 +
 
 +
=== <code><big><big><big>recallCards</big></big></big></code> ===
 +
 
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">recallCards(deckid, type(optional) )</pre>
 +
 
 +
Functions identically to using the 'recall' dialog on a deck. The type parameter is a string that determines which which cards are recalled, the valid types are hand, graphic, and all. If omitted, the type defaults to 'all'. Will return false if the function fails, returns true if successful.
 +
 
 +
=== <code><big><big><big>shuffleDeck</big></big></big></code> ===
 +
 
 +
 
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">shuffleDeck(deckid, discard(optional), deckOrder(optional) )</pre>
 +
 
 +
Shuffles a deck. If this is called with only the deckid passed in, it is identical to clicking the 'Shuffle' button, except any errors encounter will log to the api console instead of producing a browser alert.
 +
 
 +
The second parameter allows you to specify whether or not to shuffle the discard pile back into the deck. The default is true, which shuffles the discard pile back into the deck as it would normally when clicking the shuffle button. Passing in 'false' will leave the discard pile as it is and only shuffle the remaining cards in the deck.
 +
 
 +
If you call this function with an array of card ids as the second parameter, the deck will be re-shuffled and put in the order of that array. Note that the cards in this array must match the cards left in the deck exactly (plus the discard pile, if you specify discard = true), or it will fail with an error.
 +
 
 +
You can use the provided cardInfo function, in combination with the _.pluck function from the underscore.js library to easily get the list of cards the function expects, like so: _.pluck(cardInfo({type: "deck", deckid: deck.id, discard: (true/false, depending) }), "cardid").
 +
 
 +
Will return false if the function fails, returns an array of card ids representing the new deck order if successful.
 +
 
 +
=== <code><big><big><big>drawCard</big></big></big></code> ===
 +
 
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">drawCard(deckid, cardid(optional) )</pre>
 +
 
 +
Draws a card from a deck. You can pass in a card id to draw a specific card from the deck. If this is omitted, it will draw the top card.The function returns the id of the drawn card if successful, and false if it fails.
 +
 
 +
=== <code><big><big><big>pickUpCard</big></big></big></code> ===
 +
 
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">pickUpCard(cardid, fromDiscard(optional) )</pre>
 +
 
 +
Picks up a card from the table (if fromDiscard is false or omitted), or from the discard pile (if fromDiscard is true).
 +
Note that it isn't necessary to use this function to play a card from the discard pile, as using giveCardToPlayer or playCardToTable will automatically remove the card from the discard pile if it is there. However, this function may be useful as it will return false if the card is not in the discard pile.
 +
The function returns the id of the card if successful, and false if it fails.
 +
 
 +
=== <code><big><big><big>takeCardFromPlayer</big></big></big></code> ===
 +
 
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">takeCardFromPlayer(playerid, options(optional) )</pre>
 +
 
 +
Takes a card from the player with id playerid. If options are omitted, it will take a random card from that player's hand. You can add properties to the options to specify a card to take, "index" to specify an index of the currentHand array, or "cardid" to specify a card by id.
 +
By default, the function will remove the card from the players hand and return the id for that card. However, you can add the property "steal" to the options parameter, and give it a player's id to trigger the steal card dialog for that player. This functions identically to clicking on 'Steal Card' in another player's hand. Note that although this still returns the card id, the card will remain in a player's hand and should not be played elsewhere without being removed from the hand.
 +
 
 +
Returns the id of the card if successful, and false if it fails. Note that if the 'steal' option is used, the function will return a card id, but this does not necessarily mean that the card changed hands, as that will be up to the player to approve or deny the steal request.
 +
 
 +
=== <code><big><big><big>giveCardToPlayer</big></big></big></code> ===
 +
 
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">giveCardToPlayer(cardid, playerid)</pre>
 +
 
 +
Gives a card (with id cardid) to a player (with id playerid).
 +
 
 +
=== <code><big><big><big>playCardToTable</big></big></big></code> ===
 +
 
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">playCardToTable(cardid, settings(optional) )</pre>
 +
 
 +
Plays a card (with id cardid) to the table. The settings parameter can be used to customize the resulting token, if omitted default settings will be used. Here are the possible settings with their defaults:
 +
 
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">{
 +
  left: X position in pixels. Defaults to the center of the page.
 +
  top: Y position in pixels. Defaults to the center of the page.
 +
  width: width of token in pixels. Defaults to the deck's defaultwidth, or to 98 if the deck has no default.
 +
  height: height of token in pixels. Defaults to the deck's defaultheight, or to 140 if the deck has no default.
 +
  layer: the layer the token will appear on. Defaults to the objects layer.
 +
  pageid: the page the token is played to. Defaults to the current player page.
 +
  isdrawing: whether to treat the token as a drawing. Uses the deck "treatasdrawing" as the default.
 +
  currentSide: whether the card is played face up or face down, with 0 being face up and 1 being face down. Defaults to the deck's default setting.
 +
}</pre>
 +
 
 +
=== <code><big><big><big>dealCardsToTurn</big></big></big></code> ===
 +
 
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">dealCardsToTurn(deckid)</pre>
 +
 
 +
Deals a card from the deck to each object in the turn order. Functions identically to clicking the 'Deal cards to turn order items' in the 'Deal cards' dialog box. Note that in this case, any errors encountered (for example, if you run out of cards before you finish dealing) will produce a browser alert in the same way as if the user clicked the button themselves.
 +
 
 +
 
 +
==Character==
 +
=== <code><big><big><big>onSheetWorkerCompleted</big></big></big></code> ===
 +
{{function parameters
 +
|callback
 +
|''(Function)'' The function that will be called when the current 'stack' of [[Sheet Worker Scripts]] completes.}}
 +
{{returns}}
 +
==== Examples ====
 +
This function is intended to be called prior to [[API:Function documentation/Roll20 object#setWithWorker|setWithWorker]]. The <code>callback</code> function will be called only once.
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">var myCharacter = ...,
 +
    mySourceAttr = findObjs({ type: 'attribute', characterid: myCharacter.id, name: 'mySourceAttribute' })[0];
 +
 
 +
onSheetWorkerCompleted(function() {
 +
    var calculatedAttr = findObjs({ type: 'attribute', characterid: myCharacter.id, name: 'myCalculatedAttribute' })[0];
 +
    // do something with calculatedAttr.get('current');
 +
});
 +
 
 +
mySourceAttr.setWithWorker({ current: 5 });</pre>
 +
 
 +
=== <code><big><big><big>setAttrs</big></big></big></code> ===
 +
<pre style="overflow:auto;white-space:pre-wrap;">setAttrs(character_id, attribute_obj, settings(optional))</pre>
 +
 
 +
This function works like the setAttrs sheet worker function, except that the first argument must be the id of the character whose attributes you are changing. The second argument must be an object containing the attributes and values you wish to change, in the format attribute_name: value. This function can be used with the defaults variable to easily create characters with the game's default settings by simply passing in defaults.sheet as the second parameter. By default, this function will trigger sheet workers, this can be disabled by passing in "{silent: true}" as a third parameter.
 +
 
 +
==Graphic==
 +
=== <code><big><big><big>toBack</big></big></big></code> ===
 +
{{function parameters
 +
|obj
 +
|''([[API:Function documentation/Roll20 object|Roll20 object]])'' The [[API:Function documentation/Roll20 object|Roll20 object]] to send to the back of its layer.}}
 +
{{returns}}
 +
==== Examples ====
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">on('chat:message', function(msg) {
 +
    if (msg.type === 'api' && msg.content === '!toback' && msg.selected) {
 +
        _.each(msg.selected, (s) => {
 +
            toBack(getObj(s._type, s._id));
 +
        });
 +
    }
 +
});</pre>
 +
 
 +
=== <code><big><big><big>toFront</big></big></big></code> ===
 +
{{function parameters
 +
|obj
 +
|''([[API:Function documentation/Roll20 object|Roll20 object]])'' The [[API:Function documentation/Roll20 object|Roll20 object]] to bring to the front of its layer.}}
 +
{{returns}}
 +
==== Examples ====
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">on('ready', function() {
 +
    on('add:graphic', function(obj) {
 +
        toFront(obj);
 +
    });
 +
});</pre>
 +
 
 +
==Fx==
 +
=== <code><big><big><big>spawnFx</big></big></big></code> ===
 +
{{function parameters
 +
|left
 +
|''(Number)'' The x-coordinate to place the particle emitter.
 +
|top
 +
|''(Number)'' The y-coordinate to place the particle emitter.
 +
|type
 +
|''(String)'' The type of particle emitter to place. For built-in effects, this should be <code>"type-color"</code>, where ''type'' is one of <code>bomb</code>, <code>bubbling</code>, <code>burn</code>, <code>burst</code>, <code>explode</code>, <code>glow</code>, <code>missile</code>, or <code>nova</code> and ''color'' is one of <code>acid</code>, <code>blood</code>, <code>charm</code>, <code>death</code>, <code>fire</code>, <code>frost</code>, <code>holy</code>, <code>magic</code>, <code>slime</code>, <code>smoke</code>, or <code>water</code>. For custom effects, this should be the <code>id</code> of the FX [[API:Function documentation/Roll20 object|Roll20 object]].
 +
: ''Note: <code>beam</code>, <code>breath</code>, and <code>splatter</code> types cannot be used with <code>spawnFx</code>. See <code>[[#spawnFxBetweenPoints|spawnFxBetweenPoints]]</code> instead.''
 +
|page_id
 +
|''(String, optional)'' The id of the page [[API:Function documentation/Roll20 object|Roll20 object]] to place the particle emitter on. If omitted, <code>Campaign().get('playerpageid')</code> will be used instead.}}
 +
{{returns}}
 +
==== Examples ====
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">spawnFx(1400, 1400, 'bubbling-acid');</pre>
 +
 
 +
=== <code><big><big><big>spawnFxBetweenPoints</big></big></big></code> ===
 +
{{function parameters
 +
|start
 +
|''(Object)'' The starting point for the particle emitter. The point should be in the format <code>{ x: ''number'', y: ''number'' }</code>.
 +
|end
 +
|''(Object)'' The ending point for the particle emitter. The point should be in the format <code>{ x: ''number'', y: ''number'' }</code>.
 +
|type
 +
|''(String)'' The type of particle emitter to place. For built-in effects, this should be <code>"type-color"</code>, where ''type'' is one of <code>beam</code>, <code>bomb</code>, <code>breath</code>, <code>bubbling</code>, <code>burn</code>, <code>burst</code>, <code>explode</code>, <code>glow</code>, <code>missile</code>, <code>nova</code>, or <code>splatter</code> and ''color'' is one of <code>acid</code>, <code>blood</code>, <code>charm</code>, <code>death</code>, <code>fire</code>, <code>frost</code>, <code>holy</code>, <code>magic</code>, <code>slime</code>, <code>smoke</code>, or <code>water</code>. For custom effects, this should be the <code>id</code> of the FX [[API:Function documentation/Roll20 object|Roll20 object]].
 +
|page_id
 +
|''(String, optional)'' The id of the page [[API:Function documentation/Roll20 object|Roll20 object]] to place the particle emitter on. If omitted, <code>Campaign().get('playerpageid')</code> will be used instead.}}
 +
{{returns}}
 +
==== Examples ====
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">spawnFxBetweenPoints({ x: 1400, y: 1400 }, { x: 2100, y: 2100 }, 'beam-acid');</pre>
 +
 
 +
=== <code><big><big><big>spawnFxWithDefinition</big></big></big></code> ===
 +
{{function parameters
 +
|left
 +
|''(Number)'' The x-coordinate to place the particle emitter.
 +
|top
 +
|''(Number)'' The y-coordinate to place the particle emitter.
 +
|definition
 +
|''(Object)'' The characteristics of the particle emitter to place. See [[Custom FX]] for a list of possible properties and the properties of the default particle emitter types and colors. See [[FX Library]] for some custom effects Roll20 users have come up with.
 +
|page_id
 +
|''(String, optional)'' The id of the page [[API:Function documentation/Roll20 object|Roll20 object]] to place the particle emitter on. If omitted, <code>Campaign().get('playerpageid')</code> will be used instead.}}
 +
{{returns}}
 +
==== Examples ====
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">// these two are equivalent
 +
spawnFx(1400, 1400, 'bubbling-acid');
 +
spawnFxWithDefinition(1400, 1400, {
 +
    maxParticles: 200,
 +
    size: 15,
 +
    sizeRandom: 3,
 +
    lifeSpan: 20,
 +
    lifeSpanRandom: 5,
 +
    speed: 7,
 +
    speedRandom: 2,
 +
    gravity: { x: 0.01, y: 0.65 },
 +
    angle: 270,
 +
    angleRandom: 35,
 +
    emissionRate: 1,
 +
    startColour:      [0, 35, 10, 1],
 +
    startColourRandom: [0, 10, 10, 0.25],
 +
    endColour:        [0, 75, 30, 0],
 +
    endColourRandom:  [0, 20, 20, 0]
 +
});</pre>
 +
 
 +
==Jukebox==
 +
=== <code><big><big><big>playJukeboxPlaylist</big></big></big></code> ===
 +
'''Note:''' Using {{Jukebox}}/soundcloud(is SC removed?) functions will not throw errors, but they no longer do anything.
 +
[http://blog.roll20.net/post/150968376980/in-regards-to-soundcloud "In Regards to SoundCloud"]
 +
 
 +
{{function parameters
 +
|playlist_id
 +
|''(String)'' The id of the playlist to start playing.}}
 +
{{returns}}
 +
==== Examples ====
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">var playlists = JSON.parse(Campaign().get('jukeboxfolder')),
 +
    myPlaylist = _.find(playlists, (folder) => _.isObject(folder) && folder.n === myPlaylistName);
 +
playJukeboxPlaylist(myPlaylist.id);</pre>
 +
 
 +
 
 +
=== <code><big><big><big>stopJukeboxPlaylist</big></big></big></code> ===
 +
{{function parameters}}
 +
{{returns}}
 +
==== Examples ====
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">stopJukeboxPlaylist();</pre>
  
=== <code>getAttrByName</code> ===
+
[[Category:API Development]]
=== <code>getObj</code> ===
+
=== <code>log</code> ===
+
=== <code>on</code> ===
+
=== <code>playerIsGM</code> ===
+
=== <code>playJukeboxPlaylist</code> ===
+
=== <code>randomInteger</code> ===
+
=== <code>sendChat</code> ===
+
=== <code>sendPing</code> ===
+
=== <code>spawnFx</code> ===
+
=== <code>spawnFxBetweenPoints</code> ===
+
=== <code>spawnFxWithDefinition</code> ===
+
=== <code>stopJukeboxPlaylist</code> ===
+
=== <code>toBack</code> ===
+
=== <code>toFront</code> ===
+

Latest revision as of 08:32, 9 June 2024

Attention: This page is community-maintained. For the official Roll20 version of this article, see the Help Center for assistance: here .

Roll20 makes a number of functions available that are not part of core JavaScript or some other library.


Contents


[edit] Global variables

Variable Description
_ This is the namespace object for the Underscore.js library.
state Properties of the state object will persist between game sessions.

[edit] _ (Underscore)

This is the namespace object for the Underscore.js library. Underscore has many functions for collection manipulation.

[edit] state

Properties of the state object will persist between game sessions. The same state object is also shared between all API scripts in a campaign, so it is strongly recommended that when writing values to state, you minimize your footprint as much as possible in order to avoid name collisions. Note: state gets serialized with JSON, so you cannot store functions or objects with cyclical references.

[edit] Global functions

Return type Function Description
Roll20 object Campaign Gets the singleton Campaign Roll20 object.
Roll20 object createObj Creates a new Roll20 object.
Array of Roll20 objects filterObjs Gets all Roll20 objects which pass a predicate test.
Array of Roll20 objects findObjs Gets all Roll20 objects with properties that match a given set of attributes.
Array of Roll20 objects getAllObjs Gets all Roll20 objects in the campaign.
varies getAttrByName Gets the current or max value of an attribute Roll20 object.
Roll20 object getObj Gets a specific Roll20 object.
log Logs a message to the API Console.
on Registers an event handler.
onSheetWorkerCompleted Registers a one-time event handler to run after a full stack of Sheet Worker Scripts completes.
Boolean playerIsGM Checks whether a player currently has GM privileges.
playJukeboxPlaylist Start playing a u Jukebox playlist.
Number randomInteger Generates a random integer value.
sendChat Sends a chat message.
sendPing Sends a ping similar to holding the left mouse button.
spawnFx Spawns a particle emitter.
spawnFxBetweenPoints Spawns a particle emitter that moves from one point to another.
spawnFxWithDefinition Spawns a particle emitter that is not represented by an FX Roll20 object.
stopJukeboxPlaylist Stops all currently playing jukebox playlists.
toBack Moves a graphic Roll20 object below all of the other graphics on the same tabletop layer.
toFront Moves a graphic Roll20 object above all of the other graphics on the same tabletop layer.

[edit] Campaign

Parameters

No parameters

Returns

The singleton campaign Roll20 object.

[edit] Examples

var currentPageID = Campaign().get('playerpageid'),
    currentPage = getObj('page', currentPageID);


[edit] createObj

Parameters

type
(String) The type of Roll20 object to create. Only 'graphic', 'text', 'path', 'character', 'ability', 'attribute', 'handout', 'rollabletable', 'tableitem', and 'macro' may be created.
attributes
(Object) The initial values to use for the Roll20 object's properties.

Returns

The Roll20 object that was created.

[edit] Examples

When creating a Roll20 object that has a parent object (such as creating an attribute Roll20 object, which is a child of a character Roll20 object), you must supply the id of the parent in attributes.

on('add:character', function(obj) {
    createObj('attribute', {
        name: 'Strength',
        current: 0,
        max: 30,
        characterid: obj.id
    });
});

When creating a path Roll20 object, you must supply a value for the read-only property _path. This is an exception to the rule that prevents you from setting the value of read-only properties when creating Roll20 objects.

createObj('path', {
    left: 7000,
    top: 140,
    width: 140,
    height: 140,
    layer: 'objects',
    path: JSON.stringify([['M', 0, 0], ['L', 70, 0], ['L', 0, 70], ['L', 0, 0]])
});

When creating a handout Roll20 object, you cannot set the text or gmnotes at the time of creation.

var handout = createObj('handout', {
    name: 'A Letter Addressed to You',
    inplayerjournals: 'all',
    archived: false
});
handout.set({
    notes: 'Notes can only be set after the handout is created',
    gmnotes: 'GM Notes can only be set after the handout is created'
});

[edit] filterObjs

Parameters

callback
(Function) A predicate function to test all Roll20 objects against. The callback function receives a Roll20 object as a parameter, and should return either true (for Roll20 objects that will be included in the filterObjs return value) or false (for all other Roll20 objects).

Returns

An array of Roll20 objects which passed the predicate test.

[edit] Examples

var tokenName = getMyTokenName(),
    duplicateTokens = filterObjs(function(obj) {
        if (obj.get('type') !== 'graphic' || obj.get('subtype') !== 'token' || obj.get('name') === tokenName) return false;
        return obj.get('name').indexOf(tokenName) === 0 && /\d+$/.text(obj.get('name'));
    });

[edit] findObjs

Parameters

attributes
(Object) A collection of key:value pairs to match with Roll20 objects in the campaign.
options
(Object, optional) If options.caseInsensitive is true, string comparisons between Roll20 objects and attributes will be case-insensitive.

Returns

An array of Roll20 objects with properties that match attributes.

[edit] Examples

var npcs = findObjs({ type: 'character', controlledby: '' });

[edit] getAllObjs

Parameters

No parameters

Returns

An array of all Roll20 objects in the campaign.

[edit] Examples

var everything = getAllObjs();

[edit] getAttrByName

Parameters

character_id
(String) The id of the character Roll20 object that is the parent of the attribute Roll20 object you want the value of.
attribute_name
(String) The name of the attribute Roll20 object you want the value of.
value_type
(String, optional) Either "current" or "max" (defaults to "current" if omitted).

Returns

The current or max property of the appropriate attribute. If the desired property is not set, the default value specified by the character sheet (if there is a default) will be used instead.

[edit] Examples

var character = getMyCharacter(),
    strength = getAttrByName(character.id, 'strength'),
    strength_max = getAttrByName(character.id, 'strength', 'max');

[edit] getObj

Parameters

type
(String) The type of Roll20 object to get.
id
(String) The unique id for the Roll20 object to get.

Returns

The specified Roll20 object.

[edit] Examples

on('chat:message', function(msg) {
    var sendingPlayer = getObj('player', msg.playerid);
});

[edit] log

Parameters

message
(varies) The message to post to the API console. The message parameter will be transformed into a String with JSON.stringify.

Returns

(Void)

[edit] Examples

on('chat:message', function(msg) {
    log('Message received from:');
    log(getObj('player', msg.playerid));
});
"Message received from:"
{"_d20userid":"123456","_displayname":"John Doe","speakingas":"","_online":true,"color":"#885b68","_macrobar":"-J16Z-dRU5tleKiKOg0X|-K3F_4q_b1p-Vdiwgn1t","showmacrobar":true,"_id":"-J16Z-dRU5tleKiKOc0X","_type":"player","_lastpage":""}

[edit] on

Parameters

event
(String) There are five types of event:
  • ready
  • change
  • add
  • destroy
  • chat
With the exception of ready, all event types must also be paired with an object type. For chat, this is always message. For everything else, this is the type property of a Roll20 object. In addition to the object type, change events can also optionally specify a property of the specified Roll20 object to watch.
The 2-3 parts of the event (type, object, and optionally property) are separated by colons. So, valid event strings include but are not limited to "ready", "chat:message", "change:graphic", "change:campaign:playerpageid", "add:character", and "destroy:handout".
callback
(Function) The function that will be called when the specified event fires. The parameters passed depend on the event type:
  • ready events have no callback parameters.
  • change events have an obj parameter, which is a reference to the Roll20 object as it exists after the change, and a prev parameter, which is a plain old JavaScript object with properties matching the Roll20 object prior to the change event.
  • add events have an obj parameter, which is a reference to the new Roll20 object.
  • destroy events have an obj parameter, which is a reference to the no-longer existing Roll20 object.
  • chat events have a msg parameter, which contains the details of the message that was sent to the chat.

Returns

(Void)

[edit] Examples

Events are fired in the order they were registered, and from most to least specific. In this example, a change to a graphic Roll20 object's left property will result in function3 getting called, followed by function1 and then function2.

on('change:graphic', function1);
on('change:graphic', function2);
on('change:graphic:left', function3);

add events will attempt to fire for Roll20 objects that are already in the campaign when a new session starts. In order to prevent this behavior, you can wait to register your add event until the ready event fires.

on('add:graphic', function(obj) {
    // When the session begins, this function will be called for every graphic in the campaign
    // This function will also be called whenever a new graphic Roll20 object is created
});

on('ready', function() {
    on('add:graphic', function(obj) {
        // This function will *only* be called when a new graphic Roll20 object is created, not for ones that already exist
    });
});

The prev parameter for change events is not a Roll20 object, it is a plain old JavaScript object. As such, you cannot use the get or set functions, and you cannot omit the leading underscores on read-only properties.

on('change:graphic', function(obj, prev) {
    var id1 = obj.id,         // all three are equivalent
        id2 = obj.get('id'),
        id3 = obj.get('_id'),

        id4 = prev.id,        // undefined
        id5 = prev.get('id'), // undefined is not a function
        id6 = prev._id;       // correct

    // both are equivalent
    obj.set('left', 70);
    obj.set({
        left: 70
    });

    prev.set('left', 70); // undefined is not a function
    prev.set({            // undefined is not a function
        left: 70
    });
    prev.left = 70;       // correct, although it won't change anything on the tabletop
});

For the async fields of character and handout Roll20 objects (notes, gmnotes, and bio), the prev parameter will not hold the data you need. (It will have a numeric identifier used by the system instead.) If you need to access the previous value of one of these fields, you will have to keep track of it yourself:

on('ready', function() {
    if (!state.example) state.example = { bioCache: {} };
});

on('change:character:bio', function(obj, prev) {
    obj.get('bio', function(text) {
        state.example.bioCache[obj.id] = text;

        // do stuff...

        if (shouldRevertBio()) {
            obj.set('bio', state.example.bioCache[obj.id]);
        }
    });
});


[edit] playerIsGM

Parameters

player_id
(String) The id of the player Roll20 object to check.

Returns

true if the player currently has GM permissions, or false otherwise..

[edit] Examples

This function is especially useful for limiting API commands to GM use.

on('chat:message', function(msg) {
    if (msg.type !== 'api') return;

    if (msg.content.indexOf('!playercommand') === 0) {
        // ...
    } else if (msg.content.indexOf('!gmcommand') === 0) {
        if (!playerIsGM(msg.playerid)) return;
        // ...
    }
});


[edit] randomInteger

Parameters

max
(Number) The maximum number to return, inclusive.

Returns

A random integer between 1 (inclusive) and max (inclusive). This function has better distribution than Math.random(), and is recommended over it. This function doesn't make use of the Quantum Roll feature used by the dice engine, but it does use the same pseudorandom algorithm that the dice engine will fall back on if Quantum Roll is unavailable.

[edit] Examples

Because this function returns an integer from 1 to max, it is ideal for quickly generating a dice roll outcome if you don't need the full strength of Roll20's dice engine.

var d20Result = randomInteger(20); // roughly equivalent to rolling a 20-sided die


[edit] sendChat [Asynchronous]

Parameters

speakingAs
(String) The name to attach to the message being sent. If speakingAs is in the format player|player_id or character|character_id, the message will be sent as that player or character. Otherwise, the message will use the given name as though a GM had used the /as command.
message
(String) The message to send to the chat.
callback
(Function, optional) If callback is specified, the result of the chat message will be passed to it instead of appearing in the chat. The parameter of the callback method is an array of message objects.
options
(Object, optional) If options.noarchive is true, the message will not be added to the chat archive. If options.use3d is true, dice rolls in the message will use the 3D dice feature. Options are not applicable if callback is specified.

Returns

(Void)

[edit] Examples

sendChat('Example', 'This is a simple example.');

You can easily write code to send a message as the same player or character that triggered a chat:message event.

on('chat:message', function(msg) {
    var character = findObjs({ type: 'character', name: msg.who })[0],
        player = getObj('player', msg.playerid),
        message = ' said something';

    if (character) sendChat('character|'+character.id, character.get('name')+message);
    else sendChat('player|'+player.id, player.get('displayname')+message);
});

The callback parameter is useful if you need to leverage Roll20's dice engine. There is no particular need for a speakingAs value when using the callback, since the message won't appear in the chat anyway.

sendChat('', '/r 2d20k1+'+strengthMod, function(ops) {
    var msg = ops[0];
    // ...
});

options.noarchive is primarily designed for sending players menus made from API Command buttons without clogging their chat history.

sendChat('System', '[Clear changes](!clear)\n[Add tile](!add)\n[View sample](!view)\n[Save layout](!save)', null, { noarchive: true });



[edit] sendPing

Parameters

left
(Number) The x-coordinate to place the ping at.
top
(Number) The y-coordinate to place the ping at.
page_id
(String) The id of the page Roll20 object to place the ping on.
player_id
(String, optional) The ping will use the specified player's color. If player_id is omitted, the ping will be yellow.
moveAll
(Boolean, optional) If moveAll is true, all of the players on the appropriate page will have their views centered on the ping. If no value is provided for moveAll, it defaults to false; when it is false, no players are moved, but the ping is visible to everyone.
visibleTo
(String, Array, Variable, optional) Specifies one or more players that will receive the ping. If at least one player is specified, no other players will see the ping or be moved.

Note: If sending to a single player, you can include their player ID as a string or variable.

If sending multiple IDs, they can be included either as an array, or as a comma-delimited text string.

The player ID can be obtained using the findObjs() function and you can then use playerIsGM(playerID) to determine if an individual player ID is a GM. In this way, you should be able to find and pass in the player IDs of GMs into the sendPing function.

Returns

(Void)


[edit] Examples

on('chat:message', function(msg) {
    var obj;
    if (msg.type === 'api' && msg.content.indexOf('!ping') === 0) {
        if (!msg.selected) return;
        obj = getObj(msg.selected[0]._type, msg.selected[0]._id);
        sendPing(obj.get('left'), obj.get('top'), obj.get('pageid'), msg.playerid, true); // center everyone on the selected token
    }
});
const getGMPlayers = (pageid) => findObjs({type:'player'})
    .filter((p)=>playerIsGM(p.id))
    .filter((p)=>undefined === pageid || p.get('lastpage') === pageid)
    .map(p=>p.id)
    ;

const sendGMPing = (left, top, pageid, playerid=null, moveAll=false) => {
    let players = getGMPlayers(pageid);
    if(players.length){
        sendPing(left,top,pageid,playerid,moveAll,players);
    }
};

[edit] Cards

These functions were structured so that playing a card mimics how you would do that in real life. You first must pick up a card, by taking a card from the deck, table or from another player (drawCard, pickUpCard, and takeCardFromPlayer, respectively). With the card now in hand, you can now either play it to the table (playCardToTable) or give it to a player (giveCardToPlayer).

Using any of the 'take' functions will remove the card from play and return the id for that card, and also add the card to the discard pile. This is to prevent unpredictable behavior that may result from having a card completely unaccounted for. However, if you immediately use a 'play' function using the returned card id, the card will be put back in play before the discard pile is updated, so that the players will not see the card get added to the discard pile. If you wish to hold on to a card before playing it and you do not wish for it to end up in the discard pile, consider playing the card to the table on the GM layer, or perhaps to a page that the players aren't currently on.

Playing a card without first using a 'take' function could lead to duplicates that may not behave as you expect. Depending on deck settings and where the duplicates are in play, the game may (or may not) remove one of the duplicates automatically. Regardless, when cards are recalled and the deck is shuffled, the game will ensure there are no duplicate cards in the deck.

It's worth noting that the 'take' functions are also the best way to discard a card. You can simply call 'destroy' on a card played to the table, or manually remove a cardid from a player's currentHand, and these cards will eventually end up in the discard pile. However, it would be difficult to predict when the discard pile will be updated, and if multiple cards are removed this way, they may not wind up in the discard pile in the correct order for this reason. Using one of the 'take' functions will automatically update the discard pile each time one is called, ensuring that cards are discarded in the order they are removed.

[edit] cardInfo

cardInfo( { options } )

Returns information about a group of cards, or one specific card. This function accepts the following options:

{
   type: "hand", "graphic", "discard", "play", "deck", "all", "card" //Required. Determines what kind of results are returned.
   deckid: deckid //Required for all types except 'card'. Determines which deck to return information about.
   cardid: cardid //Required for type 'card'. Determines which card to return information about.
   discard: true/false //Optional. Determines whether result will include cards in the discard pile. Ignored for types 'card', 'all', and 'discard'. Defaults to 'false' if omitted.
}

As noted above, the type will determine what results are returned. "card" returns a single object containing information about the card corresponding to cardid, with the following format:

{ 
   type: "graphic", "hand", "deck", or "discard",
   id: The id of the graphic, hand, or deck containing the card. Omitted for type "discard",
   cardid: The id of the card,
   pageid: The id of the page containing the graphic. Omitted for other types,
   playerid: The id of the player holding the card. Omitted for other types,
   index: The position of the card in the hand or discard pile. Omitted for types "graphic" and "deck"
}

The other types return an array of these objects. "hand" will return info on all cards in that deck that are currently in player's hands. "graphic" returns info on the cards of that deck currently on the table. "discard" returns only the cards that are in the discard pile, and "deck" returns the cards that are still in the deck. "play" returns a combination of "hand" and "graphic", and "all" returns all cards belonging to that deck. You can also include the setting discard: true to include the cards in the discard pile in the results. This has no effect on the types "discard" and "all".

If the function fails, it will return false. If no information is retrieved, it will return an empty array.


[edit] recallCards

recallCards(deckid, type(optional) )

Functions identically to using the 'recall' dialog on a deck. The type parameter is a string that determines which which cards are recalled, the valid types are hand, graphic, and all. If omitted, the type defaults to 'all'. Will return false if the function fails, returns true if successful.

[edit] shuffleDeck

shuffleDeck(deckid, discard(optional), deckOrder(optional) )

Shuffles a deck. If this is called with only the deckid passed in, it is identical to clicking the 'Shuffle' button, except any errors encounter will log to the api console instead of producing a browser alert.

The second parameter allows you to specify whether or not to shuffle the discard pile back into the deck. The default is true, which shuffles the discard pile back into the deck as it would normally when clicking the shuffle button. Passing in 'false' will leave the discard pile as it is and only shuffle the remaining cards in the deck.

If you call this function with an array of card ids as the second parameter, the deck will be re-shuffled and put in the order of that array. Note that the cards in this array must match the cards left in the deck exactly (plus the discard pile, if you specify discard = true), or it will fail with an error.

You can use the provided cardInfo function, in combination with the _.pluck function from the underscore.js library to easily get the list of cards the function expects, like so: _.pluck(cardInfo({type: "deck", deckid: deck.id, discard: (true/false, depending) }), "cardid").

Will return false if the function fails, returns an array of card ids representing the new deck order if successful.

[edit] drawCard

drawCard(deckid, cardid(optional) )

Draws a card from a deck. You can pass in a card id to draw a specific card from the deck. If this is omitted, it will draw the top card.The function returns the id of the drawn card if successful, and false if it fails.

[edit] pickUpCard

pickUpCard(cardid, fromDiscard(optional) )

Picks up a card from the table (if fromDiscard is false or omitted), or from the discard pile (if fromDiscard is true). Note that it isn't necessary to use this function to play a card from the discard pile, as using giveCardToPlayer or playCardToTable will automatically remove the card from the discard pile if it is there. However, this function may be useful as it will return false if the card is not in the discard pile. The function returns the id of the card if successful, and false if it fails.

[edit] takeCardFromPlayer

takeCardFromPlayer(playerid, options(optional) )

Takes a card from the player with id playerid. If options are omitted, it will take a random card from that player's hand. You can add properties to the options to specify a card to take, "index" to specify an index of the currentHand array, or "cardid" to specify a card by id. By default, the function will remove the card from the players hand and return the id for that card. However, you can add the property "steal" to the options parameter, and give it a player's id to trigger the steal card dialog for that player. This functions identically to clicking on 'Steal Card' in another player's hand. Note that although this still returns the card id, the card will remain in a player's hand and should not be played elsewhere without being removed from the hand.

Returns the id of the card if successful, and false if it fails. Note that if the 'steal' option is used, the function will return a card id, but this does not necessarily mean that the card changed hands, as that will be up to the player to approve or deny the steal request.

[edit] giveCardToPlayer

giveCardToPlayer(cardid, playerid)

Gives a card (with id cardid) to a player (with id playerid).

[edit] playCardToTable

playCardToTable(cardid, settings(optional) )

Plays a card (with id cardid) to the table. The settings parameter can be used to customize the resulting token, if omitted default settings will be used. Here are the possible settings with their defaults:

{
   left: X position in pixels. Defaults to the center of the page.
   top: Y position in pixels. Defaults to the center of the page.
   width: width of token in pixels. Defaults to the deck's defaultwidth, or to 98 if the deck has no default.
   height: height of token in pixels. Defaults to the deck's defaultheight, or to 140 if the deck has no default.
   layer: the layer the token will appear on. Defaults to the objects layer.
   pageid: the page the token is played to. Defaults to the current player page.
   isdrawing: whether to treat the token as a drawing. Uses the deck "treatasdrawing" as the default.
   currentSide: whether the card is played face up or face down, with 0 being face up and 1 being face down. Defaults to the deck's default setting.
}

[edit] dealCardsToTurn

dealCardsToTurn(deckid)

Deals a card from the deck to each object in the turn order. Functions identically to clicking the 'Deal cards to turn order items' in the 'Deal cards' dialog box. Note that in this case, any errors encountered (for example, if you run out of cards before you finish dealing) will produce a browser alert in the same way as if the user clicked the button themselves.


[edit] Character

[edit] onSheetWorkerCompleted

Parameters

callback
(Function) The function that will be called when the current 'stack' of Sheet Worker Scripts completes.

Returns

(Void)

[edit] Examples

This function is intended to be called prior to setWithWorker. The callback function will be called only once.

var myCharacter = ...,
    mySourceAttr = findObjs({ type: 'attribute', characterid: myCharacter.id, name: 'mySourceAttribute' })[0];

onSheetWorkerCompleted(function() {
    var calculatedAttr = findObjs({ type: 'attribute', characterid: myCharacter.id, name: 'myCalculatedAttribute' })[0];
    // do something with calculatedAttr.get('current');
});

mySourceAttr.setWithWorker({ current: 5 });

[edit] setAttrs

setAttrs(character_id, attribute_obj, settings(optional))

This function works like the setAttrs sheet worker function, except that the first argument must be the id of the character whose attributes you are changing. The second argument must be an object containing the attributes and values you wish to change, in the format attribute_name: value. This function can be used with the defaults variable to easily create characters with the game's default settings by simply passing in defaults.sheet as the second parameter. By default, this function will trigger sheet workers, this can be disabled by passing in "{silent: true}" as a third parameter.

[edit] Graphic

[edit] toBack

Parameters

obj
(Roll20 object) The Roll20 object to send to the back of its layer.

Returns

(Void)

[edit] Examples

on('chat:message', function(msg) {
    if (msg.type === 'api' && msg.content === '!toback' && msg.selected) {
        _.each(msg.selected, (s) => {
            toBack(getObj(s._type, s._id));
        });
    }
});

[edit] toFront

Parameters

obj
(Roll20 object) The Roll20 object to bring to the front of its layer.

Returns

(Void)

[edit] Examples

on('ready', function() {
    on('add:graphic', function(obj) {
        toFront(obj);
    });
});

[edit] Fx

[edit] spawnFx

Parameters

left
(Number) The x-coordinate to place the particle emitter.
top
(Number) The y-coordinate to place the particle emitter.
type
(String) The type of particle emitter to place. For built-in effects, this should be "type-color", where type is one of bomb, bubbling, burn, burst, explode, glow, missile, or nova and color is one of acid, blood, charm, death, fire, frost, holy, magic, slime, smoke, or water. For custom effects, this should be the id of the FX Roll20 object.
Note: beam, breath, and splatter types cannot be used with spawnFx. See spawnFxBetweenPoints instead.
page_id
(String, optional) The id of the page Roll20 object to place the particle emitter on. If omitted, Campaign().get('playerpageid') will be used instead.

Returns

(Void)

[edit] Examples

spawnFx(1400, 1400, 'bubbling-acid');

[edit] spawnFxBetweenPoints

Parameters

start
(Object) The starting point for the particle emitter. The point should be in the format { x: number, y: number }.
end
(Object) The ending point for the particle emitter. The point should be in the format { x: number, y: number }.
type
(String) The type of particle emitter to place. For built-in effects, this should be "type-color", where type is one of beam, bomb, breath, bubbling, burn, burst, explode, glow, missile, nova, or splatter and color is one of acid, blood, charm, death, fire, frost, holy, magic, slime, smoke, or water. For custom effects, this should be the id of the FX Roll20 object.
page_id
(String, optional) The id of the page Roll20 object to place the particle emitter on. If omitted, Campaign().get('playerpageid') will be used instead.

Returns

(Void)

[edit] Examples

spawnFxBetweenPoints({ x: 1400, y: 1400 }, { x: 2100, y: 2100 }, 'beam-acid');

[edit] spawnFxWithDefinition

Parameters

left
(Number) The x-coordinate to place the particle emitter.
top
(Number) The y-coordinate to place the particle emitter.
definition
(Object) The characteristics of the particle emitter to place. See Custom FX for a list of possible properties and the properties of the default particle emitter types and colors. See FX Library for some custom effects Roll20 users have come up with.
page_id
(String, optional) The id of the page Roll20 object to place the particle emitter on. If omitted, Campaign().get('playerpageid') will be used instead.

Returns

(Void)

[edit] Examples

// these two are equivalent
spawnFx(1400, 1400, 'bubbling-acid');
spawnFxWithDefinition(1400, 1400, {
    maxParticles: 200,
    size: 15,
    sizeRandom: 3,
    lifeSpan: 20,
    lifeSpanRandom: 5,
    speed: 7,
    speedRandom: 2,
    gravity: { x: 0.01, y: 0.65 },
    angle: 270,
    angleRandom: 35,
    emissionRate: 1,
    startColour:       [0, 35, 10, 1],
    startColourRandom: [0, 10, 10, 0.25],
    endColour:         [0, 75, 30, 0],
    endColourRandom:   [0, 20, 20, 0]
});

[edit] Jukebox

[edit] playJukeboxPlaylist

Note: Using u Jukebox/soundcloud(is SC removed?) functions will not throw errors, but they no longer do anything. "In Regards to SoundCloud"

Parameters

playlist_id
(String) The id of the playlist to start playing.

Returns

(Void)

[edit] Examples

var playlists = JSON.parse(Campaign().get('jukeboxfolder')),
    myPlaylist = _.find(playlists, (folder) => _.isObject(folder) && folder.n === myPlaylistName);
playJukeboxPlaylist(myPlaylist.id);


[edit] stopJukeboxPlaylist

Parameters

No parameters

Returns

(Void)

[edit] Examples

stopJukeboxPlaylist();