Skip to content

Inside a script, bot gives you the trigger arguments and pipeline variables, while nnz provides helpers and calls into the bot. Use the local helpers for calculations and text; use nnz.api when you need to read channel data or cause an effect such as sending a chat message. The order of a run and its limits are explained in How a script runs.

A grant authorizes one kind of call from that saved script version. The bot derives grants from your code, so you do not maintain a separate list by hand. Grants are different from the team roles on the Permissions page: a role governs who can manage a script, while a script grant governs which calls its code can make.

Turn on Custom Code

Custom Code is off for a new channel. While it is off, every grant is refused, and a script that makes a bot call does not run. You also cannot open, write, save or test scripts. The bot answers: “Custom code is not enabled for this channel. Enable it on the Features page.”

  1. Open the Features settings page.
  2. Find Custom Code in the Automation area.
  3. Switch it on. The switch takes effect right away.

The bot name

The bot object holds the inputs and outputs of the current run. How a script runs explains what each part hands back to the pipeline.

MemberType
bot.argsstring[]
bot.getVar(key)string | null
bot.setVar(key, value)nothing; the value is text
bot.send(message)nothing
bot.stopPipeline()nothing
bot.call(key, ...args)string | null

bot.call is the one door that every nnz.api call goes through. It takes a grant key and text arguments.

Prefer the named nnz.api calls when one exists: they convert arguments and results for you. For example, bot.send only collects step output, whereas nnz.api.chat.send actually asks the bot to post in chat.

A missing value in a bot member works as One rule for a bad value says.

console.log and console.info write a line to the test run panel. console.warn starts the line with “warn:”, and console.error starts it with “error:”. Viewers never see these lines.

Helpers that need no grant

These helpers run inside the script. They make no bot call and need no grant.

Units

nnz.units.convert(value, from, to) converts a value between units, for example convert(10, 'km', 'mi'). It knows length, weight, time and temperature. It gives NaN when the two units do not match.

Time

MemberWhat it gives
nnz.time.now()The time now, as ISO 8601 text.
nnz.time.parse(iso)The time in epoch milliseconds, or NaN when the text is not a date.
nnz.time.format(epochMs)The time as ISO 8601 text.
nnz.time.add(iso, ms)The time moved by ms; a negative number goes back.
nnz.time.diff(a, b)a minus b, in milliseconds.
nnz.time.sleep(ms)A pause before the next statement, at most 5 seconds. A missing value or one that is not a number stops the run.

The pause counts against the run’s time limit.

Math

MemberWhat it gives
nnz.math.clamp(value, min, max)The value held between min and max.
nnz.math.round(value, digits)The value rounded to digits decimal places. Default: 0.
nnz.math.lerp(a, b, t)The point between a and b at t.
nnz.math.sum(values)The total of the list.
nnz.math.avg(values)The average of the list, or 0 for an empty list.
nnz.math.min(values)The smallest value.
nnz.math.max(values)The largest value.
nnz.math.randomInt(min, max)A random whole number from min to max, both included. The ends can be in either order; NaN when no whole number lies between them.

Text

MemberWhat it gives
nnz.str.padStart(value, length, pad)The text padded at the start. Default pad: a space.
nnz.str.padEnd(value, length, pad)The text padded at the end. Default pad: a space.
nnz.str.trim(value)The text without spaces at both ends.
nnz.str.upper(value)The text in upper case.
nnz.str.lower(value)The text in lower case.
nnz.str.title(value)Each word starting in upper case.
nnz.str.truncate(value, length, ellipsis)The text cut to length characters, the ellipsis included. Default: ”…”.
nnz.str.slugify(value)A lower case slug with dashes: “Hello World” gives “hello-world”.
nnz.str.format(template, values)Each {name} filled from values; a name with no value stays as it is.

JSON

nnz.json.parse(text) gives null when the text is not valid JSON. nnz.json.stringify(value) gives the text “null” when the value cannot be written as JSON. Neither one throws.

Random

MemberWhat it gives
nnz.random.int(min, max)A random whole number from min to max, both included. The ends can be in either order; NaN when no whole number lies between them.
nnz.random.pick(items)A random item of the list. An empty list stops the whole run with an error.
nnz.random.shuffle(items)A shuffled copy; the list itself stays as it is.
nnz.random.uuid()A random version 4 UUID.

Last error

nnz.lastError holds the error of the last bot call that failed, or null. Reading it is not a bot call and needs no grant.

How a script gets its grants

A script never asks for a grant by hand. When you save the code, the bot reads which bot calls the code names, and keeps that list with the version.

  1. Each nnz.api call in the code adds its grant key.
  2. Each bot.call('key', ...) with a key in quotes adds that key. The scan only reads keys made of letters, digits and dots. An action key (actions.invoke: and a type) is not picked up from bot.call, so use nnz.api.actions.invoke('type', ...) for actions.
  3. nnz.template.render adds the grant template.render.
  4. Each nnz.api.actions.invoke('type', ...) adds the grant for that one action type.

When the script runs, the bot checks every key on the list. A key that does not exist stops the whole run before it starts.

