Add exp_discord_sync to give linked players Discord roles

New controller plugin that maps clusterio roles to Discord roles and gives them to players linked through exp_discord_auth. The mapping is edited in a Discord Roles section on the role page, which needs the new exp_discord_sync.mapping.update permission. The guild's roles fill a dropdown, and typing a role ID still works when the bot can't list them.

Discord is reached with Node's fetch and WebSocket, no library. REST requests go one at a time and wait out 429 and exhausted rate limits. A minimal gateway connection with the Server Members intent gives roles on guild join. It identifies again instead of resuming, and every READY syncs all linked accounts, which covers startup and joins missed while disconnected. Without the intent the gateway is dropped and syncing carries on over REST.

Syncs run on link, unlink, clusterio role change, guild join, mapping change and connect. Only mapped Discord roles are ever added or removed.

exp_discord_auth may load after this plugin, so it is looked up and its hooks attached when the first sync runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bbassieandClaude Opus 5.5 committed 2026-11-23 16:25:53 +00:00
1 parent c1490c0709
commit 2c55cb796e
18 files changed
+1494

No files matched your search

@@ -0,0 +1,90 @@
import React, { useContext, useEffect, useState } from "react";
import { Alert, Button, Select, Typography } from "antd";
import { ControlContext, PluginExtensionProps, SectionHeader, notifyErrorHandler, useAccount } from "@clusterio/web_ui";
import { GuildRoleListRequest, RoleMappingUpdateRequest } from "../../messages.js";
import { useRoleMappings } from "..";
type GuildRole = { id: string, name: string, color: number };
function roleColor(color: number) {
return color ? `#${color.toString(16).padStart(6, "0")}` : undefined;
}
/** The Discord roles given to linked players holding this role. */
export default function RoleDiscordRoles(props: PluginExtensionProps<"RoleViewPageBeforePermissions">) {
const control = useContext(ControlContext);
const account = useAccount();
const [mappings, synced] = useRoleMappings();
const [guildRoles, setGuildRoles] = useState<GuildRole[]>([]);
const [guildError, setGuildError] = useState<string>();
const [selected, setSelected] = useState<string[]>();
const [applying, setApplying] = useState(false);
const canUpdate = account.hasPermission("exp_discord_sync.mapping.update");
const saved = (props.role ? mappings.get(props.role.id)?.discordRoleIds : undefined) ?? [];
const value = selected ?? saved;
const changed = selected !== undefined && selected.join() !== saved.join();
useEffect(() => {
control.send(new GuildRoleListRequest())
.then(roles => { setGuildRoles(roles); setGuildError(undefined); })
.catch(err => setGuildError(err.message));
}, []);
useEffect(() => setSelected(undefined), [props.role?.id, saved.join()]);
if (!props.role || !synced) {
return null;
}
async function apply() {
await control.send(new RoleMappingUpdateRequest(props.role!.id, value));
setSelected(undefined);
}
const options = guildRoles.map(role => ({
value: role.id,
label: <span style={{ color: roleColor(role.color) }}>{role.name}</span>,
search: role.name,
}));
return <>
<SectionHeader
title="Discord Roles"
extra={canUpdate ? <Button
type="primary"
disabled={!changed}
loading={applying}
onClick={() => {
setApplying(true);
apply()
.catch(notifyErrorHandler("Error updating Discord roles"))
.finally(() => setApplying(false));
}}
>Apply Discord roles</Button> : undefined}
/>
{guildError && <Alert
type="warning"
showIcon
message={`Could not list the Discord roles: ${guildError}`}
description={canUpdate ? "Role IDs can still be typed in." : undefined}
style={{ marginBottom: 8 }}
/>}
<Select
mode="tags"
style={{ width: "100%" }}
placeholder={canUpdate ? "Select Discord roles or type a role ID" : "None"}
disabled={!canUpdate}
value={value}
options={options}
optionFilterProp="search"
tokenSeparators={[",", " "]}
onChange={setSelected}
/>
<Typography.Paragraph type="secondary" style={{ marginTop: 8 }}>
Players linked to Discord get these roles while they hold this role.
</Typography.Paragraph>
</>;
}
+22
View File
@@ -0,0 +1,22 @@
import { useCallback, useSyncExternalStore } from "react";
import { WebPluginContext } from "@clusterio/web_ui";
import * as lib from "@clusterio/lib";
import * as messages from "../messages.js";
import RoleDiscordRoles from "./components/RoleDiscordRoles";
let mappings: lib.MapSubscriber<messages.RoleMappingUpdatedEvent> | undefined;
export function useRoleMappings() {
const subscribe = useCallback((cb: () => void) => mappings!.subscribe(cb), []);
return useSyncExternalStore(subscribe, () => mappings!.getSnapshot());
}
export default function registerPlugin(context: WebPluginContext) {
context.control.hooks.extensionComponents.attach("exp_discord_sync", () => ({
RoleViewPageBeforePermissions: RoleDiscordRoles,
}));
mappings = new lib.MapSubscriber(messages.RoleMappingUpdatedEvent, context.control);
}