# Bot Lifecycle

This page covers what `New`, `Start`, `Close`, and `Status` do on each platform.

## Order of calls

1. `New(...)` builds the SDK client and validates required arguments. Discord and LINE make no network call here; Telegram's SDK calls `getMe` once (5-second timeout), so a bad Telegram token fails at `New`. No platform starts receiving events yet.
2. `Reply(handler)` registers the handler. It can be called before or after `Start`; events that arrive without a handler are logged with `slog.Warn("Reply is not set")` and dropped.
3. `Start(ctx)` validates credentials, then starts receiving events.
4. `Close()` stops receiving and clears per-bot interactive state.

## Start per platform

| Platform | Credential check (fatal) | Then | Second `Start` |
|---|---|---|---|
| Telegram | `GetMe` | `GetWebhookInfo`; if a webhook URL is set, `DeleteWebhook` (both only warn on failure); long polling runs in a goroutine | returns `nil` |
| Discord | REST `User("@me")` | `Session.Open()` opens the WebSocket gateway | returns `nil` |
| LINE | `GetBotInfo` | `net.Listen` on `:<port>` (a bind failure is returned immediately), then `http.Server.Serve` in a goroutine | returns `nil` |

`Start` derives an internal context from the `ctx` you pass. Cancelling that `ctx` stops Telegram polling; Discord and LINE stop delivering to the handler once the bot is closed.

## Close per platform

| Platform | Steps |
|---|---|
| Telegram | Cancel polling and wait for the polling goroutine; stop all status timers; mark every pending multi-select as done and drop it |
| Discord | Cancel the context and close the gateway session; stop status timers; drop pending input and select state |
| LINE | Cancel the context; `http.Server.Shutdown` with a 5-second timeout; wait for the server goroutine |

`Close` on a bot that never started, or that is already closed, returns `nil`.

## Status

`Status()` returns a snapshot read under the bot's mutex. The identity fields are filled from the `Start` credential check, and stay empty until then.

| Platform | Fields |
|---|---|
| Telegram | `Running bool`, `Username string`, `UserID int64` |
| Discord | `Running bool`, `Username string`, `UserID string` |
| LINE | `Running bool`, `UserID string`, `BasicID string`, `DisplayName string` |

## Related pages

- [Reply Handler](/reply-handler)
- [Telegram Setup](/telegram), [Discord Setup](/discord), [LINE Setup](/line)
