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 "API:Development"

From Roll20 Wiki

Jump to: navigation, search
m (script.json info)
(move API Dev section from other page)
Line 5: Line 5:
  
 
=API Script Creation - Introduction=
 
=API Script Creation - Introduction=
The '''Roll20 API''' provides a powerful way to customize and enhance your game. You write scripts (little pieces of code) that tell Roll20 what to do during gameplay (for instance, move a piece, add a status marker to a token, or even roll dice). It's simple and straightforward to get started, but the possibilities are endless.
+
The '''Roll20 API''' provides a powerful way to customize and enhance your game. You write scripts (little pieces of code) that tell Roll20 what to do during gameplay (for instance, move a piece, add a status marker to a [[token]], roll a [[dice]], create [[handout]], edit [[Character#Attributes|character stats]], [[Jukebox|play music]], and much more). It's simple and straightforward to get started, but the possibilities are endless.
 
+
  
 
==What do I need to get started?==
 
==What do I need to get started?==
  
Scripts for the Roll20 API are written in '''JavaScript'''. You only need a basic understanding of the language to get started, but if you want to learn more about JavaScript, this [http://www.codecademy.com/tracks/javascript Codecademy] course can help teach you.
+
Scripts for the Roll20 API are written in '''[[JavaScript]]'''. You only need a basic understanding of the language to get started, but if you want to learn more about JavaScript, this [http://www.codecademy.com/tracks/javascript Codecademy] course can help teach you.
  
  
* '''{{fpl|10419353/ Aaron's tips on getting started}}''' - (Sept. 2021)
+
* '''{{fpl|10419353/ Aaron's tips on getting started - API Development}}''' - (Sept. 2021)
  
 
==How does it work?==
 
==How does it work?==
Line 19: Line 18:
 
You write scripts that listen to events that happen during the game. Scripts can check to make sure that rules are followed, change properties on objects and tokens, and even provide custom chat commands. The scripts you write run across the entire game, and affect things the GM does as well as all the players. Advanced scripts can also run independently, performing automatic actions such as moving a token on a patrol route or nudging players when their turn is taking too long.
 
You write scripts that listen to events that happen during the game. Scripts can check to make sure that rules are followed, change properties on objects and tokens, and even provide custom chat commands. The scripts you write run across the entire game, and affect things the GM does as well as all the players. Advanced scripts can also run independently, performing automatic actions such as moving a token on a patrol route or nudging players when their turn is taking too long.
  
'''To get started, your first stop should be the [[API:Use Guide|Use Guide]].'''
+
See '''[[API:Use Guide|Use Guide]]''' for installing & using existing APIs.
 
+
 
+
 
==Where can I find pre-made scripts?==
 
==Where can I find pre-made scripts?==
  
Line 29: Line 26:
 
* '''The [[API:Script_Index|Wiki's API Script Index]].'''  This is a good source of information about popular scripts, but it's not too well maintained nor does it describe all APIs that currently are available in the one-click menu..  However, if you'd like to document some scripts you find useful, their authors would certainly appreciate it!
 
* '''The [[API:Script_Index|Wiki's API Script Index]].'''  This is a good source of information about popular scripts, but it's not too well maintained nor does it describe all APIs that currently are available in the one-click menu..  However, if you'd like to document some scripts you find useful, their authors would certainly appreciate it!
 
** [[API:Short Community Scripts]] contains some APIs that aren't in the install menu
 
** [[API:Short Community Scripts]] contains some APIs that aren't in the install menu
 +
 +
==Types of scripts==
 +
{{NavMacroDocs}}
 +
Examples of creating APIs.  See [[API:Index]] for list of APIs to install.
 +
===Reactive Scripts: Listen to Events, Modify Objects===
 +
The first (and most simple type) of API usage is to react to changes on the tabletop, and then respond by making additional changes to the changed objects. This type of script is composed of a number of functions which listen to events that happen during the game. Then it will modify objects that are passed during those events, which will change what happens on the tabletop.
 +
 +
The most basic script which would simply move any piece which moved an additional 5 feet (assuming default page settings) would be:
 +
 +
<pre data-language="javascript">
 +
on("change:graphic", function(obj) {
 +
  obj.set({
 +
    left: obj.get("left") + 70   
 +
  });
 +
});
 +
</pre>
 +
 +
As you can see, we created a simple function using on which will be executed anytime the <code>change:graphic</code> event is heard. The function is passed the graphic object <code>obj</code>. To make a change, we just modify <code>obj</code> using the <code>set</code> function -- whatever properties we change will be detected and changed on the tabletop.
 +
 +
'''Important Note:''' You must use <code>set</code> and <code>get</code> to set and get current values on objects or your changes will not be saved. (See below for a listing of object types and their properties, as well as a listing of all events and what arguments each event is passed.)
 +
 +
====A Note on Utility Functions====
 +
Of course, the previous example isn't incredibly helpful because it always adds 70 pixels to the location of the [[token]]. But what if the user has changed their scale so that 5ft is 140 pixels? The Roll20 API provides several handy utility functions to help with this (and other) common scenarios. Let's modify our previous example to use the <code>distanceToPixelsfunction</code>, which will tell us how many pixels "five feet" (or inches, or meters, or whatever other distance type has been set) on the tabletop is.
 +
 +
<pre data-language="javascript">
 +
on("change:graphic", function(obj) {   
 +
  obj.set({       
 +
    left: obj.get("left") + distanceToPixels(5)   
 +
  });
 +
})
 +
</pre>
 +
 +
Now if the current page is setup to use the default grid sizing, <code>distanceToPixels(5);</code> will still return 70 pixels, but if the page is setup to have a scale twice the size of normal, it would return 140.
 +
 +
It's always a good idea to use utility functions whenever they're available to help keep your script from breaking if the settings of a page or a token change.
 +
 +
===Proactive Scripts: Do Things Without User Intervention===
 +
In addition to reacting to user events, you can also do things with the API automatically that aren't tied to a specific event from the [[players]]. For example, let's have a [[token]] that patrols back and forth on the map.
 +
 +
''Note'': Although this type of script is not dependent on user interaction, the API scripts for your game will still only run when at least one person is connected to your game.
 +
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">
 +
on("ready", function() {
 +
  //Wait until the ready event fires so we know the game is completely loaded.
 +
  //Get a reference to our patrolling token.
 +
  var patroltoken = findObjs({_type: "graphic", name: "Guard A"})[0]; //We know there is a token in the Game called "Guard A".
 +
  var direction = -1*distanceToPixels(5); //Walk left 70 pixels.
 +
  var stepstaken = 0; //How many steps have we walked in the current direction?
 +
  setInterval(function() {
 +
    if(stepstaken > 3) {
 +
      //Switch directions!
 +
      direction = direction * -1; //will "flip" the direction we're walking
 +
      stepstaken = 0; //reset steps back to 0.
 +
    }
 +
    patroltoken.set("left", patroltoken.get("left") + direction); //walk!
 +
    stepstaken++;
 +
  }, 5000); //take an action every 5 seconds
 +
});
 +
</pre>
 +
 +
===A Treatise on Asynchronous Functions===
 +
 +
An asynchronous function is one that returns the thread of control to the calling scope immediately and performs some duty in the background.  Here's a very simple and easy to understand example which you can paste in an API scripts tab:
 +
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">
 +
on('ready',function(){
 +
  log('Parent Scope - Before call to asynchronous function.');
 +
 +
  setTimeout(function(){
 +
    log('Asynchronous Function Scope - Doing the Asynchronous function work.');
 +
  },10 /* 10 milliseconds */);
 +
 +
  log('Parent Scope - after call to asynchronous function.');
 +
});
 +
</pre>
 +
 +
In the API log, you'll see something like this:
 +
<pre style="background-color:#333; color: #E6DB74;">
 +
"Parent Scope - Before call to asynchronous function."
 +
"Parent Scope - after call to asynchronous function."
 +
"Asynchronous Function Scope - Doing the Asynchronous function work."
 +
</pre>
 +
 +
Looking at that code, you think "Of course it will happen later, you told it to run in 10 milliseconds, duh?".  Here is a less obvious example that will have the same log messages:
 +
 +
<pre style="overflow:auto;white-space:pre-wrap;" data-language="javascript">
 +
on('ready',function(){
 +
  log('Parent Scope - Before call to asynchronous function.');
 +
 +
  sendChat('Async Function','Evaluate this: [[1d6]]',function(msg){
 +
    log('Asynchronous Function Scope - Doing the Asynchronous function work.');
 +
  });
 +
 +
  log('Parent Scope - after call to asynchronous function.');
 +
});
 +
</pre>
 +
 +
Asynchronous functions are necessary to prevent the API from hanging all the time.  If every dice roll was handled synchronously, the API would be super sluggish and unresponsive. Almost any function you see that takes a callback is asynchronous. (Exception for some of the <code>_.map</code>, <code>_.reduce</code>, etc functions, these are examples of functional programming in contrast to the procedural programming most people are used to.)
 +
  
 
==Contributing API Scripts to the Community==
 
==Contributing API Scripts to the Community==
Line 71: Line 167:
  
 
==API Meta Libraries==
 
==API Meta Libraries==
* Check the [[API:Script_Index#Library.2FMeta_Scripts|Library & Meta Scripts]] section of the API Index, there exists several APIs that can are made to be used by other APIs
+
* Check the [[API:Script_Index#Library.2FMeta_Scripts|Library & Meta Scripts]] APIs made to interact or support other APIs, which can be relied on  instead of writing everything yourself.
 
* [https://github.com/onyxring/Roll20OralOrcs Roll20 Oral Orcs] framework to simplify API writing for Roll20
 
* [https://github.com/onyxring/Roll20OralOrcs Roll20 Oral Orcs] framework to simplify API writing for Roll20
  
 
=Related Pages=
 
=Related Pages=
* '''[[Complete Guide to Macros & Rolls‎]]'''
+
* '''{{macro guide}}'''
 
** {{Text Chat}} - where the roll results appear, & info on the common chat commands
 
** {{Text Chat}} - where the roll results appear, & info on the common chat commands
 
** [[Dice Reference]] - Comprehensive list of how the Roll20 dice-rolling syntax works, and list the features available
 
** [[Dice Reference]] - Comprehensive list of how the Roll20 dice-rolling syntax works, and list the features available
Line 82: Line 178:
 
** [[Roll Templates]] - a method of formatting roll results in the chat, with some extra functions
 
** [[Roll Templates]] - a method of formatting roll results in the chat, with some extra functions
 
** [[API]]''(Pro Only)'' - API commands can be used in the <span style="font-family:Pictos;">q</span>Text Chat
 
** [[API]]''(Pro Only)'' - API commands can be used in the <span style="font-family:Pictos;">q</span>Text Chat
<br>
+
 
<br>
+
 
 +
[[Category:API Development]]
 
[[Category:API|Introduction]] [[Category:Docs]]
 
[[Category:API|Introduction]] [[Category:Docs]]

Revision as of 13:36, 13 January 2022

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

Go to the API:Use Guide-page for how to use/install existing APIs. This is an introduction to creating & modifying API Scripts.

Contents

API Script Creation - Introduction

The Roll20 API provides a powerful way to customize and enhance your game. You write scripts (little pieces of code) that tell Roll20 what to do during gameplay (for instance, move a piece, add a status marker to a token, roll a dice, create handout, edit character stats, play music, and much more). It's simple and straightforward to get started, but the possibilities are endless.

What do I need to get started?

Scripts for the Roll20 API are written in JavaScript. You only need a basic understanding of the language to get started, but if you want to learn more about JavaScript, this Codecademy course can help teach you.


How does it work?

You write scripts that listen to events that happen during the game. Scripts can check to make sure that rules are followed, change properties on objects and tokens, and even provide custom chat commands. The scripts you write run across the entire game, and affect things the GM does as well as all the players. Advanced scripts can also run independently, performing automatic actions such as moving a token on a patrol route or nudging players when their turn is taking too long.

See Use Guide for installing & using existing APIs.

Where can I find pre-made scripts?

The API Script community is fairly active with members creating and discussing scripts all the time. There are 3 basic places to look for new scripts:

  • The Official Roll20 API Script Repo on Github. This is where you'll find the current version of scripts that authors have submitted for inclusion in the repo.
  • The Roll20 API Scripts(Forum) This subforum is where scripts tend to show up first and where discussion happens about scripts that are being written or need changes. This is also where you can post and ask for help from the community in creating a script you've thought of, or finding a script to fill a need.
  • The Wiki's API Script Index. This is a good source of information about popular scripts, but it's not too well maintained nor does it describe all APIs that currently are available in the one-click menu.. However, if you'd like to document some scripts you find useful, their authors would certainly appreciate it!

Types of scripts

Examples of creating APIs. See API:Index for list of APIs to install.

Reactive Scripts: Listen to Events, Modify Objects

The first (and most simple type) of API usage is to react to changes on the tabletop, and then respond by making additional changes to the changed objects. This type of script is composed of a number of functions which listen to events that happen during the game. Then it will modify objects that are passed during those events, which will change what happens on the tabletop.

The most basic script which would simply move any piece which moved an additional 5 feet (assuming default page settings) would be:

on("change:graphic", function(obj) {
  obj.set({
    left: obj.get("left") + 70    
  });
});

As you can see, we created a simple function using on which will be executed anytime the change:graphic event is heard. The function is passed the graphic object obj. To make a change, we just modify obj using the set function -- whatever properties we change will be detected and changed on the tabletop.

Important Note: You must use set and get to set and get current values on objects or your changes will not be saved. (See below for a listing of object types and their properties, as well as a listing of all events and what arguments each event is passed.)

A Note on Utility Functions

Of course, the previous example isn't incredibly helpful because it always adds 70 pixels to the location of the token. But what if the user has changed their scale so that 5ft is 140 pixels? The Roll20 API provides several handy utility functions to help with this (and other) common scenarios. Let's modify our previous example to use the distanceToPixelsfunction, which will tell us how many pixels "five feet" (or inches, or meters, or whatever other distance type has been set) on the tabletop is.

on("change:graphic", function(obj) {    
  obj.set({        
    left: obj.get("left") + distanceToPixels(5)    
  });
})

Now if the current page is setup to use the default grid sizing, distanceToPixels(5); will still return 70 pixels, but if the page is setup to have a scale twice the size of normal, it would return 140.

It's always a good idea to use utility functions whenever they're available to help keep your script from breaking if the settings of a page or a token change.

Proactive Scripts: Do Things Without User Intervention

In addition to reacting to user events, you can also do things with the API automatically that aren't tied to a specific event from the players. For example, let's have a token that patrols back and forth on the map.

Note: Although this type of script is not dependent on user interaction, the API scripts for your game will still only run when at least one person is connected to your game.

on("ready", function() {
   //Wait until the ready event fires so we know the game is completely loaded.
   //Get a reference to our patrolling token.
   var patroltoken = findObjs({_type: "graphic", name: "Guard A"})[0]; //We know there is a token in the Game called "Guard A".
   var direction = -1*distanceToPixels(5); //Walk left 70 pixels.
   var stepstaken = 0; //How many steps have we walked in the current direction?
   setInterval(function() {
     if(stepstaken > 3) {
       //Switch directions!
       direction = direction * -1; //will "flip" the direction we're walking
       stepstaken = 0; //reset steps back to 0.
     }
     patroltoken.set("left", patroltoken.get("left") + direction); //walk!
     stepstaken++;
   }, 5000); //take an action every 5 seconds
});

A Treatise on Asynchronous Functions

An asynchronous function is one that returns the thread of control to the calling scope immediately and performs some duty in the background. Here's a very simple and easy to understand example which you can paste in an API scripts tab:

on('ready',function(){
  log('Parent Scope - Before call to asynchronous function.');

  setTimeout(function(){
    log('Asynchronous Function Scope - Doing the Asynchronous function work.');
  },10 /* 10 milliseconds */);

  log('Parent Scope - after call to asynchronous function.');
});

In the API log, you'll see something like this:

"Parent Scope - Before call to asynchronous function."
"Parent Scope - after call to asynchronous function."
"Asynchronous Function Scope - Doing the Asynchronous function work."

Looking at that code, you think "Of course it will happen later, you told it to run in 10 milliseconds, duh?". Here is a less obvious example that will have the same log messages:

on('ready',function(){
  log('Parent Scope - Before call to asynchronous function.');

  sendChat('Async Function','Evaluate this: [[1d6]]',function(msg){
    log('Asynchronous Function Scope - Doing the Asynchronous function work.');
  });

  log('Parent Scope - after call to asynchronous function.');
});

Asynchronous functions are necessary to prevent the API from hanging all the time. If every dice roll was handled synchronously, the API would be super sluggish and unresponsive. Almost any function you see that takes a callback is asynchronous. (Exception for some of the _.map, _.reduce, etc functions, these are examples of functional programming in contrast to the procedural programming most people are used to.)


Contributing API Scripts to the Community

If you create a script that you'd like to offer to the rest of the Roll20 community, you can submit it to be included in the Official Roll20 API Script Repo. Having your script approved by the Roll20 staff and included in the repository will unlock the
API Scripter
forum tag for your account as will allow you to advertise via Patreon or Patreon-like sites (see below for more info).

To find out what you need to do to correctly submit your script to the repository, check:

Guides for how to submit content to Github:

script.json

Details: Creating a script.json File

Some extra details:

  • "roll20userid" - how to find your roll20userid
  • "description" - text is displayed as markdown, with a few quirks.


Patreon and Tipeee Link

For API script authors that are contributing to the Roll20 Roll20 API repo, they are approved to advertise via subscription/donation service sites: Patreon and Tippee. Roll20 is not responsible for any payment transactions and cannot enforce any private arrangements.

In order to qualify, an API script author must first have their script contribution approved by the Roll20 staff and included into the Roll20 API Script Repo.

You will want to include your Patreon or Tipeee account information in the script.json file that should be included with your script submission on GitHub.

The json file should have one of these fields added to it if you wish to advertise with Patreon or Tipeee:

patreon: Place the URL for a Patreon campaign here, and it will appear under your script's description when selected. (e.g."https://www.patreon.com/<name>")
tipeee: Place the URL for a Tipeee here, and it will appear under your script's description when selected. (e.g. "https://www.tipeee.com/<name>")

For more information, see github.com/Roll20/roll20-api-scripts#contributing

Linking to Patreon/Tipeee on the Roll20 Forums

Linking to Patreon or Tipeee on the Roll20 Forums are only permitted for pre-approved community members who have contributing either Character Sheets or API Scripts. If you wish to solicit users directly for funding you may do so privately, but no such links are permitted in a public forum without any contributed material.


API Meta Libraries

  • Check the Library & Meta Scripts APIs made to interact or support other APIs, which can be relied on instead of writing everything yourself.
  • Roll20 Oral Orcs framework to simplify API writing for Roll20

Related Pages

  • Complete Guide to Macros & Rolls
    • q Text Chat - where the roll results appear, & info on the common chat commands
    • Dice Reference - Comprehensive list of how the Roll20 dice-rolling syntax works, and list the features available
    • Macros - How to create macros, and other info on how the Roll20 qText Chat works, like referencing stats on character sheets, roll queries, nesting macros & initiative
    • Roll Templates - a method of formatting roll results in the chat, with some extra functions
    • API(Pro Only) - API commands can be used in the qText Chat