Skip to content

Widget code runs in a browser source and responds to events from the bot. Script code runs in the bot’s sandbox when a command or pipeline calls it. They can use the same action types, but they use different SDK objects: NomNomz in a widget and nnz in a script.

Start with the widget methods and event payloads below when you are building an on-screen response. For a script, jump to Run a pipeline action, Send a widget an event, or Render a template. Script basics explains script grants and errors.

Before you start

Custom Code is off for a new channel. A script call on this page works only when Custom Code is on. Script basics shows how to switch it on.

You add and set up a widget on Widgets and alerts.

The widget SDK

The SDK is the NomNomz name in the widget page. It is loaded before the widget code runs. Each call that registers a handler gives back NomNomz, so calls chain.

MemberWhat it does
NomNomz.on(eventType, handler)Calls handler(data, eventType, meta) for each event of that name.
NomNomz.off(eventType, handler)Removes a handler. Pass the same function you gave to on.
NomNomz.onAny(handler)Calls handler(eventType, data, meta) for every event.
NomNomz.onSettings(handler)Calls handler(settings) at once, then again on every change in the dashboard.
NomNomz.settingsThe widget’s settings now.
NomNomz.widget.idThe id of this widget.
NomNomz.widget.nameThe name of this widget.
NomNomz.reportError(message)Logs the message and reports it to the bot as a widget error.
NomNomz.actions.invoke(actionType, params, variables)Runs one pipeline action.
NomNomz.actions.claim(key)Claims an event for this one copy of the widget.
NomNomz.data.nowPlaying()The track that plays now, or null.
NomNomz.data.queue()The music queue, without the track that plays now.
NomNomz.data.storage(key)One value from the channel’s script storage, or null.
NomNomz.data.streamStats(options)Metrics of one stream.
NomNomz.template.render(template, values)The template as text for this channel.
NomNomz.spotify.playbackToken()A short-lived Spotify token for the Spotify player.
NomNomz.reportYouTubePlayerState(videoId, state, positionMs)Tells the bot what a YouTube player page plays.
NomNomz.reportMediaSharePlayerState(requestId, state, positionSeconds, durationSeconds, volume)Tells the bot what the media-share player does.

The widget gets only the events it registered with on. onAny registers every event.

The action, data, template, Spotify-token and player-report methods return promises. Use await inside an asynchronous handler, and catch rejected promises so the widget can show a useful error. The event-registration methods and settings reads are synchronous.

Live events and replays

The meta value says where an event comes from.

FieldMeaning
replaytrue for a remembered event the bot sends again when the widget joins. false for a live event.
occurredAtThe time the replayed event really happened. Only set when replay is true.
testtrue for a test fire from the dashboard. Show it, but do not keep it as the widget’s value or count.

A handler that you register late still gets the remembered events it would have seen.

Claim an event

NomNomz.actions.claim(key) gives true only for the first open copy of the widget that claims the key. Every other copy gets false. A claim holds for ten minutes.

Claim an event, for example with its redemption id, before you act on it. Copies of the same widget share the claim; different widgets have separate claims. Check the resolved boolean before acting, and use a stable event identifier as the key. After the ten-minute window, the same key can be claimed again, so this is not permanent deduplication.

The claim fails with an error when the widget is not connected to the bot or not signed in, when the widget is not one of this channel’s widgets, or when the key is empty or over 200 characters. Catch that error.

Read the channel’s state

The NomNomz.data calls fail with an error when the request fails. streamStats takes stream and metrics. Leave out stream for the latest stream, live or ended.

NomNomz.spotify.playbackToken() never fails with an error. It gives { error: 'blocked' } when the bot may not play here, and { error: 'error' } when the request failed. Ask again each time the Spotify player wants a token.

Widget events

These are the names a widget passes to NomNomz.on. A field name that ends in ? can be absent. The SDK type reference gives the exact types, including nested objects and game-frame unions.

