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,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;
});