Keep host calls in their named form, such as nnz.api.chat.send(...). The save-time scan recognizes these expressions and literal bot.call keys; it does not follow arbitrary aliases or computed property names. For example, nnz.api['chat']['send'](...) does not add a grant by itself, so the call is denied unless that saved version already declares chat.send elsewhere. Use nnz.api.actions.invoke('type', ...) for an action, with the action type written as a string literal.

When Custom Code is off, a list with at least one key also stops the whole run before it starts. A script with an empty list makes no bot call, so it still runs.

A call to a key that is not on the list stops the whole run with the result Denied.

nnz.api.actions.invoke needs its action type as text in quotes. A type built in code cannot be granted, and the save fails with “nnz.api.actions.invoke needs its action type as a string literal (for example ‘tts_synthesize’): a grant is per action type, so a computed type can never be granted.”

Grant keys

CallGrant key
nnz.api.chat.sendchat.send
nnz.api.chat.replychat.reply
nnz.api.user.getuser.get
nnz.api.user.lookupuser.lookup
nnz.api.economy.balanceeconomy.read
nnz.api.music.nowPlayingmusic.nowPlaying
nnz.api.music.queuemusic.queue
nnz.api.music.playNowactions.invoke:play_track_once
nnz.api.http.fetchhttp.fetch
nnz.api.storage.getstorage.get
nnz.api.storage.setstorage.set
nnz.api.storage.deletestorage.delete
nnz.api.storage.liststorage.list
nnz.api.tts.speaktts.speak
nnz.api.tts.speakSequencetts.speakSequence
nnz.api.tts.getVoicetts.voice.get
nnz.api.tts.setVoicetts.voice.set
nnz.api.tts.listVoicestts.voice.list
nnz.api.stats.viewerstats.viewer
nnz.api.stats.streamstats.stream
nnz.api.widget.emitwidget.emit
nnz.api.reward.getreward.get
nnz.api.reward.updatereward.update
nnz.api.schedule.pipelineschedule.pipeline
nnz.api.actions.invoke('type', ...)actions.invoke: and the type
nnz.template.rendertemplate.render

The calls themselves are on three pages:

Read why a bot call failed

A bot call that fails gives back its empty result, such as null, false or an empty list. The script goes on. nnz.lastError then says why, with a code and a message.

A call to a key that is not on the list is not a failed call, as How a script gets its grants says.

CodeMeaning
invalid_argumentThe bot cannot use a value, for example text that is empty or only spaces.
not_foundNo viewer, widget or reward matches the name, or Twitch has no user with that login.
refusedThe bot will not do it, for example the widget is turned off.
rate_limitedThe work behind the call reported too many requests.
limit_exceededThe call went over a limit, for example the lookups or the data allowed in one run, or the 200 script keys a channel can hold.
upstream_failedThe service behind the call did not answer with success.

Every bot call clears nnz.lastError first, so it only ever describes the last call.

Read or copy the error before making another call. A later successful call clears it, and a later failed call replaces it with its own reason.

One rule for a bad value

This rule covers every nnz.api call and every member of bot. The page of a call names it when the call is an exception.

These work as the sections above say, and the rule does not cover them:

  • the nnz helpers
  • a key that is not on the list
  • the Custom Code check
ValueResult
A required value that is left out or nullThe whole run stops. It is not a failed call. The error names the call and the value, such as “chat.send needs a message”.
An optional value that is left out or nullThe value is skipped. The call uses its normal behavior.
A value the bot cannot use, such as text that is empty or only spacesA failed call with the code invalid_argument. The script goes on.
A name that matches nothingA failed call with the code not_found. The script goes on.

A value of another type is turned into text first, so the number 5 becomes "5".

The members of bot follow the first row. bot.getVar, bot.setVar and bot.send never make a failed call, so the last two rows do not apply to them. A bot.call that the bot fails is a failed call, the same as an nnz.api call.

MemberA value that is left out or nullEmpty text
bot.getVar(key)Stops the run: “bot.getVar needs a key”.Used as it is.
bot.setVar(key, value)Stops the run: “bot.setVar needs a key” or “bot.setVar needs a value”.Used as it is.
bot.send(message)Stops the run: “bot.send needs a message”.Used as it is.
bot.call(key, ...args)Stops the run: “bot.call needs a key”, or “bot.call needs a value for argument 1” for the first argument.An empty argument goes to the call, which can fail it with invalid_argument.
bot.stopPipeline()Takes no value.Takes no value.
bot.argsA list, not a call.A list, not a call.

This script stores the first argument of the run, or “chat” when there is none, and posts the reason when the store refuses it:

JavaScript
const saved = nnz.api.storage.set('last.hug', bot.args[0] || 'chat');

if (!saved) {
nnz.api.chat.send('Not saved: ' + nnz.lastError.message);
}

When the store works, the script posts nothing. The store refuses a new key when the channel already holds 200 script keys. Chat then shows “Not saved: Storage is full: this channel already holds 200 script keys.” in the channel’s one bot voice.