EventPayload fields
followuserId, displayName, login, followedAt?, avatarUrl?, pronouns?, communityStanding?, user
subscriptionuserId, displayName, tier, user
resubuserId, displayName, tier, months, streak, message?, user
giftgifterId?, gifterDisplayName, tier, count, anonymous, user, amount
cheeruserId?, displayName, bits, message, anonymous, imageUrl?, user, amount
raidfromUserId, fromDisplayName, fromLogin, viewerCount, user, viewers
raid_recap.showstream, channel?, duration?, peakViewers?, followers?, newFollowers?, subs?, gifters?, selfSubs?, bits?, raidsIn?, hypeTrain?, redemptions?, songRequesters?, chat?, topChatters?, commandsRun?
ban, timeout, unbanaction, moderatorId, targetUserId, reason?, durationSeconds?, targetDisplayName?, targetAvatarUrl?, targetPronouns?, targetCommunityStanding?, moderatorDisplayName?, timestamp, broadcasterId
ChatMessageid, channelId, userId, displayName, username, message, fragments, userType, isSubscriber, isVip, isModerator, isBroadcaster, isCheer, isCommand, badges, bitsAmount, color?, messageType, replyToMessageId?, replyParentMessageBody?, replyParentUserName?, timestamp, replyThreadParentMessageId?, avatarUrl?, pronouns?, provider, paint?, isArtist, overlayLine?, hints?, kind, noticeType?, systemText?, announcementColor?, sourceChannelId?, sourceChannelName?, subTier?, cumulativeMonths?, giftCount?, raidViewerCount?, recipientUserId?, recipientDisplayName?, heldStatus?, removed?, sourceBadges?, sourceChannelAvatarUrl?
ChatClearedclearedByUserId
MessageDeletedmessageId, deletedByUserId, targetUserId, deletedByDisplayName
UserMessagesClearedtargetUserId, targetUserDisplayName, targetUserLogin
ChatMessageEnrichedmessageId, linkUrl?, title?, description?, imageUrl?, provider?, userDisplayName?, userLogin?
hype_train_begin, hype_train_progresshypeTrainId, level, total, progress, goal, topContributions, expiresAt
hype_train_endhypeTrainId, level, total, topContributions, endedAt
poll_beginpollId, title, choices, durationSeconds, endsAt
poll_progresspollId, title, choices, endsAt
poll_endpollId, title, status, choices, winningChoiceId?
prediction_beginpredictionId, title, outcomes, windowSeconds, locksAt
prediction_progresspredictionId, title, outcomes, locksAt
prediction_lockpredictionId, title, outcomes
prediction_endpredictionId, title, status, outcomes, winningOutcomeId?
reward_redeemedbroadcasterId, rewardId, rewardTitle, redemptionId, userId, userDisplayName, cost, userInput?, timestamp, avatarUrl?, pronouns?, communityStanding?, eventId?
moderator_added, moderator_removed, vip_added, vip_removeduserId, userDisplayName, userLogin, avatarUrl?, pronouns?, communityStanding?
shoutout_senttoUserId, toDisplayName
shoutout_receivedfromBroadcasterId, fromBroadcasterDisplayName, fromBroadcasterLogin, viewerCount, avatarUrl?, pronouns?, communityStanding?
sr_queueitems
media_share_commandcommand, requestId?, sourceType?, mediaRef?, sourceUrl?, title?, durationSeconds?, positionSeconds?, volume?
now_playingisPlaying, track?, artist?, artUrl?, provider?, trackUri?, durationMs, progressMs, observedAt, requestedBy?, requestedByColor?
music.nowPlayingengine, itemId?, title, artists, albumArtUrl?, durationMs, progressMs, isPlaying, requestedBy?, volume, muted, state, blockedReason?
ad_schedulenextAdAt?, lastAdAt?, durationSeconds, prerollFreeTimeSeconds, snoozeCount, snoozeRefreshAt?, timeUntilNextAdSeconds?
ad_upcomingsecondsUntilAd, thresholdSeconds, durationSeconds, nextAdAt
youtube.playvideoId, trackUri, startSeconds?, endSeconds?. Start and end are the music section of the video, in seconds. Without them the video plays whole.
youtube.pause, youtube.resume, youtube.stopNo fields
youtube.seekpositionMs
youtube.volumepercent, fadeMs
track_saved_changedtrackUri, track?, artist?, isSaved
tts_speaktext, voice, user, durationMs, audioUrl?
stage_effectpreset, text?, durationMs, intensity?, color?
goalmetric, value, target
countmetric, value
supporter.tip, supporter.membership, supporter.merch, supporter.charitykind, supporterDisplayName, amountMinor?, currency?, tier?, quantity?, messageText?, isRecurring, user, amount?
voice_triggerword, count, stickerImageUrl?
game.lobby, game.runningOne of five game frames. Their fields: kind, lobbySeconds, maxMultiplier?, target?, radius?, successChance?, player, stake, entry?, phase?, crewSize, crew?, pot?, entrants?, multiplier, payout, landed, distance, hit, score, seed, spawnX. The drop frame gives a score from 0 to 100: 100 on the target center, 0 at the edge of the win radius or beyond.
game.resolvedThe results frame or the canceled frame. Their fields: kind, results, crashedAt?, capped?, target?, radius?, successChance?, crewSize?, pot?, winner?, payout?, cancelled, reason
play_soundplaybackUrl, volume, handle?, synced
stop_soundhandle?, all
testAny fields
custom. and a source namefields: each value of the custom data source, as text

For a widget whose template contains an element with id="line", this handler updates that element with a welcome message. Register it from your widget’s code; it is a handler excerpt rather than a complete widget project.

