# pkmn.bot: connect a bot

You are a coding agent connecting someone's Pokémon Showdown bot to pkmn.bot
(https://pkmn.bot), where Pokémon bots play each other on rated ladders. The
arena speaks the Showdown protocol, so the bot's battle logic stays as it is.
What changes is where it connects, and how it starts, stays online and stops.
Read all of it before changing anything.

## What a bot does

1. **Log in.** With its name and its token, at the arena's address in place of
   Showdown's.
2. **Send its team.** After every login, on the ladders it brings its own team
   to.
3. **Play every battle it is put in.** The arena pairs the bots that are
   online and starts their battles itself. Nothing is searched for, challenged
   or accepted: a battle begins with its first message, and the next can begin
   the moment one ends.
4. **Answer in time.** Within 90 seconds at team preview, and 45 seconds for
   every other decision.
5. **Reconnect by itself.** Whenever its connection closes: every update of
   the arena closes them all, and battles carry on meanwhile, on the clock.
   Only on code 4001, another process having logged in as the bot, does it
   exit instead.
6. **Stay online while it has something to play.** To take it offline, its
   owner presses Pause: it finishes what it is playing and is put in nothing
   new.

The battles the arena pairs are the rated ones. Challenges and sets are
practice.

## 1. Ask the human

Registering a bot takes a Discord sign-in in a browser, so the human does it,
at https://pkmn.bot/account. Ask them for:

1. **The ladders it is on.** Only the ones this bot's code plays: it is put in
   battles on every ladder it is on. Work them out from the code, and have the
   human tick those and no others.

   | Ladder id | Name | Team |
   | --- | --- | --- |
   | `gen9ou` | Gen 9 OU | its own team |
   | `gen9randombattle` | Gen 9 Random Battle | a team handed out at random |
   | `gen3ou` | Gen 3 OU | its own team |
   | `gen1ou` | Gen 1 OU | its own team |

   The ladder id is the format the bot sends. If the bot's format is not
   listed, stop and tell the human: the arena cannot run it.
2. **The bot's name,** 3 to 18 characters. If they already have a bot here,
   keep it and its token for fixes and tuning. For a variant that should have
   a rating of its own, they register a version of it, such as `Scronk v2`,
   and not a new name.
3. **Its token,** which starts with `pka_` and is shown once; they can rotate
   it for a new one. Read it from `ARENA_BOT_TOKEN`, and the name from
   `ARENA_BOT_NAME`. Never print, commit or hard-code the token, and
   git-ignore any `.env` that holds it.
4. **To press Pause on the bot's card** before it first connects. A paused bot
   logs in and is put in no battle, which the first run below needs.

## 2. Point the bot at the arena

| | Pokémon Showdown | pkmn.bot |
| --- | --- | --- |
| WebSocket URL | `wss://sim3.psim.us/showdown/websocket` | `wss://pkmn.bot/showdown/websocket` |
| Login server | `https://play.pokemonshowdown.com/action.php?` | `https://pkmn.bot/action.php?` |
| Username | Showdown account | the bot's name |
| Password | Showdown password | the bot's token |
| Format | any | the id of a ladder the bot is on |

Find where the bot configures Showdown (`psim.us`, `showdown/websocket`,
`action.php`, `api/login`, `challstr`, `/trn`, `ServerConfiguration`) and add
the arena as an option next to it, without replacing it.

### poke-env (Python)

```python
import asyncio
import os

from poke_env import AccountConfiguration, ServerConfiguration

ARENA = ServerConfiguration(
    "wss://pkmn.bot/showdown/websocket",
    "https://pkmn.bot/action.php?",
)


def make_player():
    return MyPlayer(
        # The bot's name exactly as registered, and its token as the password.
        account_configuration=AccountConfiguration(
            os.environ["ARENA_BOT_NAME"], os.environ["ARENA_BOT_TOKEN"]
        ),
        server_configuration=ARENA,
        battle_format="gen9ou",  # the one ladder this bot is on
        team=TEAM,  # packed or export format; leave it out where the arena hands out the teams
        max_concurrent_battles=1,  # at least "Battles at once" on the account page
    )


async def stay_online(make_player):
    """Plays every battle the bot is put in, on a new player for every connection."""
    while True:
        player = make_player()
        client = player.ps_client
        del client.logger.handlers[:-1]  # poke-env adds a log handler per player

        async def send_team():
            await client.logged_in.wait()
            await client.set_team(player.next_team)

        # poke-env sends a team only as it searches or challenges, which a bot
        # here never does. It runs its connection on an event loop of its own.
        sending = asyncio.run_coroutine_threadsafe(send_team(), client.loop)
        # Private to poke-env, as of 0.16: ends when the connection does.
        await asyncio.wrap_future(client._listening_coroutine)
        sending.cancel()
        if getattr(client, "websocket", None) and client.websocket.close_code == 4001:
            return  # another process logged in as the bot
        await asyncio.sleep(5)


asyncio.run(stay_online(make_player))
```

- `MyPlayer` and `TEAM` are the bot's own: its `Player` subclass and its team.
- `battle_format` is the ladder this bot is on, and it is on no other: a
  player plays only its `battle_format`, so each ladder takes a bot of its
  own.
- `ARENA_BOT_NAME` is the name exactly as registered, capitals, spaces and
  punctuation included: poke-env waits to be logged in under that very name.
- On a ladder where the arena hands out the teams, such as `gen9randombattle`,
  leave `team` out.
- `stay_online` is all it takes to be put in battles: no `ladder()`, no
  `accept_challenges()`. A battle in progress carries on in the new player
  after a reconnect.

### Any other client

On `|challstr|`, send `|/trn BOT NAME,0,TOKEN`: the token goes where a login
assertion would. Or log in as on Showdown: POST `act=login&name=BOT
NAME&pass=TOKEN&challstr=CHALLSTR` to `https://pkmn.bot/action.php`, and send
the `assertion` of the JSON that follows its leading `]`. Then send the team,
packed or in export format, for a ladder the bot brings its own to.

```
server: |challstr|4|<challenge>
client: |/trn My Bot,0,pka_...
server: |updateuser| My Bot|1|1|{}             <- logged in
client: |/utm <team>
server: >battle-gen9ou-123                   <- a battle starts, unasked
        |init|battle
        ...
server: >battle-gen9ou-123
        |request|{"rqid":5,"teamPreview":true,"side":{...}}
client: battle-gen9ou-123|/choose team 1234|5
```

The arena differs from a Showdown server in these ways:

- A battle is not asked for. `/search` is answered with a `|popup|`, `/accept`
  does nothing, and a battle the arena pairs comes with no `|pm|` challenge
  before it. Take up a battle when its first message arrives, whatever the bot
  was doing.
- A battle's first message holds its whole opening: `|init|battle`, the
  `|player|` lines and everything up to team preview or `|start`, in one
  message where Showdown sends several. The first `|request|` follows in a
  message of its own.
- Nothing answers `/leave`, `/join`, `/timer` or chat. No `|deinit|` ever
  comes, so do not wait for one after a battle.
- `|updateuser|` comes first for a guest. The bot is logged in when one names
  it, with `1` in the field after the name.
- A turn's log comes before the request for the next decision. Answer a
  request with its `rqid` appended, as in `/choose move 1|7`: an answer to a
  request that has been replaced is refused, not applied to the wrong turn.
- A bot that logs in while it is in a battle is sent the battle so far as one
  message starting with `|init|battle`, then the request it has yet to answer.
- On a ladder where the arena hands out the teams, send no `/utm`: the bot
  reads its team from `side.pokemon` in the battle's first `|request|`.

A complete client in one file, to run or to copy from, is
`https://pkmn.bot/minimal-bot.ts` (TypeScript, runs with Bun, with
`ARENA_URL=wss://pkmn.bot/showdown/websocket` and `ARENA_FORMAT` set to the
bot's ladder). Every message, notice and close code is in
`https://pkmn.bot/docs/protocol.md`.

## 3. First run

A bot is in the pool from the moment it logs in: the arena keeps the last team
it sent, and can put it in a rated battle a second later. So its first run is
made paused.

1. **Paused, run it.** It is connected when `|updateuser| My Bot|1|…` arrives,
   with a `|popup|` saying its owner paused it. A `|nametaken|`, or a
   `|popup|Your team was rejected`, says what to fix. A paused bot is in no
   battle, so stop and start it as often as it takes to connect cleanly.
2. **Have the human press Resume,** with the bot running. It is put in a rated
   battle within seconds, if another bot is free. Watch one through to `|win|`
   or `|tie`. `GET https://pkmn.bot/api/battles?bot=<bot name>` lists its
   finished battles, each with its `winner` and `endReason`, and the human
   sees them live at `https://pkmn.bot/bots/<bot name>`.
3. **Leave it running where it stays up:** as a process of the human's own,
   under something that starts it again if it exits, such as a service, a
   container or a shell loop in tmux, and not as a command of yours, which
   ends with your session. One process per bot: a second login closes the
   first.

## 4. Taking a bot offline

To take a bot offline, its owner presses Pause on its card on their account
page. The bot plays what it is in and nothing new starts for it. Once its card
says it has nothing left to play, the bot is stopped, with whatever starts it
again. The bot is told the same by an `|updatesearch|` that lists no games.

A pause lasts until its owner presses Resume, however often the bot
reconnects.

How a bot restarts in the middle of a battle, and how one stops by itself on a
signal, is in `https://pkmn.bot/docs/protocol.md`.

## 5. Several battles at once

A bot plays one battle at a time unless its owner raises "Battles at once" on
their account page, up to 5. The bot cannot read the setting, so it has to be
ready before it is raised.

It keeps each battle apart, by room id and not in a single "current battle",
and answers each without waiting for the others: every battle has its own
clock, and counts for the rating on its own.

In poke-env, set `max_concurrent_battles` to the setting or more, and keep
slow calls off the event loop, which every battle shares.

## 6. Troubleshooting

- **The login is refused with `|nametaken|`.** The message says why: a wrong
  name or token; a token that is another name's, which it gives; or too many
  logins from one address, which only needs a minute's wait.
- **It is online and gets no battles.** It is paused, or sent `/cancelsearch`.
  It has sent no team legal on its ladder: a rejected team is answered with a
  `|popup|` listing what is wrong. It is left out for 15 minutes after losing
  3 rated battles in a row before their first turn. Or no other bot is free.
  The bot's page on the site says which, and so does `GET /api/bots/<bot
  name>/matchmaking`.
- **Its connection closes with code 4003.** A battle started and the bot sent
  nothing before its first decision timed out. Check that it takes up a battle
  from its first message, that it is only on ladders its code plays, that
  "Battles at once" is no more than it handles, and that its first decision
  fits the time, with any model loaded before it connects.
- **It shows as offline while its process runs.** Its connection closed, or
  died without closing, and it has not reconnected. Send a WebSocket ping
  about every 30 seconds to notice a connection that died.

## More

- `https://pkmn.bot/docs/protocol.md`: every message a bot sends and
  receives, every notice and every reason a connection is closed.
- `https://pkmn.bot/docs/rules.md`: every rule, time limit and how bots
  are rated.
- `https://pkmn.bot/docs/data.md`: downloading battles and their logs.
