# KickBot widget SDK reference

> The KickBot widget SDK in one page: the four widget files, every widget.json key, every kb event and method, test events, limits and four full examples.

Source: https://kickbot.com/docs/widgets/sdk

A KickBot widget is four files (`index.html`, `style.css`, `script.js` and `widget.json`) that run in a sandboxed page in OBS. Your code gets one global object, `kb`, for live Kick events, settings, saved data, chat messages and KickBot TTS. This page lists every part of the SDK with its exact data, its limits and the mistakes to avoid, and ends with four complete widgets you can copy.

You can write the files in the code editor under **Widgets** > **Create** ([kickbot.com/dashboard/widget-create](https://kickbot.com/dashboard/widget-create)), or let an AI app write them for you (see [Build a Kick widget with your own AI](https://kickbot.com/docs/widgets/build-with-your-ai)). Widgets are free, with no limit on how many you make.

## Contents

- [The four files](#the-four-files)
- [The page your widget runs in](#the-page-your-widget-runs-in)
- [widget.json](#widgetjson)
- [The kb object](#the-kb-object)
- [Events](#events)
- [Settings: kb.settings](#settings-kbsettings)
- [Saved data: kb.store](#saved-data-kbstore)
- [Counts, stream and channel](#counts-stream-and-channel)
- [Chat messages: kb.chat.send](#chat-messages-kbchatsend)
- [KickBot TTS: kb.tts.say](#kickbot-tts-kbttssay)
- [Emotes: kb.parseMessage](#emotes-kbparsemessage)
- [Test events](#test-events)
- [Widgets you publish](#widgets-you-publish)
- [Examples](#examples)

## The four files

| File | What goes in it | Limit |
| --- | --- | --- |
| `index.html` | The markup only. No `<html>`, `<head>` or `<body>` tags. | 500 KB (512,000 characters) |
| `style.css` | The styles. | 500 KB (512,000 characters) |
| `script.js` | The code. It uses the `kb` object. | 500 KB (512,000 characters) |
| `widget.json` | The size, the settings, the saved data names and the control buttons. | 100,000 characters |

How KickBot puts them together:

1. KickBot builds one page. The `kb` object is set up first, then your CSS goes in the head, then your HTML goes in the body, then `script.js` runs at the end of the body.
2. `kb` is ready when `script.js` starts. All settings and saved data are already loaded, so there is nothing to wait for.
3. `script.js` runs as a classic script, not a module. A top-level `await` is a syntax error: put async code in an `async` function.
4. Do not add `<script src="script.js">` or `<link href="style.css">` for your own files. KickBot adds your CSS and JavaScript itself and removes such tags.
5. Libraries and fonts from a public URL work. A `<script src="https://cdn.jsdelivr.net/...">` in `index.html` loads before `script.js` runs. A `<link rel="stylesheet">` to Google Fonts works too.

## The page your widget runs in

- **A sandbox.** The widget runs in a sandboxed frame. It has no cookies and cannot read the page around it (`window.parent`), KickBot's dashboard or other widgets.
- **A transparent background.** `html` and `body` always have a transparent background, so the stream shows behind the widget. Draw your own panel inside the page. Do not try to give `html` or `body` a background.
- **The size from widget.json.** `html` and `body` fill the browser source, and the streamer sets the browser source to the `width` and `height` in `widget.json`. So `height: 100%` in your CSS means the widget's height. The dashboard preview uses the same size.
- **No clicks on stream.** Viewers watch a video of the widget, and the streamer does not click it either. Never use buttons, links or hover effects for actions. Use [controls](#controls) (buttons on the widget's settings page) or chat commands.
- **Network.** `fetch()` works for public APIs that allow browser requests (CORS) without a key. Use only official APIs: unofficial mirrors and scrapers break without warning.
- **Browser storage.** `localStorage` works and is kept in the widget's saved data, so it survives reloads and OBS restarts. `sessionStorage` works but is not kept. Prefer [`kb.store`](#saved-data-kbstore) in new code.
- **The Console.** `console.log`, `console.info`, `console.warn` and `console.error` calls and uncaught errors (with their `script.js` line) show in the **Console** of the code editor.

Where the widget can run:

| Place | `kb.env` | Notes |
| --- | --- | --- |
| Your widget URL (an OBS browser source, or any app that shows a web page) | `'obs'` | The normal case. The [scene editor](https://kickbot.com/docs/widgets/scenes) on the dashboard also runs each widget this way: there `kb.env` is `'obs'`, saved data is saved, chat messages and TTS are sent, and the widget counts as one more open copy. |
| A [KickBot scene](https://kickbot.com/docs/widgets/scenes) (many widgets in one 1920 × 1080 browser source) | `'scene'` | Several widgets share one page. |
| A preview on the dashboard (the code editor, the widget's settings page, the library) | `'preview'` | Test events change counts and stream state here. Chat messages and TTS are never sent from a preview, and its saved data writes stay in the preview (except what a [control](#controls) saves). The scene editor is not a preview (see the first row). |

Your code runs from the start each time a copy loads: when OBS starts, when the streamer refreshes the browser source, and when the scene editor opens. Do not send chat messages or TTS when the widget starts, or they go out each time.

## widget.json

`widget.json` is checked every time you save it. A save with a mistake is refused, and the error names the key and what is wrong, for example `widget.json: settings.2.show_if points to "mode", which is not a setting key of this widget.`

The check refuses wrong types, values out of range and broken `show_if` rules. It does not refuse everything that is wrong: keys it does not know are dropped without an error. See [Mistakes the check does not catch](#mistakes-the-check-does-not-catch).

### Top-level keys

| Key | Type | Required | What it does |
| --- | --- | --- | --- |
| `width` | whole number, 50 to 3840 | No (default `800`) | The width of the widget in px. The streamer sets the OBS browser source to this width. |
| `height` | whole number, 50 to 2160 | No (default `600`) | The height in px. |
| `settings` | array, up to 60 | No | The settings the streamer changes on the widget's settings page. See [Settings](#settings). |
| `saved_data` | array, up to 30 | No | Readable names for saved values, shown under **Saved data** on the settings page. See [saved_data](#saved_data). |
| `controls` | array, up to 8 | No | Buttons under **Actions** on the settings page. See [Controls](#controls). |
| `legacy_storage` | object | No | Only for widgets that moved from the old widget builder. See [Code from the old widget builder](#code-from-the-old-widget-builder). |

Pick a size that fits the content with a small margin, for example 400 × 160 for a counter, 800 × 120 for a goal bar, 800 × 300 for an alert, 400 × 600 for a chat box, or 1920 × 1080 for a full-screen layout. Everything must fit inside that size, including the longest name and the biggest number.

### Settings

Each entry in `settings` is one field on the widget's settings page. Your code reads the value as `kb.settings.<key>`.

| Field | Type | Required | What it does |
| --- | --- | --- | --- |
| `key` | text | Yes | The name in `kb.settings`. Letters, numbers and `_`, starts with a letter or `_`, up to 64 characters. Not `__proto__`, `constructor` or `prototype`. |
| `type` | text | Yes | One of the types below. |
| `label` | text, up to 80 characters | No | The field name the streamer sees. Without it, the key is shown. |
| `default` | the setting's value type | No | The value before the streamer changes it. Left out, it is `''` (empty text) for `text`, `color`, `font`, `select`, `image`, `sound` and `video`, `0` for `number` and `false` for `toggle`. |
| `help` | text, up to 300 characters | No | A short line under the field. |
| `min`, `max`, `step` | number | No | For `number` only. |
| `options` | array of text, up to 50, each up to 80 characters | No (a `select` without it shows an empty dropdown) | The choices of a `select`. Always give a `select` its `options`. |
| `section` | text, up to 60 characters | No | A heading. Settings in a row with the same section form one group. |
| `show_if` | object | No | Show the field only when another setting has a given value. See [show_if](#sections-and-show_if). |

Setting types:

| Type | Value in `kb.settings` | Fields | Example |
| --- | --- | --- | --- |
| `text` | text | | `{ "key": "title", "type": "text", "label": "Title", "default": "Top gifters" }` |
| `number` | number | `min`, `max`, `step` | `{ "key": "rows", "type": "number", "label": "Rows to show", "default": 5, "min": 3, "max": 10 }` |
| `color` | text, `#rrggbb` (the color picker saves lower case; the default stays as you wrote it, so compare without case) | | `{ "key": "accent", "type": "color", "label": "Accent color", "default": "#53FC18" }` |
| `font` | text, a Google Fonts name | | `{ "key": "font", "type": "font", "label": "Font", "default": "Inter" }` |
| `toggle` | `true` or `false` | | `{ "key": "announce", "type": "toggle", "label": "Post the winner in chat", "default": false }` |
| `select` | text, one of `options` | `options` | `{ "key": "layout", "type": "select", "label": "Layout", "default": "List", "options": ["List", "Podium"] }` |
| `image` | text, a URL (empty when none) | | `{ "key": "logo", "type": "image", "label": "Logo", "default": "" }` |
| `sound` | text, a URL (empty when none) | | `{ "key": "sound", "type": "sound", "label": "Alert sound", "default": "" }` |
| `video` | text, a URL (empty when none) | | `{ "key": "clip", "type": "video", "label": "Background video", "default": "" }` |

Good to know about settings:

- A `number` with 100 steps or fewer between `min` and `max` shows as a slider. A wider range shows as a number box. Set `min` and `max` to values a streamer really uses, for example 0 to 100 for an opacity in %.
- KickBot loads the Google Font of every `font` setting for you, in the weights 400 and 700. Your CSS only sets `font-family` from the value. For other weights, load the font yourself with a `<link>` to Google Fonts. With `"default": ""`, the font list starts with **Default font** and the value is empty: give `font-family` a fallback.
- `select` options are shown as you write them, so write them for people: `"List"`, not `"list"`.
- A `select` does not start on its first option. Give it a `default` that is one of its `options`, written exactly the same. Without a `default`, its value is `''`.
- For `image`, `sound` and `video`, the streamer can upload a file on the settings page. The value is its URL.
- Older type names still work: `switch` and `boolean` mean `toggle`, `choice` means `select`, `audio` means `sound`. Any other type is refused.
- Do not start a key with two underscores (`__`). KickBot reserves those names for its own values, so the streamer's value for that setting is never used and the setting always stays at its `default`.
- Put every value a streamer may want to change in settings, with a label that says the unit ("Time on screen (seconds)"). Every color in your CSS should come from a setting.

### Sections and show_if

Use `section` when the widget has more than about 8 settings. Settings in a row with the same `section` show as one group under that heading. Keep each group together, and once you use sections, give every setting a `section` (a setting without one after a group shows under a heading for other settings).

`show_if` hides a setting until another setting has one of the given values:

```json
{ "key": "cap_on", "type": "toggle", "label": "Limit the time", "default": false, "section": "Timer" },
{ "key": "cap_hours", "type": "number", "label": "Limit (hours)", "default": 24, "min": 1, "max": 72, "section": "Timer", "show_if": { "key": "cap_on", "equals": true } },
{ "key": "style", "type": "select", "label": "Style", "default": "Bar", "options": ["Bar", "Ring", "Text"], "section": "Look" },
{ "key": "ring_size", "type": "number", "label": "Ring size (px)", "default": 120, "min": 60, "max": 300, "section": "Look", "show_if": { "key": "style", "in": ["Ring"] } }
```

- Use `equals` with one value or `in` with a list of up to 50 values, never both.
- Compare with the real value: `true` or `false` for a `toggle`, a number for a `number`, and the option exactly as it is in `options` for a `select`.
- A rule that points to itself, to a key that does not exist, or that makes a loop is refused when you save.
- A hidden setting keeps its value and is still in `kb.settings`. Your code must ignore it in the other modes.
- A setting whose `show_if` target is hidden is hidden too.

### saved_data

`saved_data` gives readable names to values your code saves with `kb.store` (or `localStorage`). The streamer sees them under **Saved data** on the widget's settings page and can change or clear them during a stream.

| Field | Type | Required | What it does |
| --- | --- | --- | --- |
| `key` | text, 1 to 200 characters | Yes | The key you pass to `kb.store.set()` (or the `localStorage` key). Must not start with `__kb_`. |
| `label` | text, 1 to 60 characters | Yes | The name the streamer sees. |
| `type` | text | No (default `json`) | How the value is shown and edited. See the table below. |
| `help` | text, up to 200 characters | No | A short line under the value. |
| `default` | any | No | The value your widget uses while nothing is saved. The page shows it, for example after a reset. |

| Type | The value your code saves | How the page shows it |
| --- | --- | --- |
| `number` | a number | A number. |
| `text` | text | Text. |
| `toggle` | `true` or `false` | On or off. |
| `time_left` | an end time in ms since 1970, as from `Date.now()` | The time left as `H:MM:SS`, counting down. |
| `duration` | a length of time in ms | `H:MM:SS`, not counting down (for example the time a paused timer still has). |
| `list` | an array or an object | How many items it has. |
| `json` | anything else | The value as text. |

Name only values a streamer may want to see or fix. Leave out internal values such as ids and caches. Other saved keys still show on the page, without a name.

### Controls

`controls` are buttons under **Actions** on the widget's settings page, for things a streamer does by hand during a stream: "Start over", "Add 10 minutes", "Pick a winner". Your code gets them with `kb.on('control', ...)`.

| Field | Type | Required | What it does |
| --- | --- | --- | --- |
| `id` | text | Yes | What your code gets as `id`. Letters, numbers and `_`, starts with a letter or `_`, up to 40 characters. |
| `label` | text, 1 to 40 characters | Yes | The button text. |
| `confirm` | `true` or `false` | No | Asks the streamer to confirm first. Use it for a control that deletes data. |
| `live` | `true` or `false` | No | Sends the control to the widgets open in OBS instead. See below. |

There are two kinds of control:

- **A normal control** (no `live`) changes saved data. The settings page runs your handler, stores any saved-data changes your handler writes, and restarts every open copy of the widget with the new saved data. A normal control works while OBS is closed. Save the result in the handler right away: do not wait for a timer, a `fetch()` or an animation before you save.
- **A live control** (`"live": true`) does something on stream now: spin a wheel, start a round, play an animation. It goes to the copies of the widget that are open in OBS, and the settings page saves nothing from it. It does nothing while the widget is not open anywhere.

In the code editor, the controls also show as buttons under **Actions** next to the test buttons in **Preview** view.

### Permissions

A widget does not ask for permissions in `widget.json`. Under **Permissions** on each installed widget's settings page, the streamer can turn off **Send chat messages** and **Play TTS messages** for that widget. Then `kb.chat.send()` or `kb.tts.say()` fails with the code `permission_off`.

### Limits

| What | Limit |
| --- | --- |
| `index.html`, `style.css`, `script.js` | 500 KB (512,000 characters) each |
| `widget.json` | 100,000 characters |
| Widget size | Width 50 to 3840 px, height 50 to 2160 px |
| Settings, saved data names, controls | 60 settings, 30 saved data names, 8 controls |
| Saved data (`kb.store`) | 3 MB for each installed widget, 512 KB for one value, keys of 1 to 200 characters |
| Chat messages from widgets | 10 a minute for all widgets on the channel together, 500 characters each |
| TTS messages from widgets | 6 a minute for all widgets on the channel together, 300 characters each (or the channel's lower TTS maximum) |
| Library publish checks | 20 a day for each channel |

### Mistakes the check does not catch

The save goes through without an error in these cases, but the widget does not do what you meant:

- **Keys KickBot does not know are dropped.** For example `name`, `description` or `version` at the top level, or `placeholder` on a setting. The widget's name goes in **Name** under **Details** in the code editor (an AI app sets it when it creates the widget). The library description is written when you publish.
- **Two settings with the same `key`:** the last one wins, and the first one is gone. Two `saved_data` entries with the same `key`, or two controls with the same `id`: the first one is kept, and the later ones are dropped.
- **A `select` without `options`** shows an empty dropdown, and its value stays `''`.
- **A `select` whose `default` is not in `options`:** `kb.settings` has that default, but the dropdown cannot show it.
- **A `default` of the wrong type** is changed: for a `number`, `"12"` becomes `12` and text that is not a number becomes `0`. For a `toggle`, `"false"` becomes `false`, but any other text (including `"no"` or `"off"`) becomes `true`. Write real numbers and `true` or `false`.
- **`min` greater than `max`**, or `min`, `max` and `step` on a setting that is not a `number`, are accepted. Check them yourself.
- **A key that starts with `__`** is accepted, but the streamer cannot change its value.
- **A `saved_data` `default` longer than 2,000 characters** (as JSON) is dropped.

### A complete widget.json

This is the `widget.json` of the [sub goal example](#example-2-sub-goal-bar). JSON has no comments, so the notes are below it.

```json
{
	"width": 800,
	"height": 120,
	"settings": [
		{ "key": "title", "type": "text", "label": "Title", "default": "Sub goal", "section": "Goal" },
		{
			"key": "goal",
			"type": "number",
			"label": "Goal (subs)",
			"default": 50,
			"min": 1,
			"max": 10000,
			"section": "Goal"
		},
		{
			"key": "count_gifts",
			"type": "toggle",
			"label": "Count gifted subs",
			"default": true,
			"section": "Goal"
		},
		{
			"key": "done_text",
			"type": "text",
			"label": "Text when the goal is reached",
			"default": "Goal reached!",
			"help": "Leave blank to keep showing the numbers.",
			"section": "Goal"
		},
		{ "key": "bar_color", "type": "color", "label": "Bar color", "default": "#53FC18", "section": "Look" },
		{ "key": "text_color", "type": "color", "label": "Text color", "default": "#FFFFFF", "section": "Look" },
		{ "key": "panel_color", "type": "color", "label": "Panel color", "default": "#0E0F12", "section": "Look" },
		{
			"key": "panel_opacity",
			"type": "number",
			"label": "Panel opacity (%)",
			"default": 85,
			"min": 0,
			"max": 100,
			"step": 5,
			"section": "Look"
		},
		{ "key": "font", "type": "font", "label": "Font", "default": "Inter", "section": "Look" }
	],
	"saved_data": [{ "key": "subs", "label": "Subs counted", "type": "number", "default": 0 }],
	"controls": [
		{ "id": "add_one", "label": "Add 1 sub" },
		{ "id": "reset", "label": "Start over", "confirm": true }
	]
}
```

- `width` and `height`: an 800 × 120 bar. The streamer sets the OBS browser source to 800 × 120.
- `settings`: two sections. "Goal" holds what the widget does, "Look" how it looks. `goal` has a wide range, so it shows as a number box. `panel_opacity` (0 to 100 in steps of 5) shows as a slider.
- `saved_data`: the count the code saves with `kb.store.set('subs', ...)`. `default: 0` shows `0` on the page before the first sub.
- `controls`: "Add 1 sub" for a sub that did not reach the widget, and "Start over" with a confirmation.

## The kb object

`kb` is a global object. It is ready when `script.js` starts, and your code cannot replace it.

| Member | Type | What it is |
| --- | --- | --- |
| [`kb.on(name, handler)`](#events) | function | Listen for an event. Returns a function that removes the listener. |
| [`kb.settings`](#settings-kbsettings) | object | The streamer's settings, by key. |
| [`kb.store`](#saved-data-kbstore) | object | Saved data: `get`, `set`, `delete`, `keys`, `all`. |
| [`kb.counts`](#counts-stream-and-channel) | object | `{ followers, subscribers }`, kept up to date. |
| [`kb.stream`](#counts-stream-and-channel) | object | `{ live, title, started_at, viewers }`, kept up to date. |
| [`kb.channel`](#counts-stream-and-channel) | object | The streamer's channel. |
| [`kb.last`](#latest-events-kblast) | object | `{ follower, sub, gift, tip }`: the newest of each. |
| [`kb.chatHistory`](#chat-history-and-pinned-message) | array | The last chat messages, up to 100. |
| [`kb.pinned`](#chat-history-and-pinned-message) | object or `null` | The message pinned in chat now. |
| [`kb.chat.send(text)`](#chat-messages-kbchatsend) | function | Post a message in Kick chat as KickBot. |
| [`kb.tts.say(text, options)`](#kickbot-tts-kbttssay) | function | Play a message with KickBot TTS. |
| [`kb.parseMessage(text)`](#emotes-kbparsemessage) | function | Split chat text into text and Kick emotes. |
| [`kb.emit(name, data)`](#other-widgets-kbemit) | function | Send a message to the other widgets in the same KickBot scene. |
| [`kb.env`](#environment-kbenv-kbversion-kblimits) | text | `'obs'`, `'scene'` or `'preview'`. |
| [`kb.version`](#environment-kbenv-kbversion-kblimits) | number | `2`. |
| [`kb.limits`](#environment-kbenv-kbversion-kblimits) | object | `{ chat_per_minute: 10, tts_per_minute: 6 }`. |

## Events

```js
const off = kb.on('follow', (data, meta) => {
	console.log(data.user.username, 'followed', meta.test ? '(test)' : '');
});
// Later, to stop listening:
off();
```

- `kb.on(name, handler)` adds a listener and returns a function that removes it. You can add many listeners for one event.
- The handler gets `data` (the event's data, in the tables below) and `meta`: `{ name, test, at }`. `name` is the event name, `test` is `true` for a [test event](#test-events), and `at` is the time in ms since 1970.
- `kb.on('*', handler)` gets every event that reaches the widget, including `settings`, `control`, `emit`, and Kick events that have no KickBot name (see [Kick polls](#kick-polls)). Use `meta.name` to tell them apart, and ignore names you do not know.
- Some events reach the widget only when its code names them. When the widget loads, KickBot looks for these names as plain text in `script.js` and `index.html`:
  - `ttsQueued`, `tts` and `ttsEnd` come reliably only when the code contains `ttsQueued`, `ttsEnd`, or `'tts'` in quotes.
  - `imagine` comes only when the code contains `'imagine'` in quotes.
  - `kb.last.tip` is filled at start only when the code contains `'tip'` in quotes or the text `last.tip`. Write `kb.last.tip`, not `const { tip } = kb.last`. (The `tip` event itself reaches every widget.)

  A widget that only uses `kb.on('*')`, or that builds event names from a setting or a variable, gets none of these, or only some of them. Name each one in the code:

  ```js
  kb.on('tts', showTts); // the name in quotes turns on TTS events for this widget
  kb.on('imagine', showImage); // and AI image events
  kb.on('*', (data, meta) => console.log(meta.name)); // now also gets ttsQueued, tts, ttsEnd and imagine
  ```

- An error in a handler shows in the Console and does not stop the other handlers.
- Events reach the widget only while it is open somewhere. A widget that is not open in OBS (or in a scene, or on a preview) misses any events that happen while it is closed.

### Follows and subs

| Event | Data |
| --- | --- |
| `follow` | `{ user: { username, id }, followers }`. `followers` is the follower count after this follow. |
| `unfollow` | `{ user: { username, id }, followers }`. Someone stopped following. `followers` is the count after it. |
| `sub` | `{ user: { username }, months }`. `months` is the number of sub months, 1 or more. |
| `subGift` | `{ gifter: { username }, count, recipients }`. `recipients` is an array of usernames, `count` its length. |

```js
kb.on('subGift', (e) => {
	addSubs(e.count); // 5 for a gift of 5 subs
	showAlert(`${e.gifter.username} gifted ${e.count} subs`);
});
```

### KICKs, tips and raids

| Event | Data |
| --- | --- |
| `kicks` | `{ user: { username, id, color }, amount, gift: { id, name, type, tier, pinned_seconds, character_limit }, message }`. KICKs are Kick's paid gifts. `amount` is the number of KICKs. `gift.type` is `'BASIC'` or `'LEVEL_UP'`, `gift.tier` is `'BASIC'`, `'MID'` or `'HIGHER'` (Kick can send other upper-case words, and both are `''` when Kick sends none). `pinned_seconds` is how long Kick pins the message in chat (`0` = not pinned). `message` can have [emote codes](#emotes-kbparsemessage). |
| `tip` | `{ user: { username }, anonymous, amount, currency, formatted_amount, message, gif_url, kind }`. A KickBot tip. See below. |
| `raid` | `{ user: { username }, viewers, message }`. `user` is the channel that raids, `viewers` how many viewers came. `message` can be empty. |

About `tip`:

- A `tip` comes once for each tip, when the [KickBot tip alert](https://kickbot.com/docs/tipping/tip-alerts) plays it on stream (so after the streamer's tip moderation). The tip alert must be in OBS: tips reach widgets only when it plays them.
- `amount` is a number in major units (`5` is $5.00) with an upper-case `currency` (`'USD'`, `'EUR'`). Show `formatted_amount` (`'$5.00'`). Never add amounts of different currencies together.
- `anonymous` is `true` when the viewer gave no name. Then `user.username` is `'Anonymous'`.
- `message` can be empty. `gif_url` is the GIF the viewer picked (an https URL) or `null`.
- `kind` is `'live'` (a real tip, paid now), `'replay'` (the streamer plays an old tip again) or `'test'` (a test tip). Count only `'live'` tips in totals, goals and leaderboards.

```js
kb.on('tip', (e) => {
	showAlert(`${e.user.username} tipped ${e.formatted_amount}`, e.message);
	if (e.kind === 'live' && e.currency === 'USD') addToGoal(e.amount);
});
```

### Chat

| Event | Data |
| --- | --- |
| `chat` | A chat message: `{ id, text, user, reply, reply_to, at }`. See below. |
| `chatDeleted` | `{ id }`. A moderator deleted this message. |
| `chatCleared` | `{}`. A moderator cleared the chat. |
| `ban` | `{ user: { username, id }, by: { username }, permanent, duration_minutes, expires_at }`. A moderator banned (`permanent: true`) or timed out a viewer. For a timeout, `duration_minutes` and `expires_at` (ISO time) are set; else they are `null`. Remove that user's messages from a chat widget (match `user.id`). |
| `pinned` | `{ message, duration_seconds, ends_at, pinned_by: { username } }`. A message was pinned in chat. `message` has the `chat` shape. `duration_seconds` is the pin time in seconds, or `null` when Kick sends none. `ends_at` (ISO time) is when Kick removes the pin, or `null`. `pinned_by` can be `null`. For a countdown, use `ends_at` (and show none when it is `null`): `duration_seconds` is always `null` in `kb.pinned` at start. |
| `unpinned` | `{}`. The pin was removed. |

The `chat` data:

| Field | What it is |
| --- | --- |
| `id` | The message id. |
| `text` | The message, made safe: KickBot puts an invisible zero-width space (`\u200b`) into text that looks like an HTML tag (`<b`), an `on...=` attribute or a `javascript:` or `data:` link. Other text and commands such as `!banner` are not changed. Kick emotes are codes like `[emote:37226:KEKW]`: show it with [`kb.parseMessage`](#emotes-kbparsemessage). |
| `user.username`, `user.id`, `user.color` | The sender, and their name color (or `null`). |
| `user.badges` | Badge type names for checks: `'broadcaster'`, `'moderator'`, `'vip'`, `'og'`, `'founder'`, `'subscriber'`, `'sub_gifter'`, `'verified'` and others. Do not show these names. |
| `user.badge_details` | `[{ type, text, count }]`. `text` is the readable name ("Moderator") to show. `count` is the sub months or gift count, or `null`. |
| `reply` | The message this one answers, `{ id, text, user: { username, id } }`, or `null`. |
| `reply_to` | The id of that message, or `null`. |
| `at` | When it was sent (ISO time). |

A chat command for moderators:

```js
kb.on('chat', (e) => {
	if (e.text.trim().toLowerCase() !== '!reset') return;
	const b = e.user.badges;
	if (!b.includes('moderator') && !b.includes('broadcaster')) return;
	resetCounter();
});
```

To show a subscriber badge, use the channel's own badge pictures in `kb.channel.subscriber_badges`: take the one with the highest `months` that is not more than the badge's `count`.

### Stream and counts

| Event | Data |
| --- | --- |
| `streamOnline` | `{ title, started_at }`. The stream went live. |
| `streamOffline` | `{}`. The stream ended. |
| `viewers` | `{ count }`. A new viewer count. |
| `followers` | `{ count }`. A new follower count. It comes when Kick sends a new count, and right after a real follow that changed `kb.counts` (not after a test follow in OBS or a scene). |
| `subscribers` | `{ count }`. A new sub count. It comes when KickBot reads a new count from Kick, and right after a real sub or gift that changed `kb.counts` (not after a test in OBS or a scene). |

`kb.stream` and `kb.counts` already have the new values when these events come. A widget that only shows a number can listen to `followers` and draw `data.count`.

### KickBot TTS and AI images

| Event | Data |
| --- | --- |
| `ttsQueued` | `{ id, user: { username }, message, voice: { name, label, image }, command, type }`. A KickBot TTS message joined the queue. |
| `tts` | The same as `ttsQueued`, plus `duration_ms`. The message starts to play on stream. |
| `ttsEnd` | `{ id, reason }`. The message ended: `reason` is `'done'` (it played to the end), `'skipped'` (the streamer or a moderator skipped it, while it played or before) or `'failed'` (the TTS browser source could not play it). `{ id: null, reason: 'cleared' }` means the streamer cleared the whole queue. |
| `imagine` | `{ id, user: { username }, prompt, image_url }`. A viewer's `!imagine` [AI picture](https://kickbot.com/docs/ai/ai-images) is ready. |

- `type` is `'command'` (a viewer's voice command; `command` is the command, for example `'!brian'`), `'auto_read'` (a chat message that [auto read](https://kickbot.com/docs/tts/auto-read) reads out; `command` is empty) or `'kickbot'` (sent by a widget or an app; `command` is empty).
- `voice.label` is the voice name to show and `voice.image` its picture URL (or `null`).
- `duration_ms` is the length of the audio, `0` when not known.
- These events reach a widget reliably only when its code names them (see [Events](#events)).
- The audio plays in the [KickBot TTS](https://kickbot.com/docs/tts/set-up-tts) browser source, not in your widget. `ttsQueued` arrives even when that source is not open. `tts`, and `ttsEnd` with `'done'` or `'failed'`, arrive only while that TTS browser source is open in OBS. Without it open, `ttsEnd` arrives only for skipped messages and a cleared queue. After you add the first widget that uses TTS events, `tts` events can take a few minutes to start. Refresh the KickBot TTS browser source to start them at once.
- Each message gets at most one `ttsEnd`. A message skipped before it played gets `ttsEnd` with no `tts` before it. When the TTS source closes while a message plays, no `ttsEnd` comes: do not wait for it forever. Hide a message at the latest a few seconds after `duration_ms` (or after a time you choose when `duration_ms` is `0`).
- A widget can start in the middle: after an OBS restart it can get `tts` or `ttsEnd` for a message it never saw queued.
- Tip messages are not TTS events. They play in the tip alert and reach widgets only as the `tip` event.
- Do not call `kb.tts.say()` in a `tts` handler: it makes a loop.

### Kick polls

Kick's own poll (the one a streamer or moderator starts in Kick chat) has no KickBot event name. It reaches `kb.on()` under Kick's own event names, with Kick's data as Kick sends it:

| Event | Data |
| --- | --- |
| `PollUpdateEvent` | `{ poll: { title, options: [{ id, label, votes }], duration, remaining, result_display_duration, has_voted, voted_option_id } }`. It comes when a poll starts and when its votes change. `title` is the question. `id` is the option's number (`0`, `1`, `2` ...), `votes` its number of votes. `duration` (the poll length), `remaining` (the time left) and `result_display_duration` (how long Kick shows the result) are in seconds. |
| `PollDeleteEvent` | `[]` (an empty array). The poll was removed. |

```js
kb.on('PollUpdateEvent', ({ poll }) => showPoll(poll.title, poll.options, Date.now() + (poll.remaining ?? poll.duration) * 1000));
kb.on('PollDeleteEvent', () => hidePoll());
```

- `PollUpdateEvent` and `PollDeleteEvent` are the only Kick event names that widgets can rely on, alongside the KickBot event names on this page. Other Kick events also reach `kb.on('<Kick name>')` and `kb.on('*')` under Kick's name, but Kick can change or remove them at any time: do not build on them.
- Work out the end of the poll from `remaining` each time the event comes. When `remaining` is missing, keep the end you have, or use `duration` for a new poll.
- `has_voted` and `voted_option_id` are about a viewer on kick.com. A widget is not a viewer: ignore them.
- KickBot does not make the poll text safe. Show `title` and `label` with `textContent`, never with `innerHTML`.
- A poll that started before the widget loaded shows only when the next `PollUpdateEvent` comes (the next vote).
- There is no test button for Kick polls. Show sample content when `kb.env === 'preview'`, and start a poll in your Kick chat to try the widget in OBS.

### Dashboard events

| Event | Data |
| --- | --- |
| `settings` | The new `kb.settings`. The streamer changed a setting. |
| `control` | `{ id, seed, at }`. The streamer clicked one of your [controls](#controls). |
| `emit` | `{ name, data }`. Another widget in the same scene called [`kb.emit()`](#other-widgets-kbemit). |

- **`settings`:** listen for it and redraw, and the widget updates in OBS with no reload. If your code does not listen for `settings`, KickBot starts the widget again with the new settings (saved data is kept).
- **`control`:** `id` is the control's id from `widget.json`. `seed` is a random whole number and `at` the time in ms. For a live control, every open copy of the widget gets the same `seed` and `at`, so use the seed to pick a winner and all copies pick the same one.

```js
kb.on('control', async ({ id, seed }) => {
	if (id === 'pick') {
		const entries = (await kb.store.get('entries')) ?? [];
		await kb.store.set('winner', entries[seed % entries.length] ?? null);
	}
});
```

## Settings: kb.settings

`kb.settings` is an object with one value for each setting in `widget.json`, by key, already in the right type (numbers as numbers, toggles as `true` or `false`). Each value is the streamer's value or the `default`.

```js
function applyLook(s) {
	document.documentElement.style.setProperty('--accent', s.accent);
	title.textContent = s.title;
}
applyLook(kb.settings);
kb.on('settings', applyLook);
```

- Read settings each time you need them (`kb.settings.goal`), or redraw in the `settings` event. `kb.settings` gets a new object on each change: do not keep the old object.
- In a KickBot scene with "This scene only" settings, `kb.settings` already has that scene's values.
- Common mistakes: hard-coding a value a streamer wants to change, two color settings that color the same thing, and a setting the code ignores after a change.

## Saved data: kb.store

`kb.store` keeps data for each installed widget across reloads and OBS restarts: counts, end times of timers, leaderboards, game state. Each installed widget has one set of saved data. All open copies of that widget (in several OBS scenes, in KickBot scenes, or on two PCs) write to the same saved data, but one copy does not see what another copy saves while both run: see [Several open copies](#several-open-copies). The streamer sees the saved data under **Saved data** on the settings page.

| Method | Returns | What it does |
| --- | --- | --- |
| `kb.store.get(key)` | Promise of the value, or `null` | The value saved under `key`. |
| `kb.store.set(key, value)` | Promise | Saves `value` (any JSON value) under `key`. |
| `kb.store.delete(key)` | Promise | Removes `key`. |
| `kb.store.keys()` | Promise of an array | All saved keys. |
| `kb.store.all()` | Promise of an object | All saved keys and values. |

```js
const board = (await kb.store.get('board')) ?? {};
board[name] = (board[name] ?? 0) + count;
await kb.store.set('board', board);
```

How it works for your code:

- **Reads are instant.** All saved data is loaded before `script.js` starts. `get`, `keys` and `all` answer from that loaded data at once, so read your state at start and draw.
- **`set` changes the widget's copy at once.** A `get` right after a `set` gives the new value, even before the server answers.
- **Values are copies.** `set` stores a JSON copy: change an object and `set` it again to save the change. `undefined` is saved as `null`. A `Date` becomes text.
- **A missing key gives `null`.** Use `?? defaultValue`.
- **`keys()` and `all()`** leave out the keys that `localStorage` uses and KickBot's own keys.
- **Last write wins.** When two copies of the widget save the same key, the newer value stays.
- **Save when something changes.** Save once for each event or change, not from a timer or an animation loop. The server takes a limited number of saves a minute for each widget, and the extra ones fail with `store_failed`.
- **Previews do not save.** In a dashboard preview (`kb.env === 'preview'`), writes stay in the preview. Only the widget in OBS or a scene saves, and the settings page saves what a normal [control](#controls) writes.
- **The widget starts again after a change on the dashboard.** When the streamer edits saved data, clicks a normal control, or uses **Clear test events**, the widget in OBS starts again with the new saved data. Build your state from `kb.store` at start, and do not keep state that only lives in memory.
- **Timers:** save the end time (`Date.now() + ms`), not the time left. Then a reload shows the right time.
- **Start values:** when a setting controls where saved data starts (such as a starting count), save the starting value you used alongside the data, and start over when the setting changes.

When a save fails, the promise rejects with an `Error` that has a `code`:

| `code` | What it means | What happens to the value |
| --- | --- | --- |
| `too_big` | The value is over 512 KB. | Refused. The widget's copy goes back to the value before (unless your code set the key again since), so `get` gives the old value again. |
| `store_full` | This widget's saved data is over 3 MB. | Refused, as above. Delete keys you do not need. |
| `bad_key` | The key is not 1 to 200 characters. | Refused, as above. |
| `store_failed` or `network` | The server or the connection had a problem. | Kept in the widget. The next `set` of that key saves it. |

A refused write is a write the server will never take as it is: change the value or the key. Always `catch` errors of `set` and `delete`: an uncaught one shows as an error in the Console.

### Several open copies

A streamer can have the same installed widget open in more than one place at once: in two OBS scenes, in a KickBot scene, on a second PC, or in the scene editor on the dashboard. What you can rely on:

- Every open copy gets every event and runs your code on its own.
- Each copy reads the saved data when it starts. It does not see what another open copy saves until it starts again (when OBS restarts, the browser source is refreshed, or the streamer changes something on the dashboard).
- Changes on the dashboard reach every open copy. When the streamer edits saved data, clicks a normal control under **Actions**, or uses **Clear test events**, every open copy starts again with the new saved data. A live control reaches every open copy too, with the same `seed`.
- When two copies save the same key, the last save wins.

How to build for it:

- **Build state from events, the same way in every copy.** A follow counter that adds 1 on each `follow` and saves the result shows the same number in every copy, because every copy gets the same follows.
- **Keep one writer for state that events cannot rebuild,** such as a random pick or a game round. Change it with a normal control (it reaches every copy) or with a live control and its `seed` (every copy picks the same), not in one copy alone.
- **Do not show in one copy what another copy saves while both run,** for example a game state saved by a widget in one scene and shown by the same widget in another scene. Show it from one copy, or put both parts in one widget.

## Counts, stream and channel

| Member | Value |
| --- | --- |
| `kb.counts` | `{ followers, subscribers }`. Numbers, set when the widget starts. A follow, sub or gift changes them at once, and Kick's full counts correct them from time to time. |
| `kb.stream` | `{ live, title, started_at, viewers }`. `live` is `true` while the channel is live. `started_at` is when the stream started (ISO time), or `''` when not known. |
| `kb.channel` | `{ username, slug, avatar, user_id, channel_id, chatroom_id, subscriber_badges }`. `avatar` is the channel picture URL. `subscriber_badges` is `[{ months, badge_image: { src } }]`. |

```js
counter.textContent = kb.counts.followers.toLocaleString('en-US');
kb.on('followers', ({ count }) => (counter.textContent = count.toLocaleString('en-US')));
liveDot.hidden = !kb.stream.live;
```

A test event in OBS or a scene does not change `kb.counts`, `kb.stream` or `kb.pinned` (in a dashboard preview it does). A test `follow` still has the next count in `data.followers`.

### Latest events: kb.last

`kb.last` is `{ follower, sub, gift, tip }`: the newest `follow`, `sub`, `subGift` and real tip, in the same shape as the event data, or `null`. It is set when the widget starts and kept up to date, so a "latest follower" widget shows a name right after an OBS restart.

- `kb.last.tip` is only ever a real tip (`kind: 'live'`), never a replay or a test.
- There is no latest KICKs or latest raid. Keep those in `kb.store`.

### Chat history and pinned message

- `kb.chatHistory` is an array of the last chat messages (up to 100), in the `chat` event shape. New messages are added at the end. The messages it has at start can come newest first: if the first message is newer than the last one (compare `at`), reverse the list before you draw. Do not sort by `at`: messages in the same second have the same `at`, and a sort can swap them. Deleted messages, a cleared chat and the messages of a banned user are taken out. Draw it at start, so a chat widget is not empty after a reload.
- `kb.pinned` is the message pinned in chat now (the `pinned` event data) or `null`. It is set at start, so a pinned message widget shows the pin after an OBS restart.

## Chat messages: kb.chat.send

```js
try {
	await kb.chat.send('Thanks for the gifts!');
} catch (error) {
	console.warn('Not sent:', error.code);
}
```

- Posts `text` in the streamer's Kick chat as the KickBot bot. Spaces and line breaks become single spaces.
- Returns a promise of `{ sent: true }` when it was sent.
- It resolves with `{ sent: false, duplicate: true }` when another open copy of the widget sent the same text at the same moment, for example for the same event (the message goes out once). Two real events in a row still send two messages.
- It resolves with `{ sent: false, test: true }` when the call comes in the 20 seconds after a test event reached this copy of the widget, even when a real event caused the call. It resolves with `{ sent: false, preview: true }` in a dashboard preview. Nothing is sent: the editor Console shows what would have been sent.
- Limits: 500 characters, and 10 messages a minute for all widgets on the channel together.

When it fails, the promise rejects with an `Error` that has a `code`:

| `code` | What it means |
| --- | --- |
| `rate_limited` | Over the limit. `error.retry_after_ms` says how long to wait. |
| `permission_off` | The streamer turned off **Send chat messages** for this widget. |
| `empty`, `too_long` | The text is empty, or over 500 characters. |
| `send_failed` | Kick did not take the message. |
| `network`, `server` | A connection or server problem. |

Other codes are possible, for example `not_found` when the streamer removed the widget, or `failed`. Treat any code you do not know as "not sent".

Design around the limit: never send one message for each event when events can come fast. Collect gifters for some seconds and thank them in one message, send only when something important changes (a new leader, a goal reached), and add a setting to turn chat messages off.

## KickBot TTS: kb.tts.say

```js
try {
	await kb.tts.say('Goal reached!', { voice: 'brian' });
} catch (error) {
	console.warn('Not played:', error.code);
}
```

- Puts `text` in the channel's KickBot TTS queue. It plays in the [KickBot TTS](https://kickbot.com/docs/tts/set-up-tts) browser source, with the channel's volume, delay and skip commands. The widget itself plays no sound.
- `options.voice` is one of the channel's turned-on voices, by its command (`'!brian'` or `'brian'`) or its name. Without a voice, KickBot uses the channel's Brian voice, else its first turned-on voice.
- Returns a promise of `{ sent: true, voice }` (the voice name used). Duplicates, tests and previews resolve with `sent: false` as for [chat messages](#chat-messages-kbchatsend).
- Limits: 300 characters (or the channel's lower TTS maximum), and 6 messages a minute for all widgets on the channel together.
- The widget gets the message back as `ttsQueued`, `tts` and `ttsEnd` events with `type: 'kickbot'`.

Error codes: `rate_limited` (with `retry_after_ms`), `permission_off` (**Play TTS messages** is off for this widget), `tts_off` (TTS is off for the channel), `no_voice` (no turned-on voice with that name), `premium_voice` (the voice needs Premium), `empty`, `too_long`, `tts_failed`, `network` and `server`. Other codes are possible (for example `not_found` or `failed`): treat any code you do not know as "not played".

## Emotes: kb.parseMessage

```js
function showChatText(target, text) {
	target.replaceChildren();
	for (const part of kb.parseMessage(text)) {
		if (part.type === 'text') target.append(document.createTextNode(part.value));
		else {
			const img = document.createElement('img');
			img.src = part.url;
			img.alt = part.name;
			target.append(img);
		}
	}
}
```

- `kb.parseMessage(text)` returns an array of parts: `{ type: 'text', value }` and `{ type: 'emote', id, name, url }`. `url` is the emote picture. HTML entities in the text parts are decoded.
- Use it wherever you show text from Kick chat: `chat` messages, `kb.chatHistory`, the `message` of `kicks` and `raid`, and `message.text` of `pinned`. Without it, viewers see codes like `[emote:37226:KEKW]`.
- Size emote pictures to the text, for example `height: 1.4em; width: auto; vertical-align: middle`.
- Build DOM nodes as above. Never put chat text into `innerHTML`.
- For a command check, compare the raw `text`. To read chat text with `kb.tts.say()` or to count its length, use only the `text` parts.

## Other widgets: kb.emit

`kb.emit(name, data)` sends `{ name, data }` to the other widgets on the same page, which is the other widgets in the same [KickBot scene](https://kickbot.com/docs/widgets/scenes). They get it with `kb.on('emit', ({ name, data }) => ...)`. It does not reach other browser sources, other scenes or other PCs, and it is not saved. `data` must be a JSON value.

```js
// In a goal widget:
kb.emit('goal-reached', { goal: 50 });
// In a confetti widget in the same scene:
kb.on('emit', ({ name }) => name === 'goal-reached' && burst());
```

## Environment: kb.env, kb.version, kb.limits

- `kb.env` is `'obs'`, `'scene'` or `'preview'` (see [the page your widget runs in](#the-page-your-widget-runs-in)). Use it to show a hint or sample content only in a dashboard preview: `if (kb.env === 'preview') ...`.
- The scene editor on the dashboard is not a preview. There `kb.env` is `'obs'`: such a hint does not show, saved data is saved, and chat messages and TTS are sent, as in OBS.
- `kb.version` is `2`.
- `kb.limits` is `{ chat_per_minute: 10, tts_per_minute: 6 }`.

There is no clock API. Use `Date.now()`, and save end times, not time left. Clean up timers and old DOM nodes, so the widget can run for a 12-hour stream without slowing down.

## Test events

Test events let you try a widget without a real follow or sub. They come from the test buttons in the code editor and on the widget's settings page, and from AI apps with the MCP tool `send_widget_test_event`. Each test uses made-up viewers, messages and amounts that change every time.

| Test button | Event your widget gets | Notes |
| --- | --- | --- |
| **Follow** | `follow` | `followers` is the next count. |
| **Sub** | `sub` | Random `months`. |
| **Gifted subs** | `subGift` | Random `count`. |
| **KICKs** | `kicks` | A random KICKs gift. |
| **Tip** | `tip` | `kind: 'test'`. Random amount and currency. |
| **Raid** | `raid` | Random size and message. |
| **Chat message** | `chat` | Can have emotes and badges. |
| **TTS** | `ttsQueued`, then `tts`, then `ttsEnd` | Like a real message. |
| **AI image** | `imagine` | A sample picture. |
| **Pinned message**, **Unpin** | `pinned`, `unpinned` | Only shown when your code uses them. |
| **Stream start**, **Stream end** | `streamOnline`, `streamOffline` | Only shown when your code uses them. |
| A button with a chat command (for example **!banner**) | `chat` | Up to 3 commands that KickBot finds in your code or in setting values. The message is sent as you, with the broadcaster and moderator badges. |

How to tell a test from a real event:

- `meta.test` is `true` for every test event.
- A test tip has `kind: 'test'`. A test tip sent from your tipping page also has `kind: 'test'` and plays through the tip alert like a real tip, so check `kind` for tips, not only `meta.test`.

What a test changes:

- Test events show in the dashboard preview and in every open copy of the widget in OBS, even while you are live.
- Test events change saved data like real events. **Clear test events** (next to the preview) puts saved data back to how it was before the first test, and also removes real events that came in since then. Do not use it during a live stream.
- In OBS and scenes, a test does not change `kb.counts`, `kb.stream` or `kb.pinned`, and never `kb.last.tip`. It does change `kb.last.follower`, `kb.last.sub`, `kb.last.gift` and `kb.chatHistory`.
- For 20 seconds after a test event reaches a copy of the widget, that copy sends no chat messages and no TTS, even for real events that arrive during those 20 seconds. `kb.chat.send()` and `kb.tts.say()` resolve with `{ sent: false, test: true }`, and the Console shows the text.

Most widgets should handle tests like real events, so the streamer sees what will happen. If a test should look different, check `meta.test`, for example to show a small "TEST" tag.

## Widgets you publish

You can publish a widget to the KickBot library (**Everyone in the library**) or share it by link (**Only people with the link**). See [Publish and share a widget](https://kickbot.com/docs/widgets/publish-and-share#publish-a-widget-step-by-step) for the steps. Before it goes out, an automatic check runs on the current files. It blocks the widget only for real problems:

- It sends viewer data, chat messages, channel names, keys or anything private to another website, and the description does not say so and why.
- It runs code downloaded at run time from a site that is not a known library CDN, mines crypto, opens popups, tries to get out of the sandbox, or hides what it does.
- It shows hateful, sexual or gross content, or it is spam, a scam or an ad.
- It does nothing at all, or it is clearly broken (it throws on load, or never shows anything).

The check also gives notes (smaller things to fix), a suggested category and a description. Before a streamer adds your widget, KickBot shows them what it does: whether it saves data, sends chat messages or uses TTS, and which websites it contacts (font and library CDNs such as Google Fonts, jsDelivr, unpkg and cdnjs are not listed). You can run 20 checks a day for each channel, and any file change after a check needs a new check.

Build published widgets for other streamers:

- Defaults must look good and work at once on any channel.
- Put every text people read on stream in a setting. KickBot translates published widgets: setting labels, help texts, section headings, the labels of `select` options, saved data names, control labels, and the default of a text setting that shows on stream. Your code and the values it gets (for example a `select` option's value) never change.
- Never put the streamer's own name, a channel or a key in the code. Use `kb.channel`.
- Each publish is a new version. Streamers who follow the newest version get it.

## Code from the old widget builder

A widget made with the old widget builder moves to this SDK when you change its code (see [Move from the old widget builder to the new widget system](https://kickbot.com/docs/widgets/migrate-from-widget-builder)). Its old globals still work inside the sandbox: `globalValues`, `userVariables`, the `widgetEvent` event on `document`, and `window.kickbotWidget`. New code should use `kb`.

`legacy_storage` in `widget.json` copies old `localStorage` values from OBS to saved data once, the first time the new version loads:

```json
"legacy_storage": { "keys": ["total_follows"], "prefixes": ["score_"] }
```

`keys` are full `localStorage` keys, `prefixes` are the start of built keys (at least 3 characters). Keep `legacy_storage` when you rewrite `widget.json` of a moved widget.

## Examples

Four complete widgets. Each one was run against the real SDK before it was published here, and each `widget.json` passes the check that runs when you save. Paste the four files into a new widget in the code editor, or give this page to your AI app.

### Example 1: Follow counter with a reset button

Counts follows since the last reset and keeps the number across OBS restarts. A **Reset to 0** button on the settings page starts over.

`widget.json`

```json
{
	"width": 400,
	"height": 140,
	"settings": [
		{ "key": "label", "type": "text", "label": "Label", "default": "Follows today" },
		{ "key": "accent", "type": "color", "label": "Number color", "default": "#53FC18" },
		{ "key": "text_color", "type": "color", "label": "Label color", "default": "#FFFFFF" },
		{ "key": "panel_color", "type": "color", "label": "Panel color", "default": "#0E0F12" },
		{
			"key": "panel_opacity",
			"type": "number",
			"label": "Panel opacity (%)",
			"default": 85,
			"min": 0,
			"max": 100,
			"step": 5
		},
		{ "key": "font", "type": "font", "label": "Font", "default": "Inter" }
	],
	"saved_data": [
		{ "key": "follows", "label": "Follows since reset", "type": "number", "default": 0 }
	],
	"controls": [{ "id": "reset", "label": "Reset to 0", "confirm": true }]
}
```

`index.html`

```html
<div class="card">
	<div class="label" id="label"></div>
	<div class="value" id="value">0</div>
</div>
```

`style.css`

```css
.card {
	box-sizing: border-box;
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;
	justify-content: center;
	padding: 0 28px;
	border-radius: 16px;
	background: var(--panel);
	font-family: var(--font);
}
.label {
	color: var(--text);
	font-size: 22px;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}
.value {
	color: var(--accent);
	font-size: 56px;
	font-weight: 700;
	line-height: 1.1;
	text-shadow: 0 2px 6px rgba(0, 0, 0, 0.6);
}
```

`script.js`

```js
const labelEl = document.getElementById('label');
const valueEl = document.getElementById('value');
let follows = 0;

// "#0E0F12" and 85 -> "rgba(14, 15, 18, 0.85)"
function panelColor(hex, opacity) {
	const n = parseInt(String(hex).slice(1), 16) || 0;
	return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${Number(opacity) / 100})`;
}

function applySettings(s) {
	const css = document.documentElement.style;
	css.setProperty('--accent', s.accent);
	css.setProperty('--text', s.text_color);
	css.setProperty('--panel', panelColor(s.panel_color, s.panel_opacity));
	css.setProperty('--font', `'${s.font}', system-ui, sans-serif`);
	labelEl.textContent = s.label;
}

function draw() {
	valueEl.textContent = follows.toLocaleString('en-US');
}

async function save() {
	try {
		await kb.store.set('follows', follows);
	} catch (error) {
		console.error('Could not save the count:', error.code);
	}
}

kb.on('follow', () => {
	follows += 1;
	draw();
	save();
});

kb.on('control', async ({ id }) => {
	if (id !== 'reset') return;
	follows = 0;
	draw();
	await save();
});

kb.on('settings', applySettings);

(async () => {
	applySettings(kb.settings);
	follows = Number(await kb.store.get('follows')) || 0;
	draw();
})();
```

### Example 2: Sub goal bar

A goal bar that counts new subs and, if the streamer wants, gifted subs. The count is saved, and the streamer can add a sub or start over from the settings page.

`widget.json`

```json
{
	"width": 800,
	"height": 120,
	"settings": [
		{ "key": "title", "type": "text", "label": "Title", "default": "Sub goal", "section": "Goal" },
		{
			"key": "goal",
			"type": "number",
			"label": "Goal (subs)",
			"default": 50,
			"min": 1,
			"max": 10000,
			"section": "Goal"
		},
		{
			"key": "count_gifts",
			"type": "toggle",
			"label": "Count gifted subs",
			"default": true,
			"section": "Goal"
		},
		{
			"key": "done_text",
			"type": "text",
			"label": "Text when the goal is reached",
			"default": "Goal reached!",
			"help": "Leave blank to keep showing the numbers.",
			"section": "Goal"
		},
		{ "key": "bar_color", "type": "color", "label": "Bar color", "default": "#53FC18", "section": "Look" },
		{ "key": "text_color", "type": "color", "label": "Text color", "default": "#FFFFFF", "section": "Look" },
		{ "key": "panel_color", "type": "color", "label": "Panel color", "default": "#0E0F12", "section": "Look" },
		{
			"key": "panel_opacity",
			"type": "number",
			"label": "Panel opacity (%)",
			"default": 85,
			"min": 0,
			"max": 100,
			"step": 5,
			"section": "Look"
		},
		{ "key": "font", "type": "font", "label": "Font", "default": "Inter", "section": "Look" }
	],
	"saved_data": [{ "key": "subs", "label": "Subs counted", "type": "number", "default": 0 }],
	"controls": [
		{ "id": "add_one", "label": "Add 1 sub" },
		{ "id": "reset", "label": "Start over", "confirm": true }
	]
}
```

`index.html`

```html
<div class="goal" id="goal">
	<div class="row">
		<span class="title" id="title"></span>
		<span class="numbers" id="numbers"></span>
	</div>
	<div class="track"><div class="fill" id="fill"></div></div>
</div>
```

`style.css`

```css
.goal {
	box-sizing: border-box;
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;
	justify-content: center;
	gap: 12px;
	padding: 0 24px;
	border-radius: 16px;
	background: var(--panel);
	color: var(--text);
	font-family: var(--font);
}
.row {
	display: flex;
	justify-content: space-between;
	gap: 16px;
	font-size: 26px;
	font-weight: 700;
	white-space: nowrap;
}
.title {
	overflow: hidden;
	text-overflow: ellipsis;
}
.track {
	height: 22px;
	border-radius: 11px;
	background: rgba(255, 255, 255, 0.15);
	overflow: hidden;
}
.fill {
	height: 100%;
	width: 0;
	border-radius: 11px;
	background: var(--bar);
	transition: width 0.6s ease;
}
```

`script.js`

```js
const el = {
	title: document.getElementById('title'),
	numbers: document.getElementById('numbers'),
	fill: document.getElementById('fill')
};
let subs = 0;

function panelColor(hex, opacity) {
	const n = parseInt(String(hex).slice(1), 16) || 0;
	return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${Number(opacity) / 100})`;
}

function draw() {
	const s = kb.settings;
	const css = document.documentElement.style;
	css.setProperty('--bar', s.bar_color);
	css.setProperty('--text', s.text_color);
	css.setProperty('--panel', panelColor(s.panel_color, s.panel_opacity));
	css.setProperty('--font', `'${s.font}', system-ui, sans-serif`);

	const goal = Math.max(1, Number(s.goal) || 1);
	const reached = subs >= goal;
	el.title.textContent = s.title;
	el.numbers.textContent = reached && s.done_text ? s.done_text : `${subs} / ${goal}`;
	el.fill.style.width = `${Math.min(100, (subs / goal) * 100)}%`;
}

async function add(n) {
	if (n <= 0) return;
	subs += n;
	draw();
	try {
		await kb.store.set('subs', subs);
	} catch (error) {
		console.error('Could not save the sub count:', error.code);
	}
}

kb.on('sub', () => add(1));
kb.on('subGift', (e) => {
	if (kb.settings.count_gifts) add(e.count);
});

kb.on('control', async ({ id }) => {
	if (id === 'add_one') await add(1);
	if (id === 'reset') {
		subs = 0;
		draw();
		await kb.store.set('subs', 0);
	}
});

kb.on('settings', draw);

(async () => {
	subs = Number(await kb.store.get('subs')) || 0;
	draw();
})();
```

### Example 3: Chat command banner for moderators

Moderators and the streamer type `!banner Your text` in chat to show a banner on stream, and `!banner clear` to hide it. The banner shows Kick emotes, survives OBS restarts, and can post a short confirmation in chat. In OBS the widget is empty while there is no banner; on the dashboard it shows a hint.

`widget.json`

```json
{
	"width": 900,
	"height": 100,
	"settings": [
		{
			"key": "command",
			"type": "text",
			"label": "Command",
			"default": "!banner",
			"help": "Mods type it with a text to show it, or with clear to hide it."
		},
		{
			"key": "reply",
			"type": "toggle",
			"label": "Confirm in chat",
			"default": false
		},
		{ "key": "accent", "type": "color", "label": "Accent color", "default": "#53FC18" },
		{ "key": "text_color", "type": "color", "label": "Text color", "default": "#FFFFFF" },
		{ "key": "panel_color", "type": "color", "label": "Panel color", "default": "#0E0F12" },
		{
			"key": "panel_opacity",
			"type": "number",
			"label": "Panel opacity (%)",
			"default": 85,
			"min": 0,
			"max": 100,
			"step": 5
		},
		{ "key": "font", "type": "font", "label": "Font", "default": "Inter" }
	],
	"saved_data": [{ "key": "banner", "label": "Banner text", "type": "text" }],
	"controls": [{ "id": "clear", "label": "Hide the banner", "confirm": true }]
}
```

`index.html`

```html
<div class="banner" id="banner" hidden>
	<div class="text" id="text"></div>
</div>
```

`style.css`

```css
.banner {
	box-sizing: border-box;
	width: 100%;
	height: 100%;
	display: flex;
	align-items: center;
	padding: 0 28px;
	border-left: 8px solid var(--accent);
	border-radius: 14px;
	background: var(--panel);
	color: var(--text);
	font-family: var(--font);
	font-size: 34px;
	font-weight: 700;
}
.banner[hidden] {
	display: none;
}
.text {
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}
.text.hint {
	opacity: 0.6;
	font-weight: 400;
}
.text img {
	height: 1.4em;
	width: auto;
	vertical-align: middle;
}
```

`script.js`

```js
const bannerEl = document.getElementById('banner');
const textEl = document.getElementById('text');
let banner = '';

function panelColor(hex, opacity) {
	const n = parseInt(String(hex).slice(1), 16) || 0;
	return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${Number(opacity) / 100})`;
}

function applyLook(s) {
	const css = document.documentElement.style;
	css.setProperty('--accent', s.accent);
	css.setProperty('--text', s.text_color);
	css.setProperty('--panel', panelColor(s.panel_color, s.panel_opacity));
	css.setProperty('--font', `'${s.font}', system-ui, sans-serif`);
}

// Chat text with Kick emotes as pictures. Never put chat text in innerHTML.
function showChatText(target, text) {
	target.replaceChildren();
	for (const part of kb.parseMessage(text)) {
		if (part.type === 'text') {
			target.append(document.createTextNode(part.value));
		} else {
			const img = document.createElement('img');
			img.src = part.url;
			img.alt = part.name;
			target.append(img);
		}
	}
}

function draw() {
	textEl.classList.toggle('hint', !banner);
	if (banner) {
		showChatText(textEl, banner);
		bannerEl.hidden = false;
	} else if (kb.env === 'preview') {
		// Only on the dashboard: a hint, so the preview is not empty.
		textEl.textContent = `Type ${kb.settings.command} your text in chat`;
		bannerEl.hidden = false;
	} else {
		bannerEl.hidden = true;
	}
}

async function setBanner(text) {
	banner = text;
	draw();
	try {
		if (text) await kb.store.set('banner', text);
		else await kb.store.delete('banner');
	} catch (error) {
		console.error('Could not save the banner:', error.code);
	}
}

async function reply(text) {
	if (!kb.settings.reply) return;
	try {
		await kb.chat.send(text);
	} catch (error) {
		console.warn('Chat message not sent:', error.code);
	}
}

kb.on('chat', async (e) => {
	const command = String(kb.settings.command || '!banner').trim().toLowerCase();
	const text = e.text.trim();
	const lower = text.toLowerCase();
	if (lower !== command && !lower.startsWith(command + ' ')) return;
	const badges = e.user.badges;
	if (!badges.includes('moderator') && !badges.includes('broadcaster')) return;

	const rest = text.slice(command.length).trim();
	if (!rest) return;
	if (rest.toLowerCase() === 'clear') {
		await setBanner('');
		await reply('Banner hidden.');
	} else {
		await setBanner(rest.slice(0, 200));
		await reply('Banner updated.');
	}
});

kb.on('control', async ({ id }) => {
	if (id === 'clear') await setBanner('');
});

kb.on('settings', (s) => {
	applyLook(s);
	draw();
});

(async () => {
	applyLook(kb.settings);
	banner = String((await kb.store.get('banner')) ?? '');
	draw();
})();
```

### Example 4: Alerts with a queue

Shows follows, subs, gifted subs, KICKs, tips and raids one at a time, each for a set time, with an optional sound. When many events come at once, they wait in a queue, and follows are dropped first when the queue is full. Test events get a "TEST" tag.

`widget.json`

```json
{
	"width": 800,
	"height": 200,
	"settings": [
		{
			"key": "seconds",
			"type": "number",
			"label": "Time on screen (seconds)",
			"default": 6,
			"min": 2,
			"max": 30,
			"section": "Alerts"
		},
		{ "key": "show_follows", "type": "toggle", "label": "Show follows", "default": true, "section": "Alerts" },
		{
			"key": "sound",
			"type": "sound",
			"label": "Sound",
			"default": "",
			"help": "Leave empty for no sound.",
			"section": "Alerts"
		},
		{
			"key": "volume",
			"type": "number",
			"label": "Volume (%)",
			"default": 60,
			"min": 0,
			"max": 100,
			"step": 5,
			"section": "Alerts"
		},
		{ "key": "accent", "type": "color", "label": "Accent color", "default": "#53FC18", "section": "Look" },
		{ "key": "text_color", "type": "color", "label": "Text color", "default": "#FFFFFF", "section": "Look" },
		{ "key": "panel_color", "type": "color", "label": "Panel color", "default": "#0E0F12", "section": "Look" },
		{
			"key": "panel_opacity",
			"type": "number",
			"label": "Panel opacity (%)",
			"default": 90,
			"min": 0,
			"max": 100,
			"step": 5,
			"section": "Look"
		},
		{ "key": "font", "type": "font", "label": "Font", "default": "Inter", "section": "Look" }
	]
}
```

`index.html`

```html
<div class="alert" id="alert">
	<div class="title"><span id="title"></span><span class="test" id="test">TEST</span></div>
	<div class="message" id="message"></div>
</div>
```

`style.css`

```css
.alert {
	box-sizing: border-box;
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;
	justify-content: center;
	gap: 10px;
	padding: 0 32px;
	border-radius: 18px;
	border-bottom: 6px solid var(--accent);
	background: var(--panel);
	color: var(--text);
	font-family: var(--font);
	opacity: 0;
	transform: translateY(24px);
	transition: opacity 0.35s ease, transform 0.35s ease;
}
.alert.show {
	opacity: 1;
	transform: none;
}
.title {
	display: flex;
	align-items: center;
	gap: 12px;
	font-size: 40px;
	font-weight: 700;
	white-space: nowrap;
	overflow: hidden;
}
.test {
	display: none;
	padding: 2px 8px;
	border-radius: 6px;
	background: var(--accent);
	color: #000;
	font-size: 16px;
}
.alert.is-test .test {
	display: inline-block;
}
.message {
	font-size: 24px;
	line-height: 1.3;
	max-height: 2.6em;
	overflow: hidden;
}
.message:empty {
	display: none;
}
.message img {
	height: 1.4em;
	width: auto;
	vertical-align: middle;
}
```

`script.js`

```js
const el = {
	alert: document.getElementById('alert'),
	title: document.getElementById('title'),
	message: document.getElementById('message')
};
const MAX_QUEUE = 50;
const GAP_MS = 400;
const queue = [];
let playing = false;

function panelColor(hex, opacity) {
	const n = parseInt(String(hex).slice(1), 16) || 0;
	return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${Number(opacity) / 100})`;
}

function applyLook(s) {
	const css = document.documentElement.style;
	css.setProperty('--accent', s.accent);
	css.setProperty('--text', s.text_color);
	css.setProperty('--panel', panelColor(s.panel_color, s.panel_opacity));
	css.setProperty('--font', `'${s.font}', system-ui, sans-serif`);
}

function showChatText(target, text) {
	target.replaceChildren();
	for (const part of kb.parseMessage(text)) {
		if (part.type === 'text') target.append(document.createTextNode(part.value));
		else {
			const img = document.createElement('img');
			img.src = part.url;
			img.alt = part.name;
			target.append(img);
		}
	}
}

function enqueue(alert, meta) {
	alert.test = meta.test || alert.test === true;
	queue.push(alert);
	// A raid of follows must not push out the rest: drop the oldest follow first.
	if (queue.length > MAX_QUEUE) {
		const i = queue.findIndex((a) => a.kind === 'follow');
		queue.splice(i >= 0 ? i : 0, 1);
	}
	if (!playing) playNext();
}

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function playNext() {
	const alert = queue.shift();
	if (!alert) {
		playing = false;
		return;
	}
	playing = true;
	el.title.textContent = alert.title;
	showChatText(el.message, alert.message || '');
	el.alert.classList.toggle('is-test', alert.test);
	el.alert.classList.add('show');
	playSound();
	await wait(Math.max(2, Number(kb.settings.seconds) || 6) * 1000);
	el.alert.classList.remove('show');
	await wait(GAP_MS);
	playNext();
}

function playSound() {
	if (!kb.settings.sound) return;
	const audio = new Audio(kb.settings.sound);
	audio.volume = Math.min(1, Math.max(0, Number(kb.settings.volume) / 100));
	audio.play().catch(() => {});
}

kb.on('follow', (e, meta) => {
	if (kb.settings.show_follows) enqueue({ kind: 'follow', title: `${e.user.username} followed` }, meta);
});
kb.on('sub', (e, meta) => {
	const months = e.months > 1 ? ` for ${e.months} months` : '';
	enqueue({ kind: 'sub', title: `${e.user.username} subscribed${months}` }, meta);
});
kb.on('subGift', (e, meta) => {
	const subs = e.count === 1 ? '1 sub' : `${e.count} subs`;
	enqueue({ kind: 'gift', title: `${e.gifter.username} gifted ${subs}` }, meta);
});
kb.on('kicks', (e, meta) => {
	enqueue({ kind: 'kicks', title: `${e.user.username} sent ${e.amount} KICKs`, message: e.message }, meta);
});
kb.on('tip', (e, meta) => {
	// kind 'test' is a test tip, 'replay' a tip played again: shown, with a TEST tag for tests.
	enqueue(
		{ kind: 'tip', title: `${e.user.username} tipped ${e.formatted_amount}`, message: e.message, test: e.kind === 'test' },
		meta
	);
});
kb.on('raid', (e, meta) => {
	enqueue({ kind: 'raid', title: `${e.user.username} raided with ${e.viewers} viewers`, message: e.message }, meta);
});

kb.on('settings', applyLook);
applyLook(kb.settings);
```

## Checklist before you finish

1. No errors in the Console, and every promise of `kb.store`, `kb.chat.send` and `kb.tts.say` has a `catch`.
2. The widget looks right before any event and after many events (50 chat messages, 20 gifts). Chat text shows emotes as pictures.
3. Every value a streamer may change is a setting with a good default, a realistic `min` and `max`, and the unit in the label.
4. Saved data for anything that must survive a reload, read at start, with readable `saved_data` names and controls for what a streamer does during a stream.
5. Chat and TTS stay under the limits on a busy stream.
6. The background is transparent, text is readable on any stream picture, and nothing is cut off at the widget's size.
7. Every event the widget needs is named in the code as plain text, including TTS and AI image events and `kb.last.tip`. Every `select` has a `default` that is one of its `options`.
8. Nothing is sent to chat or TTS when the widget starts, and the widget still works with two copies open.

Related pages: [Build a Kick widget with your own AI](https://kickbot.com/docs/widgets/build-with-your-ai), [Code a Kick widget: quick start](https://kickbot.com/docs/widgets/code-editor), [Publish and share a widget](https://kickbot.com/docs/widgets/publish-and-share), [Customize and control a KickBot widget](https://kickbot.com/docs/widgets/customize-and-control), [Combine widgets in KickBot scenes](https://kickbot.com/docs/widgets/scenes) and the [Custom widgets API](https://kickbot.com/docs/api/reference/widgets).
