Foundry and discord bot
All checks were successful
Build and Deploy Nuxt / build (push) Successful in 1m51s

This commit is contained in:
2026-10-11 22:26:29 +02:00
parent a2b512699a
commit 1402045001
65 changed files with 5962 additions and 144 deletions

View File

@@ -0,0 +1,7 @@
node_modules
.env
.env.*
!.env.example
npm-debug.log*
Dockerfile
.dockerignore

14
discord-bot/.env.example Normal file
View File

@@ -0,0 +1,14 @@
# Create a bot application at https://discord.com/developers/applications
DISCORD_TOKEN=
DISCORD_CLIENT_ID=
# Dragonroll API URL including /api. For local development:
DRAGONROLL_API_URL=http://localhost:5000/api
# Frontend address people open when they click the sign-in button in Discord. The
# frontend then talks to the API above. Set this when the frontend is not reachable
# at the API address.
DRAGONROLL_FRONTEND_URL=http://localhost:3000
# Generate a long random value and set the same value in the backend
# environment as DRAGONROLL_DISCORD_BOT_SECRET.
DRAGONROLL_DISCORD_BOT_SECRET=replace-with-a-long-random-secret

3
discord-bot/.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
.env
node_modules/
npm-debug.log*

22
discord-bot/Dockerfile Normal file
View File

@@ -0,0 +1,22 @@
# Use official Node.js runtime
FROM node:20-alpine
# Create app directory
WORKDIR /usr/src/app
# Copy package files first (better caching)
COPY package*.json ./
# Install dependencies
RUN npm ci --only=production
# Copy application source
COPY . .
# Environment variable
ENV NODE_ENV=production
# The bot only makes outbound connections (Discord gateway + Dragonroll API),
# it does not listen on a port.
# Start the application
CMD ["node", "src/index.js"]

48
discord-bot/README.md Normal file
View File

