Files
dragonroll/discord-bot/src/index.js
Aran Roig 1402045001
All checks were successful
Build and Deploy Nuxt / build (push) Successful in 1m51s
Foundry and discord bot
2026-10-11 22:26:29 +02:00

497 lines
23 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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;
});