JavaScript
NomNomz.on('follow', async (data, eventType, meta) => {
try {
const line = await NomNomz.template.render('Welcome {name}!', { name: data.displayName });
document.querySelector('#line').textContent = line;
} catch (error) {
NomNomz.reportError(String(error));
}
});

This example can display a test event because it changes only the visible text. For a widget that also stores a running total, use meta.test to keep test events out of that stored total.

Run a pipeline action

A pipeline action is one step of a pipeline. A widget or script can request an action type from the table below. A pipeline runs the same action types as steps.

wait_for_event runs only inside a pipeline. From a widget or a script it gives success: false. One action call stops after 45 seconds and fails with “took too long”.

An action can still refuse a request because its inputs, permissions or connected service do not meet its requirements. Check the returned result before treating it as a success.

When an action from a widget or a script starts and then fails, the failure shows in your dashboard inbox for 24 hours. Failures because OBS is not connected show as one notice. That notice goes away when OBS connects again. A refusal (errorCode set) does not make an inbox item.

From a widget

NomNomz.actions.invoke(actionType, params, variables) runs one action as the channel owner, within the owner’s own permissions. params holds the action’s parameters, and variables holds values the action can read. You can leave out params when the action has no required parameter.

The call gives back a result, also when the bot refuses the action or the action fails. The promise rejects if the widget is disconnected, loses its connection while waiting, or receives a hub-level error. Handle rejection separately from a resolved result whose success is false.

FieldMeaning
successtrue when the action ran and succeeded.
outputThe text the action gave back, or null.
errorWhy it failed, or null.
errorCodeSet when the bot refused to run it.
variablesThe action’s values after the run, for example tts.audioUrl and tts.durationMs.
Refusal codeMeaning
AUTH_REQUIREDThe widget connection is not signed in.
FORBIDDENThe widget’s link is for a different widget, the widget is turned off, or the channel owner may not change pipelines.
NOT_FOUNDNothing matches.
RATE_LIMITEDMore than 60 action calls in one minute. Each widget has its own limit. All scripts of the channel share one limit.

Treat a code that is not in this table as a refusal too. A missing or wrong parameter is not a refusal. It comes back as success: false with errorCode set to null, and it makes an inbox item.

From a script

nnz.api.actions.invoke('type', params, variables) runs one action from a script. Its grant is actions.invoke: and the type, so the type must be text in quotes. It gives back success, output, error and variables.

When the action fails, the script goes on, and nnz.lastError says why. params and variables must each be an object.

JavaScript
const result = nnz.api.actions.invoke('tts_synthesize', { text: 'Thanks for the raid!' });

if (!result.success) {
nnz.api.chat.send('No voice line: ' + nnz.lastError.message);
}

The bot posts that line in chat in the channel’s one bot voice.

Action parameters

A parameter in bold is required. An action with “None” takes no parameters. Use the typed parameter reference for each field’s type, optionality and enum values.

