mirror of
https://github.com/PHIDIAS0303/ExpCluster.git
synced 2026-11-26 15:47:13 +09:00
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:
1 parent
c1490c0709
commit
2c55cb796e
18 files changed
+1494
No files matched your search
@@ -0,0 +1,284 @@
|
||||
import t from "tap";
|
||||
import * as lib from "@clusterio/lib";
|
||||
import { Controller } from "@clusterio/controller";
|
||||
import { ControllerPlugin as DiscordAuth } from "@expcluster/discord-auth/dist/node/controller.js";
|
||||
import { plugin as discordAuthDeclaration } from "@expcluster/discord-auth/dist/node/index.js";
|
||||
import entrypoint, { ControllerPlugin } from "../dist/node/controller.js";
|
||||
import * as messages from "../dist/node/messages.js";
|
||||
import { plugin as pluginDeclaration } from "../dist/node/index.js";
|
||||
import { guildId, startFakeDiscord, until } from "./fake_discord.js";
|
||||
|
||||
for (const Message of [...pluginDeclaration.messages, ...discordAuthDeclaration.messages]) {
|
||||
lib.Link.register(Message);
|
||||
}
|
||||
lib.addPluginConfigFields([pluginDeclaration, discordAuthDeclaration]);
|
||||
|
||||
const warnings = [];
|
||||
const logger = {
|
||||
child: () => logger, info: () => {}, error: msg => warnings.push(msg), verbose: () => {},
|
||||
warn: msg => warnings.push(msg),
|
||||
};
|
||||
|
||||
lib.logger.silent = true;
|
||||
t.after(() => {
|
||||
lib.logger.silent = false;
|
||||
});
|
||||
|
||||
const discordRoles = { moderator: "200000000000000001", trusted: "200000000000000002", other: "200000000000000003" };
|
||||
const alice = { id: "300000000000000001", name: "Alice" };
|
||||
const bob = { id: "300000000000000002", name: "Bob" };
|
||||
const role = (id, name) => new lib.Role(id, name, "", new Set());
|
||||
|
||||
/**
|
||||
* exp_discord_sync and exp_discord_auth on a real controller, talking to a fake Discord.
|
||||
*
|
||||
* Sync loads before auth to cover auth being looked up late.
|
||||
*/
|
||||
const defaultMappings = { 5: [discordRoles.moderator], 6: [discordRoles.trusted] };
|
||||
async function startPlugin(t2, { fakeOptions, mappings = defaultMappings } = {}) {
|
||||
const fake = await startFakeDiscord(fakeOptions);
|
||||
t2.teardown(fake.close);
|
||||
fake.roles.push(
|
||||
{ id: discordRoles.moderator, name: "Moderator", color: 0xff0000, position: 3, managed: false },
|
||||
{ id: discordRoles.trusted, name: "Trusted", color: 0, position: 2, managed: false },
|
||||
{ id: discordRoles.other, name: "Other", color: 0, position: 1, managed: false },
|
||||
{ id: "200000000000000004", name: "Some Bot", color: 0, position: 4, managed: true },
|
||||
);
|
||||
|
||||
const controllerConfig = new lib.ControllerConfig("controller", {
|
||||
"controller.database_directory": t2.testdir(),
|
||||
"controller.auth_secret": Buffer.from("test secret").toString("base64"),
|
||||
});
|
||||
const controller = new Controller(logger, [], controllerConfig);
|
||||
controller.roles.set(role(5, "Moderator"));
|
||||
controller.roles.set(role(6, "Trusted"));
|
||||
controller.roles.set(role(7, "Regular"));
|
||||
for (const name of ["Player1", "Player2", "Player3"]) {
|
||||
controller.users.createUser(name);
|
||||
}
|
||||
|
||||
const plugin = await ControllerPlugin.fromContext({ plugin: { name: "exp_discord_sync" }, controller, logger });
|
||||
t2.teardown(() => plugin.disconnect());
|
||||
const auth = await DiscordAuth.fromContext({ plugin: { name: "exp_discord_auth" }, controller, logger });
|
||||
t2.teardown(() => clearInterval(auth.cleanupInterval));
|
||||
for (const [roleId, ids] of Object.entries(mappings)) {
|
||||
plugin.mappings.set(new messages.RoleMappingRecord(Number(roleId), ids));
|
||||
}
|
||||
|
||||
plugin.apiBase = fake.apiBase;
|
||||
plugin.gatewayUrl = fake.gatewayUrl;
|
||||
controller.config.set("exp_discord_sync.bot_token", "token");
|
||||
controller.config.set("exp_discord_sync.guild_id", guildId);
|
||||
if (!plugin.gateway) {
|
||||
plugin.connect();
|
||||
}
|
||||
return { plugin, auth, controller, fake };
|
||||
}
|
||||
|
||||
function setRoles(controller, name, roleIds) {
|
||||
controller.users.getByNameMutable(name).set("roleIds", new Set(roleIds));
|
||||
}
|
||||
const rolesOf = (fake, id) => [...fake.members.get(id)].sort();
|
||||
async function settled(plugin) {
|
||||
await until(() => !plugin.draining && !plugin.pending.size);
|
||||
}
|
||||
|
||||
t.test("entrypoint", async t2 => {
|
||||
const controllerConfig = new lib.ControllerConfig("controller", { "controller.database_directory": t2.testdir() });
|
||||
const controller = new Controller(logger, [], controllerConfig);
|
||||
await entrypoint({ controller, logger, plugin: { name: "exp_discord_sync" }, metrics: undefined });
|
||||
for (const hook of ["save", "shutdown", "controllerConfigFieldChanged"]) {
|
||||
t2.ok([...controller.hooks[hook].attached].includes("exp_discord_sync"), `attached to ${hook}`);
|
||||
}
|
||||
await controller.hooks.shutdown.invoke();
|
||||
});
|
||||
|
||||
t.test("syncing", t2 => {
|
||||
t2.test("connecting syncs every linked account and only touches mapped roles", async t3 => {
|
||||
const { fake, auth, controller, plugin } = await startPlugin(t3);
|
||||
await plugin.drain();
|
||||
fake.members.set(alice.id, new Set([discordRoles.trusted, discordRoles.other]));
|
||||
fake.members.set(bob.id, new Set([discordRoles.trusted]));
|
||||
setRoles(controller, "Player1", [5]);
|
||||
auth.linkAccount(alice, "Player1");
|
||||
await settled(plugin);
|
||||
|
||||
plugin.disconnect();
|
||||
fake.members.set(alice.id, new Set([discordRoles.trusted, discordRoles.other]));
|
||||
plugin.connect();
|
||||
await until(() => fake.identifies.length === 2);
|
||||
await until(() => rolesOf(fake, alice.id).join() === [discordRoles.moderator, discordRoles.other].join());
|
||||
t3.same(rolesOf(fake, bob.id), [discordRoles.trusted], "unlinked member is left alone");
|
||||
});
|
||||
|
||||
t2.test("roles come from every player linked to the account", async t3 => {
|
||||
const { fake, auth, controller, plugin } = await startPlugin(t3);
|
||||
fake.members.set(alice.id, new Set());
|
||||
setRoles(controller, "Player1", [5]);
|
||||
setRoles(controller, "Player2", [6, 7]);
|
||||
auth.linkAccount(alice, "Player1");
|
||||
auth.linkAccount(alice, "Player2");
|
||||
await until(() => rolesOf(fake, alice.id).length === 2);
|
||||
t3.same(rolesOf(fake, alice.id), [discordRoles.moderator, discordRoles.trusted]);
|
||||
});
|
||||
|
||||
t2.test("unlinking takes the roles away", async t3 => {
|
||||
const { fake, auth, controller, plugin } = await startPlugin(t3);
|
||||
fake.members.set(alice.id, new Set([discordRoles.other]));
|
||||
setRoles(controller, "Player1", [5]);
|
||||
auth.linkAccount(alice, "Player1");
|
||||
await until(() => rolesOf(fake, alice.id).length === 2);
|
||||
auth.removeLink("Player1");
|
||||
await until(() => rolesOf(fake, alice.id).length === 1);
|
||||
t3.same(rolesOf(fake, alice.id), [discordRoles.other]);
|
||||
await settled(plugin);
|
||||
});
|
||||
|
||||
t2.test("role changes in clusterio are passed on, other user updates are not", async t3 => {
|
||||
const { fake, auth, controller, plugin } = await startPlugin(t3);
|
||||
fake.members.set(alice.id, new Set());
|
||||
auth.linkAccount(alice, "Player1");
|
||||
await settled(plugin);
|
||||
|
||||
setRoles(controller, "Player1", [6]);
|
||||
await until(() => rolesOf(fake, alice.id).length === 1);
|
||||
t3.same(rolesOf(fake, alice.id), [discordRoles.trusted]);
|
||||
setRoles(controller, "Player1", [5]);
|
||||
await until(() => rolesOf(fake, alice.id)[0] === discordRoles.moderator);
|
||||
t3.same(rolesOf(fake, alice.id), [discordRoles.moderator]);
|
||||
|
||||
await settled(plugin);
|
||||
fake.requests.length = 0;
|
||||
controller.users.getByNameMutable("Player1").set("isAdmin", true);
|
||||
setRoles(controller, "Player2", [5]);
|
||||
await settled(plugin);
|
||||
t3.same(fake.requests, [], "no requests for unlinked users or other fields");
|
||||
});
|
||||
|
||||
t2.test("a member joining the guild gets their roles", async t3 => {
|
||||
const { fake, auth, controller, plugin } = await startPlugin(t3);
|
||||
setRoles(controller, "Player1", [5]);
|
||||
auth.linkAccount(alice, "Player1");
|
||||
await settled(plugin);
|
||||
|
||||
fake.members.set(alice.id, new Set());
|
||||
fake.dispatch("GUILD_MEMBER_ADD", { guild_id: guildId, user: { id: alice.id }, roles: [] });
|
||||
await until(() => rolesOf(fake, alice.id).length === 1);
|
||||
t3.same(rolesOf(fake, alice.id), [discordRoles.moderator]);
|
||||
});
|
||||
|
||||
t2.test("roles Discord refuses are logged and the rest carry on", async t3 => {
|
||||
const { fake, auth, controller, plugin } = await startPlugin(t3);
|
||||
fake.roles.find(r => r.id === discordRoles.moderator).name = "Above bot";
|
||||
fake.members.set(alice.id, new Set());
|
||||
fake.members.set(bob.id, new Set());
|
||||
setRoles(controller, "Player1", [5]);
|
||||
setRoles(controller, "Player2", [6]);
|
||||
warnings.length = 0;
|
||||
auth.linkAccount(alice, "Player1");
|
||||
auth.linkAccount(bob, "Player2");
|
||||
await until(() => rolesOf(fake, bob.id).length === 1);
|
||||
t3.ok(warnings.some(msg => /Discord refused to change roles of 300000000000000001/.test(msg)));
|
||||
await settled(plugin);
|
||||
});
|
||||
|
||||
t2.test("a bot without the members intent still syncs", async t3 => {
|
||||
const { fake, auth, controller, plugin } = await startPlugin(t3, { fakeOptions: { closeCode: 4014 } });
|
||||
await until(() => fake.identifies.length === 1);
|
||||
await settled(plugin);
|
||||
fake.members.set(alice.id, new Set());
|
||||
setRoles(controller, "Player1", [5]);
|
||||
auth.linkAccount(alice, "Player1");
|
||||
await until(() => rolesOf(fake, alice.id).length === 1);
|
||||
t3.ok(plugin.rest, "rest is kept");
|
||||
t3.ok(warnings.some(msg => /missing the Server Members intent/.test(msg)));
|
||||
});
|
||||
|
||||
t2.test("nothing is sent while the bot is not configured", async t3 => {
|
||||
const { fake, auth, controller, plugin } = await startPlugin(t3);
|
||||
await settled(plugin);
|
||||
controller.config.set("exp_discord_sync.bot_token", null);
|
||||
plugin.disconnect();
|
||||
plugin.connect();
|
||||
fake.requests.length = 0;
|
||||
fake.members.set(alice.id, new Set());
|
||||
setRoles(controller, "Player1", [5]);
|
||||
auth.linkAccount(alice, "Player1");
|
||||
await settled(plugin);
|
||||
t3.same(fake.requests, []);
|
||||
t3.ok(await plugin.handleGuildRoleListRequest().catch(err => err) instanceof lib.UnavailableError);
|
||||
});
|
||||
t2.end();
|
||||
});
|
||||
|
||||
t.test("role mappings", t2 => {
|
||||
t2.test("RoleMappingUpdateRequest sets, validates and removes mappings", async t3 => {
|
||||
const { fake, auth, controller, plugin } = await startPlugin(t3, { mappings: {} });
|
||||
fake.members.set(alice.id, new Set());
|
||||
setRoles(controller, "Player1", [7]);
|
||||
auth.linkAccount(alice, "Player1");
|
||||
await settled(plugin);
|
||||
|
||||
const update = (roleId, ids) => plugin.handleMappingUpdateRequest(
|
||||
new messages.RoleMappingUpdateRequest(roleId, ids)
|
||||
);
|
||||
await update(7, [discordRoles.other, discordRoles.other]);
|
||||
t3.same(plugin.mappings.get(7).discordRoleIds, [discordRoles.other], "duplicates are dropped");
|
||||
await until(() => rolesOf(fake, alice.id).length === 1);
|
||||
|
||||
t3.ok(await update(7, ["abc"]).catch(err => err) instanceof lib.ValidationError);
|
||||
t3.ok(await update(99, [discordRoles.other]).catch(err => err) instanceof lib.NotFoundError);
|
||||
|
||||
await update(7, []);
|
||||
t3.notOk(plugin.mappings.has(7), "empty list removes the mapping");
|
||||
await settled(plugin);
|
||||
t3.same(rolesOf(fake, alice.id), [discordRoles.other], "roles no longer mapped are left on members");
|
||||
});
|
||||
|
||||
t2.test("mapping changes are broadcast", async t3 => {
|
||||
const { controller, plugin } = await startPlugin(t3, { mappings: {} });
|
||||
const sent = [];
|
||||
controller.subscriptions.broadcast = event => sent.push(event);
|
||||
await plugin.handleMappingUpdateRequest(new messages.RoleMappingUpdateRequest(5, [discordRoles.moderator]));
|
||||
t3.equal(sent.length, 1);
|
||||
t3.same(sent[0].updates.map(m => [m.id, m.discordRoleIds]), [[5, [discordRoles.moderator]]]);
|
||||
const event = await plugin.handleMappingSubscription({ lastRequestTimeMs: 0 });
|
||||
t3.same(event.updates.map(m => m.id), [5]);
|
||||
await settled(plugin);
|
||||
});
|
||||
|
||||
t2.test("mappings of deleted roles are removed", async t3 => {
|
||||
const { controller, plugin } = await startPlugin(t3);
|
||||
controller.roles.delete(controller.roles.get(6));
|
||||
t3.same([...plugin.mappings.values()].map(m => m.id), [5]);
|
||||
await settled(plugin);
|
||||
});
|
||||
|
||||
t2.test("mappings are saved and loaded", async t3 => {
|
||||
const { controller, plugin } = await startPlugin(t3);
|
||||
await plugin.onShutdown();
|
||||
const restarted = new Controller(logger, [], new lib.ControllerConfig("controller", {
|
||||
"controller.database_directory": controller.config.get("controller.database_directory"),
|
||||
}));
|
||||
restarted.roles.set(role(5, "Moderator"));
|
||||
restarted.roles.set(role(6, "Trusted"));
|
||||
const reloaded = await ControllerPlugin.fromContext({
|
||||
plugin: { name: "exp_discord_sync" }, controller: restarted, logger,
|
||||
});
|
||||
t3.same([...reloaded.mappings.values()].map(m => [m.id, m.discordRoleIds]), [
|
||||
[5, [discordRoles.moderator]],
|
||||
[6, [discordRoles.trusted]],
|
||||
]);
|
||||
});
|
||||
|
||||
t2.test("GuildRoleListRequest lists roles the bot can give, highest first", async t3 => {
|
||||
const { plugin } = await startPlugin(t3);
|
||||
t3.same(await plugin.handleGuildRoleListRequest(), [
|
||||
{ id: discordRoles.moderator, name: "Moderator", color: 0xff0000 },
|
||||
{ id: discordRoles.trusted, name: "Trusted", color: 0 },
|
||||
{ id: discordRoles.other, name: "Other", color: 0 },
|
||||
]);
|
||||
await settled(plugin);
|
||||
});
|
||||
t2.end();
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
import t from "tap";
|
||||
import * as lib from "@clusterio/lib";
|
||||
import { DiscordApiError, DiscordGateway, DiscordRest, gatewayIntents } from "../dist/node/discord.js";
|
||||
import { guildId, startFakeDiscord, until } from "./fake_discord.js";
|
||||
|
||||
const logger = { child: () => logger, info: () => {}, warn: () => {}, error: () => {}, verbose: () => {} };
|
||||
const memberId = "300000000000000000";
|
||||
const roleId = "200000000000000001";
|
||||
|
||||
t.test("class DiscordRest", async t2 => {
|
||||
const fake = await startFakeDiscord();
|
||||
t2.teardown(fake.close);
|
||||
fake.members.set(memberId, new Set());
|
||||
|
||||
t2.test(".getGuildMember() returns the member, or undefined when not in the guild", async t3 => {
|
||||
const rest = new DiscordRest("token", fake.apiBase);
|
||||
t3.same(await rest.getGuildMember(guildId, memberId), { user: { id: memberId }, roles: [] });
|
||||
t3.equal(await rest.getGuildMember(guildId, "1"), undefined);
|
||||
});
|
||||
|
||||
t2.test(".addMemberRole() and .removeMemberRole() change roles", async t3 => {
|
||||
const rest = new DiscordRest("token", fake.apiBase);
|
||||
await rest.addMemberRole(guildId, memberId, roleId);
|
||||
t3.same([...fake.members.get(memberId)], [roleId]);
|
||||
await rest.removeMemberRole(guildId, memberId, roleId);
|
||||
t3.same([...fake.members.get(memberId)], []);
|
||||
});
|
||||
|
||||
t2.test("waits out 429 responses and retries", async t3 => {
|
||||
const rest = new DiscordRest("token", fake.apiBase);
|
||||
fake.requests.length = 0;
|
||||
fake.rateLimit = 2;
|
||||
const start = Date.now();
|
||||
await rest.getGuildRoles(guildId);
|
||||
t3.equal(fake.requests.length, 3);
|
||||
t3.ok(Date.now() - start >= 90, "waited retry_after twice");
|
||||
});
|
||||
|
||||
t2.test("gives up after repeated 429 responses", async t3 => {
|
||||
const rest = new DiscordRest("token", fake.apiBase);
|
||||
fake.rateLimit = 6;
|
||||
await t3.rejects(rest.getGuildRoles(guildId), { status: 429 });
|
||||
fake.rateLimit = 0;
|
||||
});
|
||||
|
||||
t2.test("throws DiscordApiError with the status", async t3 => {
|
||||
const rest = new DiscordRest("wrong", fake.apiBase);
|
||||
const err = await rest.getGuildRoles(guildId).catch(e => e);
|
||||
t3.ok(err instanceof DiscordApiError);
|
||||
t3.equal(err.status, 401);
|
||||
});
|
||||
|
||||
t2.test("sends one request at a time", async t3 => {
|
||||
const rest = new DiscordRest("token", fake.apiBase);
|
||||
fake.requests.length = 0;
|
||||
fake.rateLimit = 1;
|
||||
await Promise.all([rest.getGuildRoles(guildId), rest.getGuildMember(guildId, memberId)]);
|
||||
t3.same(fake.requests, [
|
||||
`GET /guilds/${guildId}/roles`,
|
||||
`GET /guilds/${guildId}/roles`,
|
||||
`GET /guilds/${guildId}/members/${memberId}`,
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
t.test("class DiscordGateway", async t2 => {
|
||||
t2.test("identifies with the intents and passes on dispatches", async t3 => {
|
||||
const fake = await startFakeDiscord();
|
||||
t3.teardown(fake.close);
|
||||
const events = [];
|
||||
const gateway = new DiscordGateway("token", gatewayIntents.GUILD_MEMBERS, logger, {
|
||||
onReady: () => events.push("ready"),
|
||||
onDispatch: (type, data) => events.push([type, data]),
|
||||
}, fake.gatewayUrl);
|
||||
t3.teardown(() => gateway.stop());
|
||||
gateway.start();
|
||||
await until(() => events.length);
|
||||
t3.equal(fake.identifies[0].token, "token");
|
||||
t3.equal(fake.identifies[0].intents, gatewayIntents.GUILD_MEMBERS);
|
||||
fake.dispatch("GUILD_MEMBER_ADD", { guild_id: guildId, user: { id: memberId } });
|
||||
await until(() => events.length === 2);
|
||||
t3.same(events, ["ready", ["GUILD_MEMBER_ADD", { guild_id: guildId, user: { id: memberId } }]]);
|
||||
});
|
||||
|
||||
t2.test("reconnects when the connection drops", async t3 => {
|
||||
const fake = await startFakeDiscord();
|
||||
t3.teardown(fake.close);
|
||||
let ready = 0;
|
||||
const gateway = new DiscordGateway("token", 0, logger, { onReady: () => { ready += 1; } }, fake.gatewayUrl);
|
||||
gateway.backoff = new lib.ExponentialBackoff({ base: 0.01, max: 0.02 });
|
||||
t3.teardown(() => gateway.stop());
|
||||
gateway.start();
|
||||
await until(() => ready === 1);
|
||||
for (const ws of fake.sockets) {
|
||||
ws.terminate();
|
||||
}
|
||||
await until(() => ready === 2);
|
||||
t3.equal(fake.identifies.length, 2);
|
||||
});
|
||||
|
||||
t2.test("stops on a fatal close code", async t3 => {
|
||||
const fake = await startFakeDiscord({ closeCode: 4014 });
|
||||
t3.teardown(fake.close);
|
||||
let closed;
|
||||
const gateway = new DiscordGateway("token", 0, logger, {
|
||||
onFatalClose: (code, reason) => { closed = { code, reason }; },
|
||||
}, fake.gatewayUrl);
|
||||
gateway.backoff = new lib.ExponentialBackoff({ base: 0.01, max: 0.02 });
|
||||
gateway.start();
|
||||
await until(() => closed);
|
||||
t3.same(closed, { code: 4014, reason: "closed by fake" });
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
t3.equal(fake.identifies.length, 1, "did not reconnect");
|
||||
});
|
||||
|
||||
t2.test(".stop() closes without reconnecting", async t3 => {
|
||||
const fake = await startFakeDiscord();
|
||||
t3.teardown(fake.close);
|
||||
let ready = 0;
|
||||
const gateway = new DiscordGateway("token", 0, logger, { onReady: () => { ready += 1; } }, fake.gatewayUrl);
|
||||
gateway.backoff = new lib.ExponentialBackoff({ base: 0.01, max: 0.02 });
|
||||
gateway.start();
|
||||
await until(() => ready === 1);
|
||||
gateway.stop();
|
||||
await until(() => fake.sockets.size === 0);
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
t3.equal(fake.identifies.length, 1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
import * as http from "node:http";
|
||||
import { WebSocketServer } from "ws";
|
||||
|
||||
export const guildId = "100000000000000000";
|
||||
|
||||
/**
|
||||
* Discord REST and gateway for one guild on a local port.
|
||||
*
|
||||
* members maps user id to a Set of role ids. rateLimit makes the next n
|
||||
* requests answer 429. The gateway sends READY after identify, more events
|
||||
* go through dispatch().
|
||||
*/
|
||||
export async function startFakeDiscord({ token = "token", closeCode } = {}) {
|
||||
const fake = {
|
||||
roles: [
|
||||
{ id: guildId, name: "@everyone", color: 0, position: 0, managed: false },
|
||||
],
|
||||
members: new Map(),
|
||||
requests: [],
|
||||
rateLimit: 0,
|
||||
identifies: [],
|
||||
sockets: new Set(),
|
||||
dispatch(t, d) {
|
||||
for (const ws of fake.sockets) {
|
||||
ws.send(JSON.stringify({ op: 0, s: 2, t, d }));
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
const route = `${req.method} ${req.url.replace(/^\/api\/v10/, "")}`;
|
||||
fake.requests.push(route);
|
||||
const reply = (status, body) => {
|
||||
res.writeHead(status, { "Content-Type": "application/json" });
|
||||
res.end(body === undefined ? undefined : JSON.stringify(body));
|
||||
};
|
||||
if (req.headers.authorization !== `Bot ${token}`) {
|
||||
reply(401, { message: "401: Unauthorized" });
|
||||
return;
|
||||
}
|
||||
if (fake.rateLimit > 0) {
|
||||
fake.rateLimit -= 1;
|
||||
reply(429, { message: "You are being rate limited.", retry_after: 0.05, global: false });
|
||||
return;
|
||||
}
|
||||
|
||||
let match;
|
||||
if (route === `GET /guilds/${guildId}/roles`) {
|
||||
reply(200, fake.roles);
|
||||
} else if ((match = route.match(new RegExp(`^GET /guilds/${guildId}/members/(\\d+)$`)))) {
|
||||
const roles = fake.members.get(match[1]);
|
||||
if (roles) {
|
||||
reply(200, { user: { id: match[1] }, roles: [...roles] });
|
||||
} else {
|
||||
reply(404, { message: "Unknown Member", code: 10007 });
|
||||
}
|
||||
} else if ((match = route.match(new RegExp(`^(PUT|DELETE) /guilds/${guildId}/members/(\\d+)/roles/(\\d+)$`)))) {
|
||||
const roles = fake.members.get(match[2]);
|
||||
if (!roles) {
|
||||
reply(404, { message: "Unknown Member", code: 10007 });
|
||||
} else if (fake.roles.find(role => role.id === match[3])?.name === "Above bot") {
|
||||
reply(403, { message: "Missing Permissions", code: 50013 });
|
||||
} else {
|
||||
roles[match[1] === "PUT" ? "add" : "delete"](match[3]);
|
||||
reply(204);
|
||||
}
|
||||
} else {
|
||||
reply(404, { message: "404: Not Found" });
|
||||
}
|
||||
});
|
||||
|
||||
const wss = new WebSocketServer({ server });
|
||||
wss.on("connection", ws => {
|
||||
fake.sockets.add(ws);
|
||||
ws.on("close", () => fake.sockets.delete(ws));
|
||||
ws.send(JSON.stringify({ op: 10, s: null, t: null, d: { heartbeat_interval: 45000 } }));
|
||||
ws.on("message", data => {
|
||||
const payload = JSON.parse(String(data));
|
||||
if (payload.op === 1) {
|
||||
ws.send(JSON.stringify({ op: 11, s: null, t: null, d: null }));
|
||||
} else if (payload.op === 2) {
|
||||
fake.identifies.push(payload.d);
|
||||
if (closeCode) {
|
||||
ws.close(closeCode, "closed by fake");
|
||||
} else if (payload.d.token !== token) {
|
||||
ws.close(4004, "Authentication failed.");
|
||||
} else {
|
||||
ws.send(JSON.stringify({ op: 0, s: 1, t: "READY", d: { session_id: "s" } }));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
|
||||
const port = server.address().port;
|
||||
fake.apiBase = `http://127.0.0.1:${port}/api/v10`;
|
||||
fake.gatewayUrl = `ws://127.0.0.1:${port}/?v=10&encoding=json`;
|
||||
fake.close = async () => {
|
||||
for (const ws of wss.clients) {
|
||||
ws.terminate();
|
||||
}
|
||||
wss.close();
|
||||
server.closeAllConnections();
|
||||
await new Promise(resolve => server.close(resolve));
|
||||
};
|
||||
return fake;
|
||||
}
|
||||
|
||||
/** Wait until check() is truthy, failing after a second. */
|
||||
export async function until(check) {
|
||||
for (let i = 0; i < 100; i++) {
|
||||
if (check()) {
|
||||
return;
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
}
|
||||
throw new Error("timed out waiting");
|
||||
}
|
||||
Reference in new issue
Block a user