@@ -0,0 +1,48 @@
# Dragonroll Discord bot
A read-only Discord bot for consulting actors (characters, NPCs, and creatures) from Dragonroll. It talks to Dragonroll through authenticated API endpoints; it does not connect to MongoDB directly.
## Configure one campaign per Discord server
The bot can sit in as many Discord servers as you like. A Discord **Administrator** connects their own Dragonroll account with `/dragonroll connect`, signs in on Dragonroll’s site, then chooses one of their campaigns with `/dragonroll link`. The bot posts an ephemeral confirmation in Discord as soon as the authorization goes through. Dragonroll remembers the account and campaign for that guild. The bot never stores the Dragonroll user's password or token.
```
Discord server A ──link──▶ Dragonroll campaign "Katlum" (account gm-a@example.com)
Discord server B ──link──▶ Dragonroll campaign "Silang" (account gm-b@example.com)
```
## Commands
- `/characters [type]` lists the linked campaign's actors, optionally filtered to characters, NPCs, or creatures.
- `/character name public:true` shows the matching actor's portrait (when one has been uploaded), profile, ability scores, combat stats, proficiencies, traits, spells, and inventory. Type part of a name to pick it from the campaign's current roster. Set `public` to `true` to show the reply to everyone in the channel.
- `/dragonroll connect` starts a short-lived Dragonroll sign-in and authorization link, and confirms here once somebody authorizes the server.
- `/dragonroll link` lets a server administrator choose a campaign owned by the connected Dragonroll account. Type part of a campaign name to filter the choices.
- `/dragonroll unlink` removes this server’s campaign link.
- `/dragonroll status` shows the campaign linked to this server.
- `/dragonroll refresh` rechecks the current connection and campaign in Dragonroll.
Replies are private by default. `/character` can be made public with its `public` option, so everyone in the channel can see the character sheet.
## Setup
1. Create a Discord application and bot in the [Discord Developer Portal](https://discord.com/developers/applications). It only needs permission to use application commands and send replies.
2. Generate a long random shared secret. Set it as `DRAGONROLL_DISCORD_BOT_SECRET` in both the backend environment and the bot's `.env`. This authenticates the bot service; it is not a Dragonroll user account.
3. Copy `.env.example` to `.env` and enter the Discord token, application id, API URL, frontend URL, and shared secret. `DRAGONROLL_API_URL` must be reachable by the bot. `DRAGONROLL_FRONTEND_URL` is the address people open when they click the sign-in button, and it defaults to `http://localhost:3000`. Keep `.env` private.
4. Invite the bot to each server with the `bot` and `applications.commands` scopes. A Discord Administrator runs `/dragonroll connect`, opens the Dragonroll button, signs in and confirms the server link, then returns to Discord and runs `/dragonroll link` to select a campaign they own. Each campaign can be linked to one server at a time.
5. Install packages and register the slash commands:
```sh
npm install
npm run deploy-commands
```
Commands are registered globally, so every server the bot is in can use them. Global registration can take up to an hour to propagate; the bot also registers the commands itself as soon as it joins a server, and refreshes them in every server on each start so command changes reach guild commands too. For quick testing on one server only: `npm run deploy-commands -- --guild <server id>` (note that those guild commands then shadow the global ones in that server).
6. From the repository root, start the backend, frontend, and Discord bot together:
```sh
npm run dev
```
To run only the bot, start the backend first and use `npm start` from `discord-bot/`.
The bot can start without any Dragonroll user account. It uses the shared service secret for guild-scoped API calls, so configure the secret in both environments before using Dragonroll commands. Dragonroll user credentials are entered only on Dragonroll's site and are not sent through Discord. The bot needs outbound access to both the Dragonroll API and Discord.

327
discord-bot/package-lock.json generated Normal file
View File

@@ -0,0 +1,327 @@
{
"name": "dragonroll-discord-bot",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "dragonroll-discord-bot",
"version": "1.0.0",
"dependencies": {
"discord.js": "^14.27.0",
"dotenv": "^17.2.3"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@discordjs/builders": {
"version": "1.14.1",
"resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.14.1.tgz",
"integrity": "sha512-gSKkhXLqs96TCzk66VZuHHl8z2bQMJFGwrXC0f33ngK+FLNau4hU1PYny3DNJfNdSH+gVMzE85/d5FQ2BpcNwQ==",
"license": "Apache-2.0",
"dependencies": {
"@discordjs/formatters": "^0.6.2",
"@discordjs/util": "^1.2.0",
"@sapphire/shapeshift": "^4.0.0",
"discord-api-types": "^0.38.40",
"fast-deep-equal": "^3.1.3",
"ts-mixer": "^6.0.4",
"tslib": "^2.6.3"
},
"engines": {
"node": ">=16.11.0"
},
"funding": {
"url": "https://github.com/discordjs/discord.js?sponsor"
}
},
"node_modules/@discordjs/collection": {
"version": "1.5.3",
"resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.5.3.tgz",
"integrity": "sha512-SVb428OMd3WO1paV3rm6tSjM4wC+Kecaa1EUGX7vc6/fddvw/6lg90z4QtCqm21zvVe92vMMDt9+DkIvjXImQQ==",
"license": "Apache-2.0",
"engines": {
"node": ">=16.11.0"
}
},
"node_modules/@discordjs/formatters": {
"version": "0.6.2",
"resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.6.2.tgz",
"integrity": "sha512-y4UPwWhH6vChKRkGdMB4odasUbHOUwy7KL+OVwF86PvT6QVOwElx+TiI1/6kcmcEe+g5YRXJFiXSXUdabqZOvQ==",
"license": "Apache-2.0",
"dependencies": {
"discord-api-types": "^0.38.33"
},
"engines": {
"node": ">=16.11.0"
},
"funding": {
"url": "https://github.com/discordjs/discord.js?sponsor"
}
},
"node_modules/@discordjs/rest": {
"version": "2.6.3",
"resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.6.3.tgz",
"integrity": "sha512-wvOylxNYJkwKjctS/Mn5GP1w9r3/rzyH+ThD1JlAca6zEdlHs8QWBBUQJpU5Q+W6DoIj/Ljh1IPlZs7hTU+UAg==",
"license": "Apache-2.0",
"dependencies": {
"@discordjs/collection": "^2.1.1",
"@discordjs/util": "^1.2.0",
"@sapphire/async-queue": "^1.5.3",
"@sapphire/snowflake": "^3.5.5",
"@vladfrangu/async_event_emitter": "^2.4.6",
"discord-api-types": "^0.38.50",
"magic-bytes.js": "^1.13.0",
"tslib": "^2.6.3",
"undici": "^6.27.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/discordjs/discord.js?sponsor"
}
},
"node_modules/@discordjs/rest/node_modules/@discordjs/collection": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz",
"integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==",
"license": "Apache-2.0",
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/discordjs/discord.js?sponsor"
}
},
"node_modules/@discordjs/util": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.2.0.tgz",
"integrity": "sha512-3LKP7F2+atl9vJFhaBjn4nOaSWahZ/yWjOvA4e5pnXkt2qyXRCHLxoBQy81GFtLGCq7K9lPm9R517M1U+/90Qg==",
"license": "Apache-2.0",
"dependencies": {
"discord-api-types": "^0.38.33"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/discordjs/discord.js?sponsor"
}
},
"node_modules/@discordjs/ws": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-1.2.3.tgz",
"integrity": "sha512-wPlQDxEmlDg5IxhJPuxXr3Vy9AjYq5xCvFWGJyD7w7Np8ZGu+Mc+97LCoEc/+AYCo2IDpKioiH0/c/mj5ZR9Uw==",
"license": "Apache-2.0",
"dependencies": {
"@discordjs/collection": "^2.1.0",
"@discordjs/rest": "^2.5.1",
"@discordjs/util": "^1.1.0",
"@sapphire/async-queue": "^1.5.2",
"@types/ws": "^8.5.10",
"@vladfrangu/async_event_emitter": "^2.2.4",
"discord-api-types": "^0.38.1",
"tslib": "^2.6.2",
"ws": "^8.17.0"
},
"engines": {
"node": ">=16.11.0"
},
"funding": {
"url": "https://github.com/discordjs/discord.js?sponsor"
}
},
"node_modules/@discordjs/ws/node_modules/@discordjs/collection": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz",
"integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==",
"license": "Apache-2.0",
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/discordjs/discord.js?sponsor"
}
},
"node_modules/@sapphire/async-queue": {
"version": "1.5.5",
"resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.5.5.tgz",
"integrity": "sha512-cvGzxbba6sav2zZkH8GPf2oGk9yYoD5qrNWdu9fRehifgnFZJMV+nuy2nON2roRO4yQQ+v7MK/Pktl/HgfsUXg==",
"license": "MIT",
"engines": {
"node": ">=v14.0.0",
"npm": ">=7.0.0"
}
},
"node_modules/@sapphire/shapeshift": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-4.0.0.tgz",
"integrity": "sha512-d9dUmWVA7MMiKobL3VpLF8P2aeanRTu6ypG2OIaEv/ZHH/SUQ2iHOVyi5wAPjQ+HmnMuL0whK9ez8I/raWbtIg==",
"license": "MIT",
"dependencies": {
"fast-deep-equal": "^3.1.3",
"lodash": "^4.17.21"
},
"engines": {
"node": ">=v16"
}
},
"node_modules/@sapphire/snowflake": {
"version": "3.5.5",
"resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.5.tgz",
"integrity": "sha512-xzvBr1Q1c4lCe7i6sRnrofxeO1QTP/LKQ6A6qy0iB4x5yfiSfARMEQEghojzTNALDTcv8En04qYNIco9/K9eZQ==",
"license": "MIT",
"engines": {
"node": ">=v14.0.0",
"npm": ">=7.0.0"
}
},
"node_modules/@types/node": {
"version": "26.6.5",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz",
"integrity": "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==",
"license": "MIT",
"dependencies": {
"undici-types": "~8.9.0"
}
},
"node_modules/@types/ws": {
"version": "8.18.2",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz",
"integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==",
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@vladfrangu/async_event_emitter": {
"version": "2.4.7",
"resolved": "https://registry.npmjs.org/@vladfrangu/async_event_emitter/-/async_event_emitter-2.4.7.tgz",
"integrity": "sha512-Xfe6rpCTxSxfbswi/W/Pz7zp1WWSNn4A0eW4mLkQUewCrXXtMj31lCg+iQyTkh/CkusZSq9eDflu7tjEDXUY6g==",
"license": "MIT",
"engines": {
"node": ">=v14.0.0",
"npm": ">=7.0.0"
}
},
"node_modules/discord-api-types": {
"version": "0.38.56",
"resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.38.56.tgz",
"integrity": "sha512-Hti4RZsGvF5C7SM8rF2MDHtIm0Hyfrlk84GpEA29nj91tvVVMvX+oQSCodu10t2ZcjFGofq8TX0YyC04B2E69Q==",
"license": "MIT"
},
"node_modules/discord.js": {
"version": "14.27.0",
"resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.27.0.tgz",
"integrity": "sha512-qHbFlFG2N7y3LjPySYsL6A1+BnX6bkTVgo842EX0CqVPk/KTMwZkojPHEXKsQUpWZNyz5BISNHK1cPpQw0+m4A==",
"license": "Apache-2.0",
"dependencies": {
"@discordjs/builders": "^1.14.1",
"@discordjs/collection": "1.5.3",
"@discordjs/formatters": "^0.6.2",
"@discordjs/rest": "^2.6.2",
"@discordjs/util": "^1.2.0",
"@discordjs/ws": "^1.2.3",
"@sapphire/snowflake": "3.5.5",
"discord-api-types": "^0.38.49",
"fast-deep-equal": "3.1.3",
"lodash.snakecase": "4.1.1",
"magic-bytes.js": "^1.13.0",
"tslib": "^2.6.3",
"undici": "^6.27.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/discordjs/discord.js?sponsor"
}
},
"node_modules/dotenv": {
"version": "17.4.2",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz",
"integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://dotenvx.com"
}
},
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"license": "MIT"
},
"node_modules/lodash": {
"version": "4.18.1",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
"integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",
"license": "MIT"
},
"node_modules/lodash.snakecase": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz",
"integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==",
"license": "MIT"
},
"node_modules/magic-bytes.js": {
"version": "1.13.1",
"resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.13.1.tgz",
"integrity": "sha512-x5sn4UX2k5gCWlcfmoFwG4TPie8+dctESyqOBdhB5p6MsgWXdBKGmt9nXPObj/JI50TTL928lc5Yt1WntMn1bw==",
"license": "MIT"
},
"node_modules/ts-mixer": {
"version": "6.0.4",
"resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.4.tgz",
"integrity": "sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA==",
"license": "MIT"
},
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
"node_modules/undici": {
"version": "6.29.0",
"resolved": "https://registry.npmjs.org/undici/-/undici-6.29.0.tgz",
"integrity": "sha512-R+RODBqp6i2pPflGdq+xIOUkl+RNfGgHwoinecKu/JCuf2uO06cOKoDbI2P7Dn6KcswdKwrczbU6IYJ6K8X+wg==",
"license": "MIT",
"engines": {
"node": ">=18.17"
}
},
"node_modules/undici-types": {
"version": "8.9.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
"integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
"license": "MIT"
},
"node_modules/ws": {
"version": "8.22.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",
"integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
}
}
}

