Fix issue #72: Link actor with a discord user
All checks were successful
Test / test (push) Successful in 2s
All checks were successful
Test / test (push) Successful in 2s
This commit is contained in:
@@ -51,7 +51,24 @@ const commands = [
|
||||
.setDescription('Show the campaign linked to this server.'))
|
||||
.addSubcommand((subcommand) => subcommand
|
||||
.setName('refresh')
|
||||
.setDescription('Refresh this server’s Dragonroll connection status.')))
|
||||
.setDescription('Refresh this server’s Dragonroll connection status.'))
|
||||
.addSubcommand((subcommand) => subcommand
|
||||
.setName('assign')
|
||||
.setDescription('Link one character of the campaign to your Discord account.')
|
||||
.addStringOption((option) => option
|
||||
.setName('character')
|
||||
.setDescription('Character to play (pick it from the campaign roster).')
|
||||
.setRequired(true)
|
||||
.setMaxLength(100)
|
||||
.setAutocomplete(true)))
|
||||
.addSubcommand((subcommand) => subcommand
|
||||
.setName('unassign')
|
||||
.setDescription('Remove the link between a character and a Discord player.')
|
||||
.addStringOption((option) => option
|
||||
.setName('character')
|
||||
.setDescription('Character to free (yours by default, anyone’s as a server administrator).')
|
||||
.setMaxLength(100)
|
||||
.setAutocomplete(true))))
|
||||
];
|
||||
|
||||
module.exports = commands;
|
||||
|
||||
@@ -123,7 +123,32 @@ function createDragonrollApi(config) {
|
||||
return { campaign, actors: payload.actors };
|
||||
}
|
||||
|
||||
return { startAuthorization, claimLinkNotifications, getStatus, getCampaign, listCampaigns, linkCampaign, unlinkCampaign, listActors };
|
||||
// Linking players to characters (Syndria98/dragonroll#72). `admin` says
|
||||
// whether the Discord side already checked the person is a server
|
||||
// administrator, who may move a character somebody else holds.
|
||||
async function assignActor(guildId, { actorId, discordUserId, admin = false }) {
|
||||
const payload = await request(`/discord/bot/guild/${encodeURIComponent(guildId)}/actors/assign`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ actorId, discordUserId: String(discordUserId), admin })
|
||||
});
|
||||
if (!payload.actor) throw new Error('Dragonroll returned an invalid character link.');
|
||||
return { actor: payload.actor, previous: payload.previous ?? null };
|
||||
}
|
||||
|
||||
async function unassignActor(guildId, { actorId, discordUserId, admin = false }) {
|
||||
const payload = await request(`/discord/bot/guild/${encodeURIComponent(guildId)}/actors/unassign`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
discordUserId: String(discordUserId),
|
||||
...(actorId ? { actorId } : {}),
|
||||
admin
|
||||
})
|
||||
});
|
||||
if (!payload.actor) throw new Error('Dragonroll returned an invalid character link.');
|
||||
return { actor: payload.actor, wasYours: payload.wasYours === true };
|
||||
}
|
||||
|
||||
return { startAuthorization, claimLinkNotifications, getStatus, getCampaign, listCampaigns, linkCampaign, unlinkCampaign, listActors, assignActor, unassignActor };
|
||||
}
|
||||
|
||||
module.exports = { createDragonrollApi, CampaignNotLinkedError, DragonrollNotConnectedError };
|
||||
|
||||
@@ -234,6 +234,20 @@ async function main() {
|
||||
: 'Not linked yet.' }
|
||||
);
|
||||
|
||||
// The campaign's character linked to this Discord account (#72), when there is one.
|
||||
if (status.campaign) {
|
||||
try {
|
||||
const { actors } = await dragonroll.listActors(guildId);
|
||||
const yours = actors.find((actor) => String(actor.discordUserId ?? '') === interaction.user.id);
|
||||
embed.addFields({
|
||||
name: 'Your character',
|
||||
value: yours ? safeField(yours.name, 100) : 'None. Run /dragonroll assign to link one to your Discord account.'
|
||||
});
|
||||
} catch {
|
||||
// The roster is a bonus of this card, which stays useful without it.
|
||||
}
|
||||
}
|
||||
|
||||
if (!status.connected) {
|
||||
embed.setDescription('A server administrator can run /dragonroll connect to connect a Dragonroll account.');
|
||||
} else if (!status.campaign) {
|
||||
@@ -243,6 +257,78 @@ async function main() {
|
||||
await respond(interaction, { embeds: [embed] });
|
||||
}
|
||||
|
||||
// /dragonroll assign and unassign (Syndria98/dragonroll#72): each player of the
|
||||
// server holds one character of the linked campaign. Anyone claims a free
|
||||
// character for themselves; server administrators also move and free the ones
|
||||
// somebody else holds.
|
||||
async function handleActorAssignment(interaction, guildId, subcommand) {
|
||||
const isAdmin = interaction.memberPermissions?.has(PermissionFlagsBits.Administrator) === true;
|
||||
const name = interaction.options.getString('character');
|
||||
const { actors } = await dragonroll.listActors(guildId);
|
||||
|
||||
// Unassign without a character gives up the one linked to you.
|
||||
if (subcommand === 'unassign' && !name) {
|
||||
const mine = actors.find((actor) => String(actor.discordUserId ?? '') === interaction.user.id);
|
||||
if (!mine) {
|
||||
await respond(interaction, { content: 'You do not have a character linked to your Discord account here. Run `/dragonroll assign` to claim one.' });
|
||||
return;
|
||||
}
|
||||
await dragonroll.unassignActor(guildId, { discordUserId: interaction.user.id });
|
||||
await respond(interaction, { content: `You are no longer linked to **${safeField(mine.name, 100)}**.` });
|
||||
return;
|
||||
}
|
||||
|
||||
const result = findActor(actors, name);
|
||||
if (!result.actor) {
|
||||
await respond(interaction, {
|
||||
content: result.matches?.length
|
||||
? safeField(`Several characters match **${name}**: ${result.matches.slice(0, 15).map((actor) => actor.name).join(', ')}. Try a more specific name.`, 1800)
|
||||
: safeField(`I couldn't find a character named **${name}**. Try \`/characters\` to see the campaign roster.`, 1800)
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const actor = result.actor;
|
||||
const holder = String(actor.discordUserId ?? '');
|
||||
|
||||
if (subcommand === 'assign') {
|
||||
if (holder === interaction.user.id) {
|
||||
await respond(interaction, { content: `You are already linked to **${safeField(actor.name, 100)}**.` });
|
||||
return;
|
||||
}
|
||||
if (holder && !isAdmin) {
|
||||
await respond(interaction, { content: `**${safeField(actor.name, 100)}** is already linked to <@${holder}>. A server administrator can give it away and take it with the same command.` });
|
||||
return;
|
||||
}
|
||||
const { previous } = await dragonroll.assignActor(guildId, {
|
||||
actorId: String(actor._id),
|
||||
discordUserId: interaction.user.id,
|
||||
admin: isAdmin
|
||||
});
|
||||
const lines = [`You are now linked to **${safeField(actor.name, 100)}**.`];
|
||||
if (holder) lines.push(`That character was linked to <@${holder}>; the link is removed.`);
|
||||
if (previous) lines.push(`Your previous character, **${safeField(previous.name, 100)}**, is free again.`);
|
||||
await respond(interaction, { content: safeField(lines.join('\n'), 1800) });
|
||||
return;
|
||||
}
|
||||
|
||||
// Unassign with a character named: your own, or anybody's as an administrator.
|
||||
if (!holder) {
|
||||
await respond(interaction, { content: `**${safeField(actor.name, 100)}** does not have a linked Discord player.` });
|
||||
return;
|
||||
}
|
||||
if (holder !== interaction.user.id && !isAdmin) {
|
||||
await respond(interaction, { content: `**${safeField(actor.name, 100)}** is linked to <@${holder}>. Only a server administrator can unlink it.` });
|
||||
return;
|
||||
}
|
||||
await dragonroll.unassignActor(guildId, { actorId: String(actor._id), discordUserId: interaction.user.id, admin: isAdmin });
|
||||
await respond(interaction, {
|
||||
content: holder === interaction.user.id
|
||||
? `You are no longer linked to **${safeField(actor.name, 100)}**.`
|
||||
: `**${safeField(actor.name, 100)}** is no longer linked to <@${holder}>.`
|
||||
});
|
||||
}
|
||||
|
||||
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
|
||||
@@ -331,9 +417,16 @@ async function main() {
|
||||
await respondActorChoices(interaction, guildId);
|
||||
return;
|
||||
}
|
||||
if (interaction.commandName === 'dragonroll' && interaction.options.getSubcommand() === 'link') {
|
||||
await respondCampaignChoices(interaction, guildId);
|
||||
return;
|
||||
if (interaction.commandName === 'dragonroll') {
|
||||
const subcommand = interaction.options.getSubcommand();
|
||||
if (subcommand === 'link') {
|
||||
await respondCampaignChoices(interaction, guildId);
|
||||
return;
|
||||
}
|
||||
if (['assign', 'unassign'].includes(subcommand)) {
|
||||
await respondActorChoices(interaction, guildId);
|
||||
return;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -412,6 +505,34 @@ async function main() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Players link themselves to a character of the campaign (Syndria98/dragonroll#72).
|
||||
if (['assign', 'unassign'].includes(subcommand)) {
|
||||
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
|
||||
try {
|
||||
await handleActorAssignment(interaction, guildId, subcommand);
|
||||
} catch (error) {
|
||||
if (error instanceof DragonrollNotConnectedError) {
|
||||
await explainNotConnected(interaction, guildId);
|
||||
return;
|
||||
}
|
||||
if (error instanceof CampaignNotLinkedError) {
|
||||
await explainMissingCampaign(interaction, guildId);
|
||||
return;
|
||||
}
|
||||
if (error.code === 'discord.errors.actor-held') {
|
||||
await respond(interaction, { content: 'That character is already linked to another player. A server administrator can give it away and take it with the same command.' });
|
||||
return;
|
||||
}
|
||||
if (error.status === 401 || error.message.includes('DRAGONROLL_DISCORD_BOT_SECRET')) {
|
||||
await respond(interaction, { content: 'The bot API secret is missing or does not match the backend. Contact the bot operator.' });
|
||||
return;
|
||||
}
|
||||
console.error(`Could not ${subcommand} a character link in Discord server ${guildId}:`, error.message);
|
||||
await respond(interaction, { content: 'I could not change that character link right now. Please try again.' });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
|
||||
await showStatus(interaction, guildId);
|
||||
return;
|
||||
@@ -442,7 +563,10 @@ async function main() {
|
||||
const details = [actor.species, actor.className, actor.level ? `Lv. ${actor.level}` : null]
|
||||
.filter(Boolean)
|
||||
.join(' · ');
|
||||
return `• **${actor.name}**${details ? ` — ${details}` : ''}`;
|
||||
// The player a character is linked to (#72); mentions never ping
|
||||
// here, the replies parse no mentions.
|
||||
const player = actor.discordUserId ? ` 🎮 <@${actor.discordUserId}>` : '';
|
||||
return `• **${actor.name}**${details ? ` — ${details}` : ''}${player}`;
|
||||
});
|
||||
const embed = new EmbedBuilder()
|
||||
.setTitle(`Characters of ${campaign.name}`)
|
||||
|
||||
Reference in New Issue
Block a user