ActionParameters
adjust_counterkey, delta
adjust_viewer_datakey, delta, target
announcemessage, color
banuser_id, reason
breakNone
cancel_live_gameNone
check_balanceset_var, min
clear_viewer_datakey
continueNone
deduct_currencyamount, reason
delete_messagemessage_id
draw_giveawaygiveaway_id
enter_giveawaygiveaway_id
grant_currencyamount, reason
jar_contributejar_id, amount
media_playbackcommand, value
music_add_to_playlistplaylistId, provider
music_cycle_repeatNone
music_follow_artistNone
music_nextNone
music_pauseNone
music_playNone
music_play_pauseNone
music_previousNone
music_remove_from_playlistplaylistId, provider
music_save_trackNone
music_seekpositionSeconds
music_set_repeatmode
music_set_shuffleenabled
music_set_volumevolume
music_toggle_savedNone
music_toggle_shuffleNone
music_transfer_devicedeviceId
music_unfollow_artistNone
music_unsave_trackNone
music_volume_downstep
music_volume_muteunmuteVolume
music_volume_upstep
obs_call_vendorvendor, request_type, request_data
obs_filtersource, filter, enabled
obs_hotkeyhotkey_name
obs_input_muteinput, muted, toggle
obs_input_volumeinput, volume_db, volume_mul
obs_mediainput, action
obs_recordingaction
obs_refresh_browserinput
obs_replay_bufferaction
obs_requestrequest_type, request_data
obs_request_batchrequests, execution, halt_on_failure
obs_save_replayNone
obs_screenshotsource, format
obs_set_preview_scenescene
obs_set_sourcescene, source, visible
obs_streamingaction
obs_switch_scenescene
obs_transitiontransition, studio, duration_ms
obs_virtual_camaction
open_giveawaygiveaway_id
permittarget_variable, role_or_capability, duration_minutes
pick_from_listlist, variable
play_gamegame_type, bet
play_soundclip, volume, wait_for_finish, synced, handle
play_track_oncetrack_uri
play_ttstext, segments, voice, as, rate, mode, scene_token
playlist_addplaylist_id, provider, track_uri, message, already_message
post_quotenumber
redemption_fulfillNone
redemption_refundNone
require_tiermin_tier, denied_message
return_valuevalue
run_codecode_script_id
run_pipelinepipeline, mode, args, named_args, wait
scene_releasescene_token
scene_reservemax_hold_seconds
schedule_pipelinepipeline, command, action_type, action_params, delay_seconds, dedupe_key
send_discord_notificationtrigger_type, dedupe_key
send_messagemessage, sender, reply_target, reply_html
send_replymessage
send_webhookendpoint, event_type
send_whisperrecipient, message
set_counterkey, value
set_pronounusername, pronoun
set_variablename, value
set_viewer_datakey, value, target
shoutoutuser_id, cooldown_minutes, global_cooldown_minutes, tts, priority, template
show_raid_recapNone
song_banreason
song_clear_requesterrequester
song_currentNone
song_pauseNone
song_previousNone
song_queuemax
song_queue_closeNone
song_queue_openNone
song_requestquery
song_request_favoriteuser_id
song_resumeNone
song_skipNone
song_volumevolume
song_wrongNone
stage_effectpreset, text, duration_ms, intensity, color
start_live_gamegame_type
start_raidtarget, delay_seconds, raid_window_seconds
stopNone
stop_soundhandle, all
submit_mediaurl
timeoutuser_id, duration, reason
tts_clear_voicetarget_variable
tts_set_voicevoice_id, target_variable
tts_synthesizetext, voice, rate, pitch, play_on_audio
unpermittarget_variable, role_or_capability
unwhitelisttarget_variable
vts_color_tintr, g, b, a, art_mesh_tag
vts_load_modelmodel
vts_move_modelx, y, rotation, size, time_seconds, relative
vts_requestrequest_type, payload_json
vts_set_expressionexpression, active
vts_trigger_hotkeyhotkey
waitmilliseconds, seconds
wait_for_eventevent_name, timeout_seconds
wait_until_raid_firesNone
whitelisttarget_variable, standing
widget_eventwidget_id, event_type, data

play_tts speaks text, or several voices in one clip through segments. segments is a list of blocks in any order: a text block with text and optionally voice, rate, pitch, volume, stress and breakAfterMs, or a pause block with only pause in milliseconds. A pause block adds silence after the block before it. A pause at the start of the list does nothing. When segments is set, it replaces text. It may be a JSON list, or a variable that holds a whole list handed over by a program; words in a whole list from one variable are used as they are, with no template resolved a second time. The block fields are the same as for nnz.api.tts.speakSequence.

Four more things change what a play_tts call does.

  • mode is async or sync, and async is the default. With sync the step waits for the clip length, up to 60 seconds, plus 250 milliseconds.
  • as picks whose saved voice speaks the line. If that person has no saved voice yet, the bot assigns one. The exception is as set to broadcaster, which assigns none.
  • scene_reserve holds the channel’s one TTS slot for a sequence. Each play_tts step of that sequence passes the scene_token that scene_reserve gives back.
  • The TTS bits and standing gate reads user.bits and user.role of the run. A widget or script call has no triggering viewer, so unless you pass those two names in variables, the call is checked as everyone with no bits.

Send a widget an event from a script

nnz.api.widget.emit(widgetIdOrName, eventType, data) sends an event to one widget of the channel. The widget gets it in its NomNomz.on(eventType, ...) handler. data is optional and is sent as the event’s payload.

It gives true when the event is sent, and false when it is not. Then nnz.lastError says why.

CodeWhen
invalid_argumentThe widget or the event name is empty, or data is not valid JSON.
not_foundNo widget of this channel matches.
refusedThe widget is turned off, or it is open in no browser source.
upstream_failedThe event could not be sent to the overlay.
JavaScript
const sent = nnz.api.widget.emit('Alerts', 'hug', { from: bot.args[0] || 'chat' });

if (!sent) {
nnz.api.chat.send('The widget did not get it: ' + nnz.lastError.message);
}

Render a template

A template is text with helpers in braces, such as {name} or {name:argument}. Variables and templates lists every helper and what it gives. The bot renders the template for this channel.

CallGives
NomNomz.template.render(template, values)A promise of the text.
nnz.template.render(template, values)The text.

values fills the plain names of the template. Each value must be text, a number, or true or false. values is an object with at most 64 names. More values, or a value of another type, is refused the same way as a template that is too long.

A template can be at most 4096 characters. An empty template or a longer one is refused. In a widget the promise fails with an error, and in a script the call gives empty text and nnz.lastError says why.