18
discord-bot/package.json Normal file
View File

@@ -0,0 +1,18 @@
{
"name": "dragonroll-discord-bot",
"version": "1.0.0",
"private": true,
"description": "Discord slash commands for consulting Dragonroll campaign characters.",
"main": "src/index.js",
"scripts": {
"start": "node src/index.js",
"deploy-commands": "node src/deploy-commands.js"
},
"engines": {
"node": ">=20"
},
"dependencies": {
"discord.js": "^14.27.0",
"dotenv": "^17.2.3"
}
}

View File

@@ -0,0 +1,57 @@
const { InteractionContextType, SlashCommandBuilder } = require('discord.js');
// Every command needs a Dragonroll campaign, and campaigns are linked to
// Discord servers, so none of them make sense in a DM.
const guildOnly = (command) => command.setContexts(InteractionContextType.Guild);
const commands = [
guildOnly(new SlashCommandBuilder()
.setName('characters')
.setDescription('List the characters of the Dragonroll campaign linked to this server.')
.addStringOption((option) => option
.setName('type')
.setDescription('Filter by actor type.')
.addChoices(
{ name: 'All', value: 'all' },
{ name: 'Characters', value: 'character' },
{ name: 'NPCs', value: 'npc' },
{ name: 'Creatures', value: 'creature' }
))),
guildOnly(new SlashCommandBuilder()
.setName('character')
.setDescription('Consult a character sheet from the Dragonroll campaign linked to this server.')
.addStringOption((option) => option
.setName('name')
.setDescription('Character name (full or partial).')
.setRequired(true)
.setMaxLength(100)
.setAutocomplete(true))
.addBooleanOption((option) => option
.setName('public')
.setDescription('Show the character sheet to everyone in this channel.'))),
guildOnly(new SlashCommandBuilder()
.setName('dragonroll')
.setDescription('Configure or check this server’s Dragonroll campaign.')
.addSubcommand((subcommand) => subcommand
.setName('connect')
.setDescription('Connect your Dragonroll account to this server.'))
.addSubcommand((subcommand) => subcommand
.setName('link')
.setDescription('Choose a campaign owned by the connected Dragonroll account.')
.addStringOption((option) => option
.setName('campaign')
.setDescription('Campaign to use in this server.')
.setRequired(true)
.setAutocomplete(true)))
.addSubcommand((subcommand) => subcommand
.setName('unlink')
.setDescription('Remove this server’s Dragonroll campaign link.'))
.addSubcommand((subcommand) => subcommand
.setName('status')
.setDescription('Show the campaign linked to this server.'))
.addSubcommand((subcommand) => subcommand
.setName('refresh')
.setDescription('Refresh this server’s Dragonroll connection status.')))
];
module.exports = commands;

