> ## Documentation Index
> Fetch the complete documentation index at: https://valaw.madebyjet.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Build a VALORANT Discord bot

> Build a VALORANT Discord bot in Python with valaw and discord.py: slash commands for match history, ranked leaderboards, and server status, with RSO account linking, caching, and rate-limit handling.

This tutorial walks through a complete VALORANT Discord bot built on Riot's official API, designed so Riot can approve it for a production key. By the end you'll have these slash commands:

| Command | What it does | Endpoints used |
| - | - | - |
| `/link` | Links your Riot account by signing in with Riot (RSO) | RSO, `account-v1` |
| `/unlink` | Removes your linked account | none |
| `/lastmatch [member]` | Summarizes a linked player's most recent match: map, agent, score, K/D/A, ACS | `account-v1`, `val-match-v1`, `val-content-v1` |
| `/leaderboard North America` | Shows the top of the ranked leaderboard for the current act | `val-content-v1`, `val-ranked-v1` |
| `/status Europe` | Shows server incidents and maintenance | `val-status-v1` |
| `/about` | Explains the bot, privacy, and Riot's legal notice | none |

The finished code is in [`examples/discord-bot`](https://github.com/Jet612/valaw/tree/main/examples/discord-bot) on GitHub. Clone it to skip ahead.

> [!NOTE]
>
> **Why `/link` instead of `/stats PlayerName#TAG`?** Riot requires VALORANT apps to get each player's opt-in through Riot Sign On (RSO) before showing their match history. A bot that looks up any Riot ID won't get a production key. This bot only shows match data for players who signed in with `/link`. Leaderboards and server status don't need opt-in. Details are in [Getting a production key](https://valaw.madebyjet.dev/guides/production-key.md).

## Prerequisites

* Python 3.10 or newer
* A Riot API key from the [Riot Developer Portal](https://developer.riotgames.com/). A development key is enough to start the bot, but most VALORANT endpoints return `403` until you have a production key.
* A Discord application with a bot user. Create one in the [Discord Developer Portal](https://discord.com/developers/applications), copy the bot token, and invite the bot to your server with the `bot` and `applications.commands` scopes.
* Later: RSO client credentials from Riot, which are issued after your production key is approved. Until then `/link` is disabled, and everything else runs normally.

## Project setup

**1. Get the code**

```bash theme={null}
git clone https://github.com/Jet612/valaw.git
cd valaw/examples/discord-bot
```

The Python files, each with one job:

* `riot.py`: Riot API access with caching
* `rso.py`: the "Sign in with Riot" flow and linked-account storage
* `bot.py`: Discord slash commands
* `test_example.py`: offline tests for the Riot and RSO logic

**2. Install dependencies**

```bash theme={null}
python -m venv .venv
source .venv/bin/activate   # Windows: .venv\Scripts\activate
pip install -r requirements.txt
```

This installs `valaw`, `discord.py`, and `python-dotenv`.

**3. Add your tokens**

```bash theme={null}
cp .env.example .env
```

Then fill in at least these:

```bash .env theme={null}
DISCORD_TOKEN=your-discord-bot-token
RIOT_API_TOKEN=RGAPI-your-riot-key
RIOT_CLUSTER=americas
DEV_GUILD_ID=123456789012345678
```

`DEV_GUILD_ID` is optional. When it's set, slash commands sync to that one server instantly instead of waiting for global commands to appear.

> [!WARNING]
>
> Never commit `.env`. Anyone with your Riot key can use up your rate limit or get your key revoked.

**4. Run it**

```bash theme={null}
python bot.py
```

Type `/` in your server and the commands appear.

## How it works

### One shared client

Create one `valaw.Client` for the whole bot and reuse it. It holds an `aiohttp` session, so creating one per command wastes connections. `RiotService` in `riot.py` owns the client, and the bot closes it on shutdown:

```python bot.py theme={null}
class ValorantBot(discord.Client):
    def __init__(self, riot, links, rso=None, dev_guild_id=None):
        super().__init__(intents=discord.Intents.default())
        self.tree = app_commands.CommandTree(self)
        self.tree.error(self.on_app_command_error)
        self.riot = riot
        self.links = links
        self.rso = rso
        self.dev_guild_id = dev_guild_id

    async def close(self) -> None:
        if self.rso:
            await self.rso.close()
        await self.riot.close()
        await super().close()
```

Slash commands don't need the privileged message content intent, so `Intents.default()` is enough.

### Account linking with RSO

`/link` sends the user a one-time "Sign in with Riot" button. valaw's [`create_RSO_link`](https://valaw.madebyjet.dev/api-reference/rso/create-rso-link) builds the URL. The random `state` value ties the sign-in to the Discord user and protects against CSRF:

```python rso.py theme={null}
def login_url(self, discord_id: int, discord_name: str) -> str:
    self._drop_expired()
    state = secrets.token_urlsafe(24)
    self._sign_ins[state] = PendingLink(
        discord_id=discord_id,
        discord_name=discord_name,
        generation=self._generation[discord_id],
        expires_at=time.monotonic() + STATE_TTL,
    )
    return self.riot.client.create_RSO_link(
        redirect_uri=self.redirect_uri,
        client_id=self.client_id,
        response_type="code",
        scopes=["openid"],
        state=state,
    )
```

After the player signs in, Riot redirects them to your callback URL. A small `aiohttp` web server, started with the bot, trades the code for an access token. It then asks Riot who signed in using [`GET_getByAccessToken`](https://valaw.madebyjet.dev/api-reference/account/get-by-access-token):

```python rso.py theme={null}
async def callback(self, request: web.Request) -> web.Response:
    pending = self._sign_ins.pop(request.query.get("state", ""), None)
    code = request.query.get("code")
    if not self._is_live(pending) or not code:
        return page("Link expired", "This sign-in link expired. Run /link again.", 400)

    # Error handling omitted here; see rso.py
    access_token = await self.exchange_code(code)
    account = await self.riot.client.GET_getByAccessToken(f"Bearer {access_token}")

    if not self._is_live(pending):  # the user ran /unlink while we waited on Riot
        return page("Link cancelled", "This sign-in was cancelled. Run /link again.", 400)

    pending.account = LinkedAccount(account.puuid, account.gameName or "", account.tagLine or "")
    token = secrets.token_urlsafe(24)
    self._confirms[token] = pending
    return confirm_page(self.confirm_path, token, pending)
```

The callback doesn't save anything yet. It shows a confirmation page: "Link Riot account **Name#TAG** to Discord user **@alice**?" The link is saved only when the person who signed in clicks **Link my account**. Without this step, someone could forward their `/link` URL to a friend, and the friend's Riot sign-in would silently attach to the sender's Discord account. The page shows the Discord **username**, not the display name, because anyone can copy a display name.

Two more details keep linking safe:

* **`/unlink` cancels unfinished sign-ins.** `revoke()` bumps a per-user counter, and the callback and confirmation both check it after waiting on Riot. A sign-in that was in progress can't re-link an account the user just removed.
* **Failed sign-ins are logged** with the cause, but never the authorization code or access token. The player sees a generic error page.

Links are saved to `links.json`. That's fine for one bot process. Move to SQLite or Postgres when you outgrow it.

To turn it on, add your RSO credentials to `.env`:

```bash .env theme={null}
RSO_CLIENT_ID=your-client-id
RSO_CLIENT_SECRET=your-client-secret
RSO_REDIRECT_URI=https://your-domain.example/rso/callback
WEB_PORT=8080
```

The redirect URI must exactly match the one registered with Riot and must be reachable over HTTPS. Put the bot's web server behind a reverse proxy such as Caddy or nginx, or a tunnel such as Cloudflare Tunnel.

### Caching

Most VALORANT data barely changes. Game content changes once per patch, a finished match never changes, and leaderboards update every few minutes. Caching keeps the bot fast and well under Riot's rate limits:

```python riot.py theme={null}
self._content = TTLCache(ttl=60 * 60)  # game content changes once per patch
self._regions = TTLCache(ttl=60 * 60)
self._matches = TTLCache(ttl=60 * 60, maxsize=512)  # finished matches never change
self._leaderboards = TTLCache(ttl=5 * 60)
self._status = TTLCache(ttl=2 * 60)
```

`TTLCache` is a small in-memory dictionary with expiry times. If you run more than one bot process, swap it for Redis.

### Rate-limit handling

The bot doesn't need any rate-limit code of its own. `valaw.Client` waits to stay under your key's limits and retries `429 Too Many Requests` responses, so the bot just calls it:

```python riot.py theme={null}
self.client = valaw.Client(token, cluster)
```

If Riot is still limiting the bot after valaw's retries, the command tells the user to try again in a minute. See [Rate limits](https://valaw.madebyjet.dev/guides/rate-limits.md) for how it works.

### Finding the right region

Account calls go to a **cluster** (`americas`, `europe`, `asia`), but match data lives on the player's **region** (`na`, `eu`, `ap`, `kr`, ...). Don't make users type their region. Ask Riot for the player's active shard:

```python riot.py theme={null}
async def region_for(self, puuid: str) -> str:
    shard = await self._cached(
        self._regions, puuid, lambda: self.client.GET_getActiveShard(puuid)
    )
    return shard.activeShard.lower()
```

### Turning IDs into names

Match data refers to maps by asset path and agents by UUID. Look them up in the cached content response with valaw's [content lookups](https://valaw.madebyjet.dev/api-reference/objects/content-objects.md#lookups):

```python riot.py theme={null}
async def agent_name(self, character_id: str) -> str:
    agent = (await self.content()).get_agent(character_id)
    return agent.name if agent else "Unknown agent"
```

The lookups ignore case, since the content and match endpoints don't use the same casing for IDs.

The `/lastmatch` command gets its stats from [`player_summary`](https://valaw.madebyjet.dev/api-reference/objects/match-objects#matchdto-helpers), so the bot doesn't compute ACS or headshot percentage itself.

### The `/lastmatch` command

`/lastmatch` checks for a linked account before calling Riot. It then defers, because Discord only waits 3 seconds for a response and a cold lookup can take longer:

```python bot.py theme={null}
@app_commands.command(description="Summarize a linked player's most recent match")
@app_commands.describe(member="Whose match to show (defaults to you)")
async def lastmatch(interaction: discord.Interaction, member: discord.User | None = None) -> None:
    bot = bot_of(interaction)
    target = member or interaction.user
    linked = bot.links.get(target.id)
    if linked is None:
        if target == interaction.user:
            raise UserFacingError("Link your Riot account first with /link.")
        raise UserFacingError(f"{target.display_name} hasn't linked a Riot account.")

    await interaction.response.defer()
    region = await bot.riot.region_for(linked.puuid)
    match = await bot.riot.last_match(linked.puuid, region)
    ...
```

### One error handler for every command

Commands don't contain `try`/`except`. Errors bubble up to one tree-wide handler, which turns Riot's status codes into messages a user can act on:

```python riot.py theme={null}
def describe_error(exc):
    if isinstance(exc, UserFacingError):
        return str(exc)
    if isinstance(exc, valaw.Exceptions.RiotAPIResponseError):
        if exc.status_code in (401, 403):
            return (
                "Riot refused the bot's API key. Development keys expire every 24 hours, "
                "and most VALORANT endpoints need a production key."
            )
        if exc.status_code == 429:
            return "The bot is being rate limited by Riot. Try again in a minute."
        ...
    return None  # a real bug: log it
```

## Before you apply for a production key

Riot reviews your bot before it gets a production key. This example already covers the basics: RSO opt-in, `/unlink`, anonymous leaderboard entries stay anonymous, and the legal notice in `/about`. You'll also need a landing page with screenshots of each command. Change `BOT_NAME` in `bot.py` so the legal notice uses your bot's name. See the [Discord bot checklist](https://valaw.madebyjet.dev/guides/production-key.md#checklist-for-discord-bots).

## Ideas for next steps

* **Match tracking.** Poll linked players' match lists every few minutes and post new results to a channel.
* **Persistent cache.** Move `TTLCache` to Redis so restarts don't start from zero.
* **Deploy it.** Any always-on host with HTTPS works for the RSO callback, such as a small VPS behind Caddy, Railway, or Fly.io.

> [card] [Full source on GitHub](https://github.com/Jet612/valaw/tree/main/examples/discord-bot)
>
> Clone the complete bot from examples/discord-bot.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.