Linked Roles
Give members server roles from data your bot has outside Discord, like matches won in your game or a GitHub account, through Discord's Linked Roles.
Discord's Linked Roles (opens in a new tab) let a server put a requirement on a role that only your bot can answer, like "100 matches won or more" in your game. A member who meets it can claim the role. @seedcord/plugin-linked-roles serves that whole flow from your bot.
A record is one thing that a server can set a requirement on, like matches won or merged pull requests. By hand, you'd register your records with Discord and serve a verification route and a callback route. You'd also log each member in with OAuth2 and send their values in the string format that Discord takes for each type. The plugin does all of that, and it checks the values you return against the records you declared.
pnpm add @seedcord/plugin-linked-rolesAttaching the plugin
import { class SeedcordSeedcord } from '@seedcord/gateway';
import {
class LinkedRoles<
TRecords extends LinkedRoleRecords,
TScopes extends OAuthScope = never,
TKeep extends boolean = false
>
LinkedRoles,
enum RecordTypeRecordType
} from '@seedcord/plugin-linked-roles';
import { enum GatewayIntentBitsGatewayIntentBits } from 'discord.js';
import { const players: {
byDiscordId(userId: string): Promise<
| {
name: string;
wins: number;
}
| undefined
>;
}
players } from './players';
const const Ranked: new (host: CoreBase) => LinkedRoles<
{
readonly matches_won: {
readonly type: RecordType.IntegerGreaterThanOrEqual;
readonly name: "Matches won";
readonly description: "or more matches won";
};
},
never,
false
>
Ranked = class LinkedRoles<
TRecords extends LinkedRoleRecords,
TScopes extends OAuthScope = never,
TKeep extends boolean = false
>
LinkedRoles.LinkedRoles<TRecords extends LinkedRoleRecords, TScopes extends OAuthScope = never, TKeep extends boolean = false>.with<{
readonly matches_won: {
readonly type: RecordType.IntegerGreaterThanOrEqual;
readonly name: "Matches won";
readonly description: "or more matches won";
};
}, never, false>(options: LinkedRolesOptions<{
readonly matches_won: {
readonly type: RecordType.IntegerGreaterThanOrEqual;
readonly name: "Matches won";
readonly description: "or more matches won";
};
}, never, false>): new (host: CoreBase) => LinkedRoles<{
readonly matches_won: {
readonly type: RecordType.IntegerGreaterThanOrEqual;
readonly name: "Matches won";
readonly description: "or more matches won";
};
}, never, false>
with({
LinkedRolesOptions<{ readonly matches_won: { readonly type: ApplicationRoleConnectionMetadataType.IntegerGreaterThanOrEqual; readonly name: "Matches won"; readonly description: "or more matches won"; }; }, never, false>.records: {
readonly matches_won: {
readonly type: RecordType.IntegerGreaterThanOrEqual;
readonly name: "Matches won";
readonly description: "or more matches won";
};
} & {} & {
readonly matches_won: TextProblems<{
readonly type: RecordType.IntegerGreaterThanOrEqual;
readonly name: "Matches won";
readonly description: "or more matches won";
}>;
}
records: {
matches_won: {
readonly type: RecordType.IntegerGreaterThanOrEqual;
readonly name: "Matches won";
readonly description: "or more matches won";
} & TextProblems<{
readonly type: RecordType.IntegerGreaterThanOrEqual;
readonly name: "Matches won";
readonly description: "or more matches won";
}>
matches_won: {
type: RecordType.IntegerGreaterThanOrEqualtype: enum RecordTypeRecordType.function (enum member) ApplicationRoleConnectionMetadataType.IntegerGreaterThanOrEqual = 2IntegerGreaterThanOrEqual,
name: "Matches won"name: 'Matches won',
description: "or more matches won"description: 'or more matches won'
}
},
LinkedRolesOptions<{ readonly matches_won: { readonly type: ApplicationRoleConnectionMetadataType.IntegerGreaterThanOrEqual; readonly name: "Matches won"; readonly description: "or more matches won"; }; }, never, false>.values(connecting: ConnectingUser<never>): Promisable<Refusal | RoleConnection<{
readonly matches_won: {
readonly type: RecordType.IntegerGreaterThanOrEqual;
readonly name: "Matches won";
readonly description: "or more matches won";
};
}>>
values: async ({ user: APIUseruser }) => {
const const player:
| {
name: string;
wins: number;
}
| undefined
player = await const players: {
byDiscordId(userId: string): Promise<
| {
name: string;
wins: number;
}
| undefined
>;
}
players.function byDiscordId(userId: string): Promise<
| {
name: string;
wins: number;
}
| undefined
>
byDiscordId(user: APIUseruser.APIUser.id: stringid);
if (!const player:
| {
name: string;
wins: number;
}
| undefined
player) {
return { Refusal.refuse: stringrefuse: 'Link Discord in the game first.' };
}
return {
RoleConnection<TRecords extends LinkedRoleRecords>.platformUsername?: string | undefinedplatformUsername: const player: {
name: string;
wins: number;
}
player.name: stringname,
RoleConnection<{ readonly matches_won: { readonly type: ApplicationRoleConnectionMetadataType.IntegerGreaterThanOrEqual; readonly name: "Matches won"; readonly description: "or more matches won"; }; }>.metadata: {
matches_won: number;
}
metadata: { matches_won: numbermatches_won: const player: {
name: string;
wins: number;
}
player.wins: numberwins }
};
}
});
export const const seedcord: Seedcord &
Record<
"linkedRoles",
LinkedRoles<
{
readonly matches_won: {
readonly type: RecordType.IntegerGreaterThanOrEqual;
readonly name: "Matches won";
readonly description: "or more matches won";
};
},
never,
false
>
>
seedcord = new new Seedcord(config: GatewayConfig): SeedcordSeedcord({
// the address people reach your bot at
ServerHostConfig.server?: ServerConfigserver: { BaseServerConfig.url?: string | URLurl: 'https://bot.example.com' },
GatewayConfig.bot: GatewayBotConfigbot: {
GatewayBotConfig.clientOptions: ClientOptionsclientOptions: { ClientOptions.intents: BitFieldResolvable<
| "Guilds"
| "GuildMembers"
| "GuildModeration"
| "GuildBans"
| "GuildExpressions"
| "GuildEmojisAndStickers"
| "GuildIntegrations"
| "GuildWebhooks"
| "GuildInvites"
| "GuildVoiceStates"
| "GuildPresences"
| "GuildMessages"
| "GuildMessageReactions"
| "GuildMessageTyping"
| "DirectMessages"
| "DirectMessageReactions"
| "DirectMessageTyping"
| "MessageContent"
| "GuildScheduledEvents"
| "AutoModerationConfiguration"
| "AutoModerationExecution"
| "GuildMessagePolls"
| "DirectMessagePolls",
number
>
intents: [enum GatewayIntentBitsGatewayIntentBits.function (enum member) GatewayIntentBits.Guilds = 1Guilds] },
GatewayBotConfig.interactions: InteractionsConfig<UnhandledHandler>interactions: { path: stringpath: './handlers' },
BotConfig.commands: CommandsConfigcommands: { path: stringpath: './commands' },
GatewayBotConfig.events: EventsConfigevents: { path: nullpath: null }
},
Config.subscribers: SubscribersConfigsubscribers: { path: nullpath: null }
}).PluginHost<"gateway", "server">.attach<"linkedRoles", new (host: CoreBase) => LinkedRoles<{
readonly matches_won: {
readonly type: RecordType.IntegerGreaterThanOrEqual;
readonly name: "Matches won";
readonly description: "or more matches won";
};
}, never, false>>(this: Seedcord, key: "linkedRoles", Plugin: new (host: CoreBase) => LinkedRoles<{
readonly matches_won: {
readonly type: RecordType.IntegerGreaterThanOrEqual;
readonly name: "Matches won";
readonly description: "or more matches won";
};
}, never, false>): Seedcord & Record<...>
attach('linkedRoles', const Ranked: new (host: CoreBase) => LinkedRoles<
{
readonly matches_won: {
readonly type: RecordType.IntegerGreaterThanOrEqual;
readonly name: "Matches won";
readonly description: "or more matches won";
};
},
never,
false
>
Ranked);
export default const seedcord: Seedcord &
Record<
"linkedRoles",
LinkedRoles<
{
readonly matches_won: {
readonly type: RecordType.IntegerGreaterThanOrEqual;
readonly name: "Matches won";
readonly description: "or more matches won";
};
},
never,
false
>
>
seedcord;In records, you list what a server can set a requirement on. This bot has one record, matches_won. The plugin runs values for each person who connects, and you return their value for every record. players is your own file, and it looks up your game's player by Discord id. A member who hasn't linked Discord in the game doesn't have a player, so values refuses them with a message.
LinkedRoles.with() returns a plugin class with your options in it, and Ranked is that class. You attach it like any other plugin. That's also how matches_won in metadata gets typed as a number from the record's type. The plugin authoring guide shows how to write a with() for a plugin of your own.
LinkedRoles works on gateway, on http, and on Cloudflare Workers. It needs these, and a deployed bot doesn't start without them:
| it needs | where it comes from | without it |
|---|---|---|
| your bot's public address | server.url in the config, as in the sample. You can leave it out under seedcord dev, which uses your local or tunnel address | CoreServerUrlUnset |
| your application's client secret | DISCORD_CLIENT_SECRET in the environment | ConfigMissingEnv |
Copy the client secret from your application's OAuth2 page in the Developer Portal (opens in a new tab).
Warning
Discord only redirects to an address on your application's list (opens in a new tab), and a bot can't add one for you. On the same OAuth2 page, add your callback address under Redirects. It's server.url followed by linked-roles/callback. For the sample, that's https://bot.example.com/linked-roles/callback.
If the address isn't on the list, the plugin logs a warning at startup with the exact address to paste.
Nobody can connect until this address is under Redirects on your OAuth2 page
https://bot.example.com/linked-roles/callbackWhen your bot starts, the plugin also registers your records with Discord and sets your application's Linked Roles Verification URL (opens in a new tab) to server.url followed by linked-roles/verify. A later start skips those calls unless your records or server.url changed, or the last time it made them was more than a day ago.
Warning
Use a separate application for development. Under seedcord dev, the plugin sets the verification URL to your local or tunnel address. On your production application, every member's link would then open your development bot. The development application needs its own client secret, and its own callback address under Redirects.
Cloudflare Workers only
Set a kv driver on a worker, like D1 through unstorage. The plugin saves in kv that it registered your records. On the default driver every isolate starts with an empty kv, so each one registers them again.
Declaring records
You give each record a type from RecordType, a name, and a description. The type sets how Discord compares a member's value to the role's requirement. It also sets what you return for that record from values.
values returns | for a RecordType of | the server sets |
|---|---|---|
| a whole number | IntegerLessThanOrEqual, IntegerGreaterThanOrEqual, IntegerEqual, IntegerNotEqual | a number to compare it to |
a Date | DatetimeLessThanOrEqual, DatetimeGreaterThanOrEqual | a number of days before today |
true or false | BooleanEqual, BooleanNotEqual | nothing, the requirement is the record itself |
RecordType is ApplicationRoleConnectionMetadataType from discord-api-types under a shorter name. Discord's docs explain what each type compares (opens in a new tab).
Discord takes five records at most (opens in a new tab). A key can only use a-z, 0-9, and _, and takes at most 50 characters. A name takes at most 100 characters and a description at most 200. If a record breaks one of these, your bot fails to compile, and the error message gives the limit. For a key or text that isn't a literal, like one you build from a variable, the bot stops at startup with PluginOptionsRejected.
To show a record in other languages, add nameLocalizations and descriptionLocalizations, keyed by Discord locale code. A translation takes the same limit as the text it translates, and the plugin checks it at startup. LinkedRoleRecords is the type of the whole records object.
import { RecordType } from '@seedcord/plugin-linked-roles';
import type { LinkedRoleRecords } from '@seedcord/plugin-linked-roles';
export const records = {
matches_won: {
type: RecordType.IntegerGreaterThanOrEqual,
name: 'Matches won',
description: 'or more matches won',
nameLocalizations: {
fr: 'Matchs gagnés',
de: 'Gewonnene Spiele'
}
}
} satisfies LinkedRoleRecords;How a member gets the role
- A server admin opens Server Settings, then Roles, picks a role, and under Links clicks Add requirement. They pick your bot and set a value for one of your records. Discord's tutorial (opens in a new tab) walks through it.
- A member clicks the server name, then Linked Roles, and clicks the role.
- Discord sends their browser to your bot's
linked-roles/verifyroute, which redirects them to Discord's consent screen. - After they approve, Discord sends them to
linked-roles/callback. The plugin runs yourvaluesfor them and writes what it returns to Discord. - Back in Discord, they finish claiming the role.
The callback only finishes a visit that the same browser started at the verify route, the same way the OAuth plugin's login does. A callback from any other browser gets the invalid result in the table below.
What values gets
values gets a ConnectingUser. It has the Discord user who is connecting, and asUser, which calls Discord's API with that person's own token. With 'connections' in scopes, asUser.connections() returns the accounts they linked on their Discord profile.
import {
class LinkedRoles<
TRecords extends LinkedRoleRecords,
TScopes extends OAuthScope = never,
TKeep extends boolean = false
>
LinkedRoles,
enum RecordTypeRecordType
} from '@seedcord/plugin-linked-roles';
import { enum ConnectionServiceConnectionService } from 'discord.js';
import { function mergedPullRequests(login: string): Promise<number>mergedPullRequests } from './github';
export const const Contributors: new (host: CoreBase) => LinkedRoles<
{
readonly merged_prs: {
readonly type: RecordType.IntegerGreaterThanOrEqual;
readonly name: "Merged pull requests";
readonly description: "or more merged pull requests";
};
},
"connections",
false
>
Contributors = class LinkedRoles<
TRecords extends LinkedRoleRecords,
TScopes extends OAuthScope = never,
TKeep extends boolean = false
>
LinkedRoles.LinkedRoles<TRecords extends LinkedRoleRecords, TScopes extends OAuthScope = never, TKeep extends boolean = false>.with<{
readonly merged_prs: {
readonly type: RecordType.IntegerGreaterThanOrEqual;
readonly name: "Merged pull requests";
readonly description: "or more merged pull requests";
};
}, "connections", false>(options: LinkedRolesOptions<{
readonly merged_prs: {
readonly type: RecordType.IntegerGreaterThanOrEqual;
readonly name: "Merged pull requests";
readonly description: "or more merged pull requests";
};
}, "connections", false>): new (host: CoreBase) => LinkedRoles<{
readonly merged_prs: {
readonly type: RecordType.IntegerGreaterThanOrEqual;
readonly name: "Merged pull requests";
readonly description: "or more merged pull requests";
};
}, "connections", false>
with({
LinkedRolesOptions<{ readonly merged_prs: { readonly type: ApplicationRoleConnectionMetadataType.IntegerGreaterThanOrEqual; readonly name: "Merged pull requests"; readonly description: "or more merged pull requests"; }; }, "connections", false>.records: {
readonly merged_prs: {
readonly type: RecordType.IntegerGreaterThanOrEqual;
readonly name: "Merged pull requests";
readonly description: "or more merged pull requests";
};
} & {} & {
readonly merged_prs: TextProblems<{
readonly type: RecordType.IntegerGreaterThanOrEqual;
readonly name: "Merged pull requests";
readonly description: "or more merged pull requests";
}>;
}
records: {
merged_prs: {
readonly type: RecordType.IntegerGreaterThanOrEqual;
readonly name: "Merged pull requests";
readonly description: "or more merged pull requests";
} & TextProblems<{
readonly type: RecordType.IntegerGreaterThanOrEqual;
readonly name: "Merged pull requests";
readonly description: "or more merged pull requests";
}>
merged_prs: {
type: RecordType.IntegerGreaterThanOrEqualtype: enum RecordTypeRecordType.function (enum member) ApplicationRoleConnectionMetadataType.IntegerGreaterThanOrEqual = 2IntegerGreaterThanOrEqual,
name: "Merged pull requests"name: 'Merged pull requests',
description: "or more merged pull requests"description: 'or more merged pull requests'
}
},
LinkedRolesOptions<{ readonly merged_prs: { readonly type: ApplicationRoleConnectionMetadataType.IntegerGreaterThanOrEqual; readonly name: "Merged pull requests"; readonly description: "or more merged pull requests"; }; }, "connections", false>.scopes?: readonly "connections"[] | undefinedscopes: ['connections'],
LinkedRolesOptions<{ readonly merged_prs: { readonly type: ApplicationRoleConnectionMetadataType.IntegerGreaterThanOrEqual; readonly name: "Merged pull requests"; readonly description: "or more merged pull requests"; }; }, "connections", false>.values(connecting: ConnectingUser<"connections">): Promisable<Refusal | RoleConnection<{
readonly merged_prs: {
readonly type: RecordType.IntegerGreaterThanOrEqual;
readonly name: "Merged pull requests";
readonly description: "or more merged pull requests";
};
}>>
values: async ({ asUser: UserCalls<"connections" | "role_connections.write", never>asUser }) => {
const const accounts: RESTGetAPICurrentUserConnectionsResultaccounts = await asUser: UserCalls<"connections" | "role_connections.write", never>asUser.UserCalls<"connections" | "role_connections.write", never>.connections(): ScopedResult<
"connections" | "role_connections.write",
"connections",
RESTGetAPICurrentUserConnectionsResult
>
connections();
const const github: APIConnection | undefinedgithub = const accounts: RESTGetAPICurrentUserConnectionsResultaccounts.Array<APIConnection>.find(predicate: (value: APIConnection, index: number, obj: APIConnection[]) => unknown, thisArg?: any): APIConnection | undefined (+1 overload)find(
(account: APIConnectionaccount) =>
account: APIConnectionaccount.APIConnection.type: ConnectionServicetype === enum ConnectionServiceConnectionService.function (enum member) ConnectionService.GitHub = "github"GitHub &&
account: APIConnectionaccount.APIConnection.verified: booleanverified
);
if (!const github: APIConnection | undefinedgithub) {
return { Refusal.refuse: stringrefuse: 'Connect GitHub on Discord first.' };
}
return {
RoleConnection<TRecords extends LinkedRoleRecords>.platformUsername?: string | undefinedplatformUsername: const github: APIConnectiongithub.APIConnection.name: stringname,
RoleConnection<{ readonly merged_prs: { readonly type: ApplicationRoleConnectionMetadataType.IntegerGreaterThanOrEqual; readonly name: "Merged pull requests"; readonly description: "or more merged pull requests"; }; }>.metadata: {
merged_prs: number;
}
metadata: {
merged_prs: numbermerged_prs: await function mergedPullRequests(login: string): Promise<number>mergedPullRequests(const github: APIConnectiongithub.APIConnection.name: stringname)
}
};
}
});asUser.connections() compiles because the sample lists 'connections' in scopes. The consent screen asks for identify and role_connections.write on every visit, plus the scopes you list. asUser has the same calls as the OAuth plugin's as(), and Scopes and calls lists every one.
From values, you return one of two things:
- The member's values, a
RoleConnection. Inmetadata, you set a value for every record, of the kind itstypetakes.platformNameandplatformUsernameare optional, and Discord shows them with the connection.platformNametakes at most 50 characters andplatformUsernameat most 100. - A refusal, a
Refusal. If you return{ refuse: 'your message' }, the plugin doesn't write anything to Discord, and it shows the member your message.
The plugin converts the values to the strings Discord takes. If a value doesn't fit, like a number with a fraction for an integer record, the plugin throws PluginLinkedRolesValueRejected. The member then gets the failed result in the table below.
Warning
If values reads the bot that its class gets attached to, like another plugin on it, TypeScript reports that both are referenced in their own initializer. That section has two ways to fix it.
The page after connecting
Without onResult, the member gets a plain page that says what happened. To show your own page or send them somewhere else, return a Response from onResult.
export const WithOwnPage = LinkedRoles.with({
records: {
matches_won: {
type: RecordType.IntegerGreaterThanOrEqual,
name: 'Matches won',
description: 'or more matches won'
}
},
values: () => ({ metadata: { matches_won: 12 } }),
onResult: (result) =>
Response.redirect(
`https://example.com/linked?result=${result.kind}`
)
});onResult gets a LinkedRolesResult and then the callback's Request. It runs for every kind of result, and it has to return a Response for each:
result.kind | what happened | the plain page's status |
|---|---|---|
connected | the plugin wrote the member's values. result.user is who connected | 200 |
refused | your values returned a refusal. result.message is its text | 200, with your message |
denied | the member pressed Cancel, or Discord refused the request. result.error has Discord's reason | 400 |
invalid | the link expired, the page was reloaded, or this browser didn't start the visit | 400 |
failed | something threw, like your values or the write to Discord. The plugin logs result.error before it calls onResult | 500 |
The plugin only writes a member's values when they connect. Updating values covers writing them again after they change, and what Discord does with the role then.