41
discord-bot/src/config.js Normal file
View File

@@ -0,0 +1,41 @@
const dotenv = require('dotenv');
dotenv.config();
function required(name) {
const value = process.env[name]?.trim();
if (!value) throw new Error(`Missing required environment variable: ${name}`);
return value;
}
function apiUrl(value, name) {
const url = value.trim().replace(/\/+$/, '');
if (!/^https?:\/\//i.test(url)) throw new Error(`${name} must start with http:// or https://`);
return url;
}
// Frontend address, not the API: the sign-in page people open from Discord lives there.
function frontendUrl(value, name) {
const url = apiUrl(value, name).replace(/\/api$/i, '');
if (!url) throw new Error(`${name} must be the Dragonroll frontend address, like http://localhost:3000`);
return url;
}
function getConfig() {
const apiUrlValue = process.env.DRAGONROLL_API_URL || 'http://localhost:5000/api';
const apiBaseUrl = apiUrl(apiUrlValue, 'DRAGONROLL_API_URL');
const frontendBaseUrl = frontendUrl(
process.env.DRAGONROLL_FRONTEND_URL || process.env.DRAGONROLL_PUBLIC_API_URL || 'http://localhost:3000',
'DRAGONROLL_FRONTEND_URL'
);
return {
apiBaseUrl,
frontendBaseUrl,
discordBotSecret: process.env.DRAGONROLL_DISCORD_BOT_SECRET?.trim() || '',
discordToken: required('DISCORD_TOKEN'),
discordClientId: required('DISCORD_CLIENT_ID')
};
}
module.exports = { getConfig };

View File

@@ -0,0 +1,44 @@
const { REST, Routes } = require('discord.js');
const { getConfig } = require('./config');
const commands = require('./commands');
// Global by default: the bot can be invited to any number of servers, and the
// campaign it answers with is decided per server by Dragonroll.
// Pass "--guild <server id>" while developing to see changes in one server at once.
function routeFor(clientId, guildId) {
return guildId
? Routes.applicationGuildCommands(clientId, guildId)
: Routes.applicationCommands(clientId);
}
function parseGuildArg(argv) {
const index = argv.indexOf('--guild');
if (index === -1) return null;
const guildId = argv[index + 1];
if (!guildId || guildId.startsWith('--')) {
throw new Error('Usage: npm run deploy-commands -- --guild <discord server id>');
}
return guildId;
}
async function deploy() {
const config = getConfig();
const guildId = parseGuildArg(process.argv.slice(2));
const rest = new REST({ version: '10' }).setToken(config.discordToken);
await rest.put(routeFor(config.discordClientId, guildId), { body: commands.map((command) => command.toJSON()) });
if (guildId) {
console.log(`Registered ${commands.length} commands in Discord server ${guildId}.`);
return;
}
console.log(`Registered ${commands.length} commands globally.`);
console.log('New servers can take up to an hour to see them; the bot also registers them when it joins a server.');
}
deploy().catch((error) => {
console.error('Could not register Discord commands:', error.message);
process.exitCode = 1;
});

View File

@@ -0,0 +1,117 @@
class CampaignNotLinkedError extends Error {
constructor(guildId) {
super(`No Dragonroll campaign is linked to Discord server ${guildId}.`);
this.name = 'CampaignNotLinkedError';
this.guildId = guildId;
}
}
class DragonrollNotConnectedError extends Error {
constructor(guildId) {
super(`No Dragonroll account is connected to Discord server ${guildId}.`);
this.name = 'DragonrollNotConnectedError';
this.guildId = guildId;
}
}
function createDragonrollApi(config) {
async function request(path, options = {}) {
if (!config.discordBotSecret) {
throw new Error('Set DRAGONROLL_DISCORD_BOT_SECRET in the bot and backend environments before using Dragonroll commands.');
}
const response = await fetch(`${config.apiBaseUrl}${path}`, {
...options,
headers: {
...(options.body ? { 'Content-Type': 'application/json' } : {}),
'X-Dragonroll-Discord-Bot-Secret': config.discordBotSecret,
...options.headers
}
});
let payload;
try {
payload = await response.json();
} catch {
const error = new Error(`Dragonroll API returned an unreadable response (${response.status}).`);
error.status = response.status;
throw error;
}
if (!response.ok || payload.status === 'error') {
const error = new Error(payload.msg || `Dragonroll API request failed (${response.status}).`);
error.status = response.status;
error.code = payload.msg;
throw error;
}
return payload;
}
async function startAuthorization(guildId, guildName, discordUserId, discordUserName) {
return request('/discord/link/start', {
method: 'POST',
body: JSON.stringify({ guildId, guildName, discordUserId, discordUserName })
});
}
async function claimLinkNotifications() {
const payload = await request('/discord/bot/link-requests/notifications', { method: 'POST' });
return Array.isArray(payload.notifications) ? payload.notifications : [];
}
async function getStatus(guildId) { return request(`/discord/bot/guild/${encodeURIComponent(guildId)}/status`);
}
async function listCampaigns(guildId) {
const payload = await request(`/discord/bot/guild/${encodeURIComponent(guildId)}/campaigns`);
if (!Array.isArray(payload.campaigns)) {
throw new Error(payload.msg || 'Dragonroll returned an invalid campaign list.');
}
return payload.campaigns;
}
async function linkCampaign(guildId, campaignId) {
const payload = await request(`/discord/bot/guild/${encodeURIComponent(guildId)}/campaign`, {
method: 'POST',
body: JSON.stringify({ campaignId })
});
if (!payload.campaign) throw new Error('Dragonroll returned an invalid campaign link.');
return payload.campaign;
}
async function unlinkCampaign(guildId) {
const current = await getCampaign(guildId);
await request(`/discord/bot/guild/${encodeURIComponent(guildId)}/campaign`, { method: 'DELETE' });
return current;
}
async function getCampaign(guildId) {
const key = String(guildId);
const status = await getStatus(key);
if (!status.connected) throw new DragonrollNotConnectedError(key);
if (!status.campaign) throw new CampaignNotLinkedError(key);
const campaign = {
id: String(status.campaign._id ?? status.campaign.id),
name: status.campaign.name || 'Untitled campaign'
};
if (!campaign.id || campaign.id === 'undefined') throw new Error('Dragonroll returned an invalid campaign.');
return campaign;
}
async function listActors(guildId) {
const payload = await request(`/discord/bot/guild/${encodeURIComponent(guildId)}/actors`);
if (!Array.isArray(payload.actors) || !payload.campaign) {
throw new Error(payload.msg || 'Dragonroll returned an invalid actor list.');
}
const campaign = {
id: String(payload.campaign.id ?? payload.campaign._id),
name: payload.campaign.name || 'Untitled campaign'
};
return { campaign, actors: payload.actors };
}
return { startAuthorization, claimLinkNotifications, getStatus, getCampaign, listCampaigns, linkCampaign, unlinkCampaign, listActors };
}
module.exports = { createDragonrollApi, CampaignNotLinkedError, DragonrollNotConnectedError };

496
discord-bot/src/index.js Normal file
View File

@@ -0,0 +1,496 @@
const {
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
Client,
EmbedBuilder,
Events,
GatewayIntentBits,
MessageFlags,
PermissionFlagsBits,
REST,
Routes
} = require('discord.js');
const { getConfig } = require('./config');
const {
createDragonrollApi,
CampaignNotLinkedError,
DragonrollNotConnectedError
} = require('./dragonroll-api');
const commands = require('./commands');
// Same lifetime as the authorization link on the backend.
const LINK_REQUEST_TTL_MS = 10 * 60 * 1000;
const LINK_NOTIFICATION_POLL_MS = 4000;
function abilityModifier(score) {
const modifier = Math.floor((Number(score || 10) - 10) / 2);
return `${modifier >= 0 ? '+' : ''}${modifier}`;
}
function safeField(value, limit = 600) {
const text = String(value || '').trim();
if (!text) return '—';
return text.length > limit ? `${text.slice(0, limit - 1)}…` : text;
}
// Actor images are stored as a bare filename and served publicly at
// `<api>/public/<filename>`, the same way the frontend renders them. An
// absolute URL is used as-is if one ever gets saved.
function actorImageUrl(image, publicBaseUrl) {
const value = String(image || '').trim();
if (!value) return null;
if (/^https?:\/\//i.test(value)) return value;
return `${publicBaseUrl.replace(/\/+$/, '')}/${encodeURIComponent(value)}`;
}
function actorEmbed(actor, campaign, publicImageBaseUrl) {
const abilities = actor.abilityScores || {};
const abilityFields = [
['💪 STR', 'str'], ['🏹 DEX', 'dex'], ['🛡️ CON', 'con'],
['📚 INT', 'int'], ['👁️ WIS', 'wis'], ['✨ CHA', 'cha']
].map(([name, key]) => {
const score = abilities[key] ?? 10;
return { name, value: `**${score}** · _${abilityModifier(score)}_`, inline: true };
});
const className = String(actor.className || actor.class || '').trim();
const race = actor.species || actor.race;
const embed = new EmbedBuilder()
.setTitle(safeField(actor.name, 256))
.setColor(0x8c6bb1)
.setDescription(safeField(actor.description, 1200))
.setFooter({ text: safeField(`Campaign: ${campaign.name}`, 600) });
const imageUrl = actorImageUrl(actor.image, publicImageBaseUrl);
if (imageUrl) embed.setImage(imageUrl);
embed.addFields(
{ name: '🧬 Race', value: safeField(race), inline: true },
{ name: '⚔️ Class', value: safeField([className, actor.level ? `Level ${actor.level}` : null].filter(Boolean).join(' · ')), inline: true }
);
if (actor.subclass) embed.addFields({ name: '✨ Subclass', value: safeField(actor.subclass), inline: true });
embed.addFields(
{ name: '📜 Background', value: safeField(actor.background), inline: true },
{ name: '🛡️ Combat', value: `AC ${actor.armorClass ?? 10} · Speed ${actor.speed ?? 30} ft.`, inline: true },
{ name: 'Ability scores', value: '\u200b' },
...abilityFields
);
if (actor.proficiencies) embed.addFields({ name: 'Proficiencies', value: safeField(actor.proficiencies) });
if (actor.traits) embed.addFields({ name: 'Traits', value: safeField(actor.traits) });
if (actor.spells) embed.addFields({ name: 'Spells', value: safeField(actor.spells) });
if (Array.isArray(actor.inventory) && actor.inventory.length) {
const inventory = actor.inventory
.map((item) => `${item.name || 'Item'} ×${item.quantity || 1}`)
.join('\n');
embed.addFields({ name: 'Inventory', value: safeField(inventory) });
}
return embed;
}
function findActor(actors, input) {
const query = input.trim().toLocaleLowerCase();
const exact = actors.find((actor) => actor.name.toLocaleLowerCase() === query);
if (exact) return { actor: exact };
const matches = actors.filter((actor) => actor.name.toLocaleLowerCase().includes(query));
if (matches.length === 1) return { actor: matches[0] };
return { matches };
}
async function main() {
const config = getConfig();
if (!config.discordBotSecret) {
console.warn('DRAGONROLL_DISCORD_BOT_SECRET is not set; the bot will start, but Dragonroll commands will need it.');
}
const dragonroll = createDragonrollApi(config);
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
const rest = new REST({ version: '10' }).setToken(config.discordToken);
// Discord downloads character portraits itself, so they need to be absolute
// URLs pointing at the backend's public uploads folder.
const publicImageBaseUrl = `${config.apiBaseUrl}/public`;
// Reply, or edit the deferred reply, always without pinging anybody.
async function respond(interaction, payload) {
const body = { allowedMentions: { parse: [] }, ...payload };
if (interaction.deferred || interaction.replied) return interaction.editReply(body);
return interaction.reply({ ...body, flags: MessageFlags.Ephemeral });
}
async function explainMissingCampaign(interaction, guildId) {
await respond(interaction, {
content: safeField([
'This Discord server is not linked to a Dragonroll campaign yet.',
`A server administrator can connect Dragonroll with \`/dragonroll connect\`, then choose a campaign with \`/dragonroll link\`. Server ID: \`${guildId}\`.`
].join('\n'), 1800)
});
}
async function explainNotConnected(interaction, guildId) {
await respond(interaction, {
content: safeField([
'No Dragonroll account is connected to this Discord server yet.',
`A server administrator can run \`/dragonroll connect\` to sign in. Server ID: \`${guildId}\`.`
].join('\n'), 1800)
});
}
// The /dragonroll connect interactions waiting for somebody to authorize on Dragonroll.
// Their tokens stay usable for 15 minutes, longer than the authorization link lasts.
const pendingLinkRequests = new Map();
let linkNotificationTimer = null;
function linkRequestKey(guildId, discordUserId) {
return `${guildId}:${discordUserId}`;
}
function rememberLinkRequest(interaction) {
for (const [key, pending] of pendingLinkRequests) {
if (Date.now() - pending.requestedAt > LINK_REQUEST_TTL_MS) pendingLinkRequests.delete(key);
}
pendingLinkRequests.set(linkRequestKey(interaction.guildId, interaction.user.id), {
interaction,
requestedAt: Date.now()
});
if (!linkNotificationTimer) {
linkNotificationTimer = setInterval(() => {
deliverLinkNotifications().catch((error) => {
console.error('Could not confirm a Dragonroll authorization:', error.message);
});
}, LINK_NOTIFICATION_POLL_MS);
linkNotificationTimer.unref();
}
}
async function confirmLinkRequest(interaction, notification) {
const account = notification.dragonrollUserName ? ` \`${safeField(notification.dragonrollUserName, 40)}\`` : '';
await interaction.followUp({
content: safeField([
`Your Dragonroll account${account} is now connected to **${safeField(notification.guildName, 100)}**.`,
'Run `/dragonroll link` to choose which campaign this server can read.'
].join('\n'), 1800),
flags: MessageFlags.Ephemeral,
allowedMentions: { parse: [] }
});
}
async function deliverLinkNotifications() {
if (!config.discordBotSecret || !pendingLinkRequests.size) return;
const notifications = await dragonroll.claimLinkNotifications();
for (const notification of notifications) {
const key = linkRequestKey(notification.guildId, notification.discordUserId);
const pending = pendingLinkRequests.get(key);
pendingLinkRequests.delete(key);
// Without the interaction that asked for this authorization there is nothing to
// answer: the bot was restarted, and Dragonroll's own web page already told the
// person what to do next.
if (!pending) continue;
try {
await confirmLinkRequest(pending.interaction, notification);
} catch (error) {
console.error(`Could not confirm the Dragonroll authorization for Discord user ${notification.discordUserId}:`, error.message);
}
}
}
// Commands live on every server the bot joins: guild-scoped registration is
// instant, unlike the global registration done by deploy-commands.
async function registerCommandsIn(guildId) {
try {
await rest.put(Routes.applicationGuildCommands(config.discordClientId, guildId), {
body: commands.map((command) => command.toJSON())
});
} catch (error) {
console.error(`Could not register commands in Discord server ${guildId}:`, error.message);
}
}
async function showStatus(interaction, guildId) {
const embed = new EmbedBuilder()
.setTitle('Dragonroll link')
.setColor(0x8c6bb1)
.addFields({ name: 'This server', value: `${interaction.guild?.name || 'Unknown'} · \`${guildId}\`` });
let status;
try {
status = await dragonroll.getStatus(guildId);
} catch (error) {
console.error('Could not read the Dragonroll connection for this server:', error.message);
embed.addFields({ name: 'Dragonroll account', value: 'Dragonroll could not be reached right now.' });
await respond(interaction, { embeds: [embed] });
return;
}
embed.addFields(
{ name: 'Dragonroll account', value: status.connected ? 'Connected' : 'Not connected.' },
{ name: 'Campaign', value: status.campaign
? `${status.campaign.name} · \`${status.campaign._id ?? status.campaign.id}\``
: 'Not linked yet.' }
);
if (!status.connected) {
embed.setDescription('A server administrator can run /dragonroll connect to connect a Dragonroll account.');
} else if (!status.campaign) {
embed.setDescription('A server administrator can run /dragonroll link to choose a campaign.');
}
await respond(interaction, { embeds: [embed] });
}
client.once(Events.ClientReady, (readyClient) => {
console.log(`Dragonroll character bot is online as ${readyClient.user.tag}, in ${readyClient.guilds.cache.size} servers.`);
// Guild commands registered when the bot joined shadow global ones and
// keep their old definition forever, so refresh them on every start to
// propagate command changes (new options, autocomplete) to all servers.
for (const guild of readyClient.guilds.cache.values()) registerCommandsIn(guild.id);
});
client.on(Events.GuildCreate, (guild) => {
console.log(`Added to Discord server ${guild.id} (${guild.name}).`);
registerCommandsIn(guild.id);
});
client.on(Events.InteractionCreate, (interaction) => {
// One broken command should not take the bot down for every other server.
handleInteraction(interaction).catch((error) => {
console.error(`Could not answer ${interaction.commandName}:`, error.message);
});
});
async function respondCampaignChoices(interaction, guildId) {
if (!interaction.memberPermissions?.has(PermissionFlagsBits.Administrator)) {
await interaction.respond([]);
return;
}
try {
const query = interaction.options.getFocused().toLocaleLowerCase();
const campaigns = await dragonroll.listCampaigns(guildId);
const choices = campaigns
.filter((campaign) => !campaign.discordGuildId || String(campaign.discordGuildId) === String(guildId))
.filter((campaign) => String(campaign.name || '').toLocaleLowerCase().includes(query))
.slice(0, 25)
.map((campaign) => ({
name: safeField(campaign.name, 100),
value: String(campaign._id ?? campaign.id)
}))
.filter((choice) => choice.value && choice.value !== 'undefined');
await interaction.respond(choices);
} catch (error) {
if (error.status !== 401 && error.code !== 'discord.errors.not-connected') {
console.error('Could not list campaigns for Discord configuration:', error.message);
}
await interaction.respond([]);
}
}
// Character names for /character. Anyone who may read the campaign may use
// the suggestions; when nothing is linked we answer with an empty list, as
// autocomplete replies cannot carry an error message.
async function respondActorChoices(interaction, guildId) {
try {
const query = interaction.options.getFocused().trim().toLocaleLowerCase();
const { actors } = await dragonroll.listActors(guildId);
const seen = new Set();
const choices = actors
.filter((actor) => String(actor.name || '').trim() && actor.name.length <= 100)
.filter((actor) => actor.name.toLocaleLowerCase().includes(query))
.map((actor) => ({
name: safeField(actor.name, 100),
value: actor.name
}))
.filter((choice) => !seen.has(choice.value) && seen.add(choice.value))
.slice(0, 25);
await interaction.respond(choices);
} catch (error) {
if (!(error instanceof DragonrollNotConnectedError)
&& !(error instanceof CampaignNotLinkedError)
&& error.status !== 401
&& error.code !== 'discord.errors.not-connected') {
console.error('Could not list characters for Discord autocomplete:', error.message);
}
await interaction.respond([]);
}
}
async function handleInteraction(interaction) {
if (interaction.isAutocomplete()) {
const guildId = interaction.guildId;
if (!guildId) {
await interaction.respond([]);
return;
}
if (interaction.commandName === 'character') {
await respondActorChoices(interaction, guildId);
return;
}
if (interaction.commandName === 'dragonroll' && interaction.options.getSubcommand() === 'link') {
await respondCampaignChoices(interaction, guildId);
return;
}
return;
}
if (!interaction.isChatInputCommand()) return;
if (!['characters', 'character', 'dragonroll'].includes(interaction.commandName)) return;
const guildId = interaction.guildId;
if (!guildId) {
await respond(interaction, { content: 'These commands only work inside a Discord server.' });
return;
}
if (interaction.commandName === 'dragonroll') {
const subcommand = interaction.options.getSubcommand();
if (['connect', 'link', 'unlink'].includes(subcommand)) {
if (!interaction.memberPermissions?.has(PermissionFlagsBits.Administrator)) {
await respond(interaction, { content: 'Only Discord server administrators can connect Dragonroll or change this campaign link.' });
return;
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
try {
if (subcommand === 'connect') {
const request = await dragonroll.startAuthorization(
guildId,
interaction.guild?.name || 'Discord server',
interaction.user.id,
interaction.user.username
);
const authorizationUrl = `${config.frontendBaseUrl}/discord/authorize#code=${encodeURIComponent(request.code)}`;
const button = new ButtonBuilder()
.setLabel('Sign in to Dragonroll')
.setStyle(ButtonStyle.Link)
.setURL(authorizationUrl);
await respond(interaction, {
content: 'Open Dragonroll to sign in and authorize this server. The link expires in 10 minutes.',
components: [new ActionRowBuilder().addComponents(button)]
});
rememberLinkRequest(interaction);
return;
} else if (subcommand === 'link') {
const campaignId = interaction.options.getString('campaign', true);
const campaign = await dragonroll.linkCampaign(guildId, campaignId);
await respond(interaction, {
content: `This server is now linked to **${safeField(campaign.name, 180)}**.`,
allowedMentions: { parse: [] }
});
} else {
try {
const campaign = await dragonroll.unlinkCampaign(guildId);
await respond(interaction, {
content: `Removed this server’s link to **${safeField(campaign.name, 180)}**.`,
allowedMentions: { parse: [] }
});
} catch (error) {
if (error instanceof CampaignNotLinkedError) {
await respond(interaction, { content: 'This server does not have a linked campaign.' });
return;
}
throw error;
}
}
} catch (error) {
console.error(`Could not ${subcommand} the campaign for Discord server ${guildId}:`, error.message);
let message = `I could not ${subcommand} this campaign link. Please try again.`;
if (error instanceof DragonrollNotConnectedError || error.code === 'discord.errors.not-connected') {
message = 'Connect a Dragonroll account first with /dragonroll connect.';
} else if (error.status === 401 || error.message.includes('DRAGONROLL_DISCORD_BOT_SECRET')) {
message = 'The bot API secret is missing or does not match the backend. Contact the bot operator.';
} else if (error.code === 'campaigns.errors.discord-guild-in-use' || error.code === 'discord.errors.campaign-already-linked') {
message = 'That campaign is already linked to another Discord server.';
}
await respond(interaction, { content: message });
}
return;
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
await showStatus(interaction, guildId);
return;
}
const showCharacterPublicly = interaction.commandName === 'character'
&& interaction.options.getBoolean('public');
await interaction.deferReply(showCharacterPublicly ? {} : { flags: MessageFlags.Ephemeral });
try {
const { campaign, actors } = await dragonroll.listActors(guildId);
if (interaction.commandName === 'characters') {
const type = interaction.options.getString('type') || 'all';
const filtered = type === 'all' ? actors : actors.filter((actor) => actor.type === type);
if (!filtered.length) {
await interaction.editReply({
content: type === 'all'
? `There are no characters in **${campaign.name}** yet.`
: `There are no ${type === 'npc' ? 'NPCs' : `${type}s`} in **${campaign.name}**.`,
allowedMentions: { parse: [] }
});
return;
}
const shown = filtered.slice(0, 40);
const lines = shown.map((actor) => {
const details = [actor.species, actor.className, actor.level ? `Lv. ${actor.level}` : null]
.filter(Boolean)
.join(' · ');
return `• **${actor.name}**${details ? ` — ${details}` : ''}`;
});
const embed = new EmbedBuilder()
.setTitle(`Characters of ${campaign.name}`)
.setColor(0x8c6bb1)
.setDescription(safeField(lines.join('\n'), 4000))
.setFooter({ text: filtered.length > shown.length
? `Showing ${shown.length} of ${filtered.length}; use /character to look up a specific sheet.`
: `${filtered.length} ${filtered.length === 1 ? 'entry' : 'entries'} · Use /character to inspect a sheet.` });
await interaction.editReply({ embeds: [embed], allowedMentions: { parse: [] } });
return;
}
const name = interaction.options.getString('name', true);
const result = findActor(actors, name);
if (result.actor) {
await interaction.editReply({ embeds: [actorEmbed(result.actor, campaign, publicImageBaseUrl)], allowedMentions: { parse: [] } });
} else if (result.matches?.length > 1) {
await interaction.editReply({
content: safeField(`Several characters match **${name}**: ${result.matches.slice(0, 15).map((actor) => actor.name).join(', ')}. Try a more specific name.`, 1800),
allowedMentions: { parse: [] }
});
} else {
await interaction.editReply({
content: `I couldn't find a character named **${name}**. Try \`/characters\` to see the campaign roster.`,
allowedMentions: { parse: [] }
});
}
} catch (error) {
if (error instanceof DragonrollNotConnectedError) {
await explainNotConnected(interaction, guildId);
return;
}
if (error instanceof CampaignNotLinkedError) {
await explainMissingCampaign(interaction, guildId);
return;
}
console.error('Character lookup failed:', error.message);
await interaction.editReply({
content: 'I could not reach the Dragonroll campaign right now. Please try again in a moment.',
allowedMentions: { parse: [] }
});
}
}
await client.login(config.discordToken);
}
main().catch((error) => {
console.error('Could not start Dragonroll Discord bot:', error.message);
process.exitCode = 1;
});