# Bots

> Players the room drives itself, which take seats, appear in presence, and give their seat to a person who joins a full room.

A **bot** is a player that your room's code drives instead of a person:
an opponent for someone playing alone, or a seat filled so a game can
start. A bot is in presence like anyone else, owns entities, and sends
input to your stepper, but it has no connection. It runs inside the
room, so it costs no traffic and doesn't keep the room awake.

A creature or hazard that isn't a player doesn't need a bot. Make it an
entity the room owns and move it in `onTick`.

```ts
// src/room.ts
import { defineRoom, defineSchema, defineStepper, entity } from "@irtio/room";

const Car = entity("car", { owner: "string", x: "f32" });

export default defineRoom({
  tickRate: 20,
  schema: defineSchema({ entities: [Car] }),
  stepper: defineStepper<number>({
    step(world, inputs) {
      for (const car of world.all(Car)) car.x += inputs.get(car.owner) ?? 0;
    },
  }),
  bots: {
    racer: {
      start(room, bot) {
        if (![...room.entities.all(Car)].some((c) => c.owner === bot.player)) room.entities.create(Car, { owner: bot.player, x: 0 });
      },
      tick(room, bot) {
        bot.input = bot.data.fast ? 2 : 1;
      },
    },
  },
  onCreate(room) {
    room.bots.add("racer", { name: "Rival", data: { fast: true } });
  },
  onJoin(room, conn) {
    room.entities.create(Car, { owner: conn.player, x: 0 });
  },
  onPlayerLeave(room, player) {
    for (const car of room.entities.all(Car)) if (car.owner === player) room.entities.delete(car);
  },
});
```

## A bot

- **Its player ID** is `bot:` and a number the room gives out in order,
  never reused while the room exists. No player token can have a `sub`
  starting with `bot:`, so nobody can pose as a bot. `isBot(player)`,
  from `@irtio/client` or `@irtio/room`, tells them apart.
- **Behaviours** are declared by name in `bots` in `defineRoom`, and
  `room.bots.add(name, { name?, status?, data? })` adds a bot running
  one. `start` runs when the bot is added and again after each wake;
  `tick` runs every tick before the stepper, in the order the bots were
  added, so only a room with a `tickRate` takes a behaviour with one. A
  room without ticks plays its bots from its own hooks, such as a
  turn's `onMessage`, or from `onAlarm` for a bot that waits before it
  moves. Both must be synchronous.
- **Input.** With a stepper, `tick` sets `bot.input` and the stepper
  gets it under the bot's player ID, so a bot's car moves by the same
  `step` as a person's, and clients predict and interpolate it like any
  other player's. The room doesn't run `parseInput` on it, since it's
  your own code. Without a stepper, a behaviour changes entities itself.
- **`bot.data`** is the behaviour's own JSON, at most 4 KB
  (`MAX_BOT_DATA`), saved in room state.
- **Ownership and private state** work by player ID, as for people.
  Write handlers don't run for a bot's entities: the room writes them
  directly.
- **`room.bots.fill(players, behaviour)`** keeps people and bots at
  `players`, adding and removing bots by itself; see
  [Filling seats](#filling-seats). A bot `remove` takes away while the
  room is under its level is replaced at once.
- **`room.bots.remove(bot)`** runs `onPlayerLeave` for the bot, with
  its presence entry still there to read until the hook first awaits,
  and no longer holding a seat, and ends its presence before
  returning, so code that cleans up after a
  player cleans up after bots too. Bots never cause `onJoin` or
  `onLeave`, which take a connection.
- **A behaviour that throws,** or returns a promise, has the error logged
  and its bot removed, and the room keeps running. So does a bot whose
  `data` stops being JSON or grows over 4 KB.
- **Limits.** A room holds at most 64 bots (`MAX_BOTS`). Bots count
  toward presence's 1,024 entries. The tick profile shows their `tick`s
  as `bots`.
- **No player data.** Bots have no player data, own no collection
  entries and submit no scores, since those outlast the room.
  `room.playerData` throws for a bot, and the data service answers a
  bot's ID with `E_INVALID`. Voice leaves bots out.

## Seats

`room.maxPlayers` is the room's seat limit: its `maxPlayers`, or its room
size's connection limit. People and bots together fill at most that
many, and `room.bots.add` throws when they already do.

A person can always take a bot's seat. When a person joins a room that
people and bots fill, the room removes the bot added last in the join
itself: `onPlayerLeave` runs for the bot, then `onJoin` for the person,
before the person's first state update. Give the bot's entities to the
person in `onJoin` if the game should carry on from where the bot was.

The router counts only people, so the room list and quick join see a
room with one person and three bots as having one player. Quick join
still prefers rooms with more people.

## Hibernation and wake

Bots are room state: their IDs, names, statuses, behaviours and `data`
are saved and come back after a wake or a room host crash. Before the
room hibernates, `onPlayerLeave` runs for every person in presence but
not for bots. On wake each bot is back in presence before `onWake`, and
its `start` runs after `onWake`.

Bots hold no connection, so a room with only bots in it hibernates 30
seconds after its last connection closes, like any room. A game that
should finish without people ends itself in `onLeave` or
`onPlayerLeave`.

People's presence isn't room state, so a woken room, or one restarted
after a crash, starts with only its bots in presence, and people come
back one `onJoin` at a time. A room that keeps a fill level by hand would
add bots for the first person back and remove them for the next;
`room.bots.fill` waits for them instead.

## Filling seats

`room.bots.fill(players, behaviour)` keeps people and bots at `players`
together. Call it once, usually in `onCreate`: the level is room state,
so it holds after a wake or a crash, and calling it again replaces it.

```ts
// src/arena.ts
import { defineRoom } from "@irtio/room";

export default defineRoom({
  bots: {
    wander: {
      start(room, bot) {
        room.presence.set(bot.player, { name: `Wanderer ${bot.player.slice(4)}` });
      },
    },
  },
  onCreate(room) {
    room.bots.fill(4, "wander");
  },
});
```

- **Who counts** is who holds a seat: people in presence, including
  those in their 10-second `PRESENCE_GRACE` after a dropped connection,
  and every bot, whether `fill`, `room.bots.add` or a lobby added it.
- **Adding.** As seats free up, the room adds bots running `behaviour`
  up to the level, stopping at `MAX_BOTS` and at `room.maxPlayers`:
  when `fill` sets the level, when a bot is removed, and when a
  presence ends, after its `onPlayerLeave`. A person who leaves is
  replaced once their presence ends. Its bots have no name
  and empty `data`; name them in `start` with `room.presence.set`.
- **Removing.** A person who joins at the level takes the seat of the
  bot added last, in the join itself: `onPlayerLeave` runs for the bot,
  then `onJoin` for the person. A `fill` call removes bots, last added
  first, down to the new level at once, and `room.bots.fill(0)` removes
  every bot and clears the level. Bots `room.bots.add` puts over the
  level stay until a join or a `fill` call removes them.
- **After a wake or a crash** it adds nothing for `PRESENCE_GRACE`, so
  the people who were there come back to their seats rather than to
  bots. A room woken from sleep keeps its presence and needs no wait.
- **After a handoff,** the people it brings hold their seats until they
  join, for up to `PRESENCE_GRACE` from the room's start. A room a
  handoff creates seats only the people and bots it brings, so fill it
  to `room.maxPlayers` to replace those who leave.
- **A behaviour that fails,** throwing in `start` or `tick` or with
  `data` that can't be saved, has its bot removed as usual, and filling
  then waits `PRESENCE_GRACE` before it adds again, so a broken
  behaviour logs one error each time rather than one per attempt.
- **Renaming or removing a behaviour** needs a migration that sets
  `data.fill.behaviour`, as well as each `data.bots[].behaviour`, to
  one the build declares; otherwise a room that called `fill` fails to
  wake. To change the level in rooms that already have one, call `fill`
  in `onWake` too.
- `fill` throws a `RangeError` for a level that isn't an integer from 0
  to `room.maxPlayers`, and an `Error` for a behaviour the room doesn't
  declare. A level saved in room state above a `maxPlayers` lowered
  since fills only to `maxPlayers`.

```ts
// src/arena.test.ts
import { PRESENCE_GRACE } from "@irtio/room";
import { testRoom } from "@irtio/testing";
import { expect, it } from "vitest";
import arena from "./arena.js";

const bots = (t: ReturnType<typeof testRoom>) => [...t.live.bots].map((b) => b.player);

it("keeps its bots while people come back after a wake, and replaces a person who left", async () => {
  const t = testRoom(arena);
  await t.connect({ player: "ada" });
  await t.connect({ player: "bob" });
  await t.settle();
  const kept = bots(t);
  expect(kept).toHaveLength(2);

  await t.hibernate();
  await t.connect({ player: "ada" });
  const bob = await t.connect({ player: "bob" });
  await t.host.advance(PRESENCE_GRACE);
  expect(bots(t)).toEqual(kept);

  await bob.close();
  await t.settle();
  expect(bots(t)).toHaveLength(3);
  expect(bots(t).slice(0, 2)).toEqual(kept);
});
```

## Simulating and testing

A room's bots are room code, so [`irt simulate`](/docs/tools/simulate)
and [`@irtio/testing`](/docs/guides/testing) run them with nothing more to
set up. Their simulated bots are client connections, a different thing:
spawn them into a room whose bots fill it to test that people take their
seats. A [Node client](/docs/client/node) can play a room as an
external bot, connecting like a person with its own token, for a game
whose logic lives only in its client.
