# Script reference

Every call a community script can make. Scripts are JavaScript in strict mode (or [Luau](overview.md#other-languages)
with the same names).

## Handlers

The top level only registers handlers.

```js
on('join' | 'leave' | 'message' | 'buy' | 'widget' | 'status' | 'game' | 'playing' | 'webhook', e => { ... })
on('message', { channel: '1v1', startsWith: '!win' }, e => { ... })   // a filter: wakes only for these
command('roll', e => { ... })          // "!roll 1 6": e.args = ['1', '6'], e.text, e.member, e.channel
widget('vote', e => answer)            // a widget's GC.send('vote', data): e.data, e.member; the answer goes back
every(60, e => { ... })                // every N minutes (1 or more)
at('18:00', e => { ... })              // each day at this time (UTC)
button('join', e => 'You're in!')      // a press on this script's button 'join' (or 'join:anything')
menu('role', e => ...)                 // a pick in its menu: e.values
form('apply', e => ...)                // a button's form: e.fields
```

`buy` is a game bought through the store (no buyer named). What a `command`, `button`, `menu` or `form` handler
returns is shown only to whoever used it; `reply()` posts for everyone.

### Filters

| Event | Filter fields |
| --- | --- |
| `message` | `channel` (name, id or a list), `startsWith`, `contains` |
| `command` | `channel` |
| `buy`, `playing` | `game` (ident or a list) |
| `leave` | `kicked: true \| false` |
| `status` | `site` (or a list), `live: true \| false` |
| `webhook` | `hook`, `event` (a name or a list) |
| `edit` | `channel`, `startsWith`, `contains` |
| `delete`, `thread` | `channel` |
| `reaction` | `channel`, `emoji`, `added` |
| `roles` | `role` |
| `achievement`, `quest` | `game` |

Text matches ignore case.

### More events

```js
on('edit', e => ...)        // e.member, e.channel, e.id, e.text, e.was (the text before)
on('delete', e => ...)      // e.member (who deleted), e.author (who wrote; null if a bot's), e.bot, e.channel, e.id
on('reaction', e => ...)    // e.member, e.channel, e.message = { id, bot }, e.emoji, e.added
on('thread', e => ...)      // a public thread started: e.member, e.channel (its parent), e.thread = { id, name }
on('roles', e => ...)       // e.member, e.added, e.removed = [{ id, name }], e.by (null: they, onboarding or a linked role)
on('achievement', e => ...) // e.member, e.game = { ident, title }, e.achievement = { name, title }
on('quest', e => ...)       // a member finished a quest: e.member, e.quest = { name, title, game, minutes }
```

Achievements reach scripts only from members who let the community's bots have them.

### Commands with options

```js
command('roll', {
  description: 'Rolls dice',
  options: [
    { name: 'sides', type: 'whole', required: true, min: 2, max: 100 },
    { name: 'why', type: 'text' },
  ],
}, e => `You rolled ${random(e.options.sides) + 1}`);
```

A command with a description is in the `/` menu, which asks its options. `!roll 6 for luck` fills them in order (the
last text option takes the rest). Types: `text`, `whole`, `number`, `yes/no`, `member`, `channel`, `role`; `choices`
(a list, or `{ name, value }`), `min` and `max` (for text: its length). Required options first.
`e.slash` is true when it came from the menu.

### Settings

```js
const s = settings({
  properties: {
    channel: { type: 'string', title: 'Where to greet', format: 'gc-channel', default: 'general' },
    words: { type: 'string', title: 'Welcome words', default: 'Welcome!' },
  },
});
on('join', e => post(s.channel, `${s.words} ${e.member.name}`));
```

Called once at the top: a JSON Schema form officers fill in (string, number, integer, boolean, array of strings;
`title`, `description`, `default`, `enum` (+ `enumNames`) or `oneOf [{ const, title }]`, min/max, `format: 'color'`
or `'gc-channel'`). `s` holds their values, the defaults for the rest.

## What's in an event

`e.member = { id, name, rank, flair }` (rank 20 member, 30 moderator, 40 officer, 50 owner). `e.channel = { id, name }`.

## Posting

```js
post('general', 'Hello!')               // as the script's bot, in a text or announcements channel; 3 a run
reply('Rolled 4')                        // in the channel the message or command came from
post('general', 'Sign up?', {
  buttons: [{ label: 'Join', id: 'join', style: 'success' }, { label: 'Rules', url: 'https://…' }],
  menu: { id: 'role', placeholder: 'Pick one', options: ['Tank', 'Healer'], min: 1, max: 1 },
})
edit(id, 'New text')                     // or edit(id, { text, card, buttons, menu }): one of its own posts
dm(memberId, 'text', { buttons, menu })  // a direct message; true if sent
```

- **Buttons**: up to 10; `style` primary, secondary, success, danger; `emoji`; `disabled`. A button's `form:
  { title, fields: [{ id, label, long, required, placeholder, min, max }] }` (up to 5 fields).
- **Menus**: up to 25 options, as `{ label, value, description }` or texts.
- **DMs** fail (false) when the member hasn't let the community's bots message them (*Bots and you…*), is under 16
  (under 18: private communities only), or got 5 today. Up to 3 a run, 60 an hour.

## Data

```js
data.get(key), data.set(key, value), data.add(key, n), data.delete(key), data.list(prefix)
```

The community's own JSON data. Keys starting `public.` can also be read by widgets and the page (`GC.data`).

```js
memberData.get(id, key), memberData.set(id, key, value), memberData.add(id, key, n)
memberData.delete(id, key), memberData.list(id, prefix), memberData.top(key, n)  // [{ member, value }]
```

Data about one member: 50 keys of 4 KB each, erased when they leave, are kicked or banned.

## Members

```js
members.get(id), members.find(name), members.count()
flair(memberId, 'Champion', '#ffcc00')   // or flair(memberId, '') to clear
connections.get(id)      // [{ site, name, url }]: accounts the member shared with this community
connections.status(id)   // [{ site, live: { title, game, viewers, since, url } | null, playing: { title, by, url } | null, checked }]
game.get(id)             // { game: { title, steamAppId, ident, source }, phase, mode, map, character, team,
                         //   party: { key, size }, match: { key, players: [{ name, team, character, member }] }, stats, since } | null
match.members(key)       // [member]: members in that match or party (e.match.key, e.party.key) who share it
playing.get(id)          // the old shape: { game: { ident, title }, status, groupSize } | null
on('status', { site: 'twitch', live: true }, e => ...)   // e.member, e.site, e.live, e.playing, e.was
on('game', { game: 'A game', phase: 'end' }, e => ...)   // e.member, game.get's fields, e.was
on('playing', { game: 'a-game' }, e => ...)              // e.member, e.game, e.status, e.groupSize, e.was
```

Connections are Twitch, YouTube, Spotify, Steam, GitHub and Reddit, checked each minute (YouTube each five), only those
the member lets this community see. `game` is what the member is doing in a game (phase: menu, queue, lobby, picking,
loading, match or end; anything unknown is null), only if they share their games with this community (Settings > In
game) and said yes to that game. Keys are hashed with the game; members in one match share its `match.key`. Players who
aren't members are names inside the event only: a script never keeps them.

## Cards

```js
cards.set('board', card), cards.get(name), cards.delete(name), cards.list()
post('general', 'Tonight:', { card: 'board' })   // or reply({ card: 'board' })
```

A card is UI Games Communities draws in a post or a page, updated live: set it again and every message showing it
changes. Cards are **Adaptive Cards 1.6**: `TextBlock`, `Image` (an upload's hash), `Media` (`{ sources: [{ url }],
poster }`: a YouTube, TikTok, Spotify, SoundCloud, Vimeo, Twitch or Instagram link), `Container`, `ColumnSet`,
`FactSet`, `Table`, `ActionSet`, `Input.Text|Number|Toggle|ChoiceSet`, and GC's own `GC.Bar { value, max, label }`
and `GC.Countdown { until, label }`. Buttons are `{ type: 'Action.Execute', title, verb, data }`: `widget(verb)`
answers, with `e.data` = data plus the inputs.

```js
cards.set('score', {
  type: 'AdaptiveCard', version: '1.6',
  body: [
    { type: 'TextBlock', text: 'Raid progress', weight: 'Bolder' },
    { type: 'GC.Bar', value: data.get('raid') ?? 0, max: 100, label: 'Boss HP' },
  ],
  actions: [{ type: 'Action.Execute', title: 'Hit!', verb: 'hit' }],
});
widget('hit', e => { data.add('raid', 1); /* set the card again to update it */ });
```

**Overlay links**: a card can be shown live in a stream, as OBS's browser source. Officers make the link with
`POST /v1/communities/<id>/cards/<name>/overlay` (one per card; the link is shown once, making it again stops the old
one; `DELETE` stops it). The overlay shows the card as a signed-out viewer sees it, without buttons, over the design's
`overlay` scene (see [Effects](../stores/effects.md#places)).

## Look and live news

```js
design.get(), design.set({ accent: '#ff66aa', effect: 'snow' })   // once a run; checked as the Design editor
live('scores', data)              // tells the community's open widgets and page: GC.on('scores', …)
burst('confetti'), burst('hearts', memberId)   // over everyone's pages (or one member's); 30 a minute
sounds.list()                     // [{ id, name, emoji }]
sounds.play('Lounge', 'airhorn')  // a soundboard sound to a voice channel; one every 2 s
```

## Webhooks

```js
on('webhook', { hook: 'github', event: 'push' }, e => ...)
// e.hook, e.kind (plain, github, twitch, websub, standard), e.event, e.id, e.body (JSON or text), e.contentType
webhooks.send('my-server', data)   // to an outgoing webhook with Scripts' data ticked; private groups only, 3 a run, 16 KB
```

Incoming webhook addresses are made in Integrations › **Into scripts**; their signatures are checked. Outgoing ones are
signed as Standard Webhooks sign, and tried again for a day and a half.

## Leagues and quests

```js
leagues.all(), leagues.get(league, key), leagues.set(league, key, value), leagues.add(league, key, 1)
leagues.delete(league, key), leagues.list(league, prefix)   // data shared between communities in a league
quests.set('marathon', { title: 'Play 2 hours', description, game: 'cat-quest', minutes: 120, ends: Date })
quests.get(name), quests.list(), quests.delete(name), quests.progress(name, memberId?)
```

A **league** is several communities sharing data (each one's officers say yes in Code… › Leagues). **Quests**
are play-time goals; members join them themselves, and only their Games Communities play time since then counts.

## Library scripts

```js
const board = use(12, 3)   // library script number 12, version 3: what it put on exports
```

Scripts shared in the [library](tools.md#the-library) can be used by number and version (pinned). Their handlers and
powers become this script's. Up to 5.

## Everything else

`log(...)`, `random(n)`, `now()`, `community = { id, name, members, open }`.

## Powers and limits

A script may use only what its code names when saved: posting (`post`/`reply`), `members`, `flair`, `data`,
`memberData`, `design`, `live`, `cards`, `connections`, `playing`, `webhooks.send`, `leagues`, `sounds`, `burst`;
listening for `message` reads chat, for `webhook` hears outside sites.

Limits: 300 ms, 250,000 statements and 24 MB a run (double in a private group); no network, files or timers of its own.

> [!AI]
> This page is the same API `reference("scripts")` answers through the MCP server. Try a script with `try_script`
> before `save_script`.
