@littlespace/fluxkit 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +51 -2
- package/index.js +7 -0
- package/package.json +37 -4
- package/src/client.js +98 -0
- package/src/commands.js +61 -0
- package/src/discovery.js +31 -0
- package/src/gateway.js +210 -0
- package/src/permissions.js +71 -0
- package/src/rest.js +147 -0
- package/src/webhook.js +22 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Cloud Data Hosting LLC
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,52 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @littlespace/fluxkit
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Bot library for [Fluxer](https://fluxer.app). Not an official Fluxer project.
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
npm install @littlespace/fluxkit
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```js
|
|
10
|
+
import { FluxerClient } from '@littlespace/fluxkit';
|
|
11
|
+
|
|
12
|
+
const client = new FluxerClient({ instance: 'https://littlespace.chat', token: process.env.FLUXER_TOKEN });
|
|
13
|
+
client.command('ping', ({ reply }) => reply('pong'));
|
|
14
|
+
await client.login();
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## What it handles
|
|
18
|
+
|
|
19
|
+
- **Discovery.** Reads `/.well-known/fluxer` on the instance and uses `endpoints.api_public` and `endpoints.gateway`. Nothing is hard-coded, so the same bot works on littlespace.chat, us2, us3, etc. by changing `instance`.
|
|
20
|
+
- **Gateway.** Hello, heartbeats (including server-requested ones), Identify, Resume within the 60s window, op 7 reconnect, op 9 re-identify on the same socket, and backoff. Stops for good on 4004 (bad token), 4010, 4011 and 4012 instead of looping.
|
|
21
|
+
- **REST.** `Authorization: Bot <token>`. Uses `retry_after` from 429 bodies (not the rounded header), pauses everything on a global limit, and tracks route buckets from `X-RateLimit-*`. Message sends get a nonce that's reused on retry, so a retry can't double-post. `reason` becomes `X-Audit-Log-Reason`.
|
|
22
|
+
- **Prefix commands.** `!name` or `@Bot name`, quoted args, aliases, `guildOnly`, and a `check` hook. Bots, webhooks and the bot's own messages are ignored.
|
|
23
|
+
- **Webhooks.** `executeWebhook(url, body)` posts with no bot account.
|
|
24
|
+
- **Permissions.** Fluxer's own bit values (`Permissions`) plus `computePermissions(guild, userId, roleIds, channel)`.
|
|
25
|
+
|
|
26
|
+
## How Fluxer differs from Discord (from docs.fluxer.com)
|
|
27
|
+
|
|
28
|
+
| | Discord | Fluxer |
|
|
29
|
+
| --- | --- | --- |
|
|
30
|
+
| Intents | Required | None. Filter with `ignored_events` (default: `TYPING_START`, `PRESENCE_UPDATE`) |
|
|
31
|
+
| Message content | Privileged intent | Always included |
|
|
32
|
+
| Slash commands, buttons, modals | Yes | Not yet. `verify_key` is a placeholder of zeros |
|
|
33
|
+
| Resume URL | `resume_gateway_url` | Same gateway URL, within 60s |
|
|
34
|
+
| Op 9 | `d: true/false` | Always `d: false`, and the socket stays open |
|
|
35
|
+
| Reply option `fail_if_not_exists` | Yes | Doesn't exist |
|
|
36
|
+
|
|
37
|
+
Bots are never "passive" in a guild, so they get every message they can see without sending a Lazy Request.
|
|
38
|
+
|
|
39
|
+
## API
|
|
40
|
+
|
|
41
|
+
- `client.rest`: `sendMessage`, `editMessage`, `deleteMessage(ch, id, reason)`, `react`, `createDM`, `me`, plus `get/post/patch/put/delete(path, ...)` for anything else (paths work with or without `/v1`).
|
|
42
|
+
- `client.reply(message, content)`: replies without pinging the author.
|
|
43
|
+
- Events: `ready`, `message`, `commandError`, `debug`, `error`, `raw (t, d)`, and every dispatch by name (`MESSAGE_DELETE`, `GUILD_MEMBER_ADD`, ...).
|
|
44
|
+
- `client.guilds`, `client.user`, `client.gateway.ping`.
|
|
45
|
+
|
|
46
|
+
## Testing
|
|
47
|
+
|
|
48
|
+
`npm test` runs against a mock Fluxer instance (discovery, HTTP and gateway).
|
|
49
|
+
|
|
50
|
+
For the real thing: `FLUXER_INSTANCE=https://littlespace.chat FLUXER_TOKEN=... node examples/ping.js`, then type `!ping` or `!roll 2d6`.
|
|
51
|
+
|
|
52
|
+
Requires Node 18+ and ESM (`"type": "module"`).
|
package/index.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { FluxerClient } from './src/client.js';
|
|
2
|
+
export { REST, FluxerAPIError, routeKey } from './src/rest.js';
|
|
3
|
+
export { Gateway, Op } from './src/gateway.js';
|
|
4
|
+
export { Commands, splitArgs } from './src/commands.js';
|
|
5
|
+
export { discover, clearDiscoveryCache } from './src/discovery.js';
|
|
6
|
+
export { executeWebhook } from './src/webhook.js';
|
|
7
|
+
export { Permissions, hasPermission, computePermissions } from './src/permissions.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,39 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@littlespace/fluxkit",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Shared Fluxer adapter for the CiGaming bot fleet",
|
|
5
|
+
"main": "index.js",
|
|
6
|
+
"directories": {
|
|
7
|
+
"example": "examples",
|
|
8
|
+
"test": "test"
|
|
9
|
+
},
|
|
10
|
+
"scripts": {
|
|
11
|
+
"test": "node --test test/*.test.js"
|
|
12
|
+
},
|
|
13
|
+
"keywords": [
|
|
14
|
+
"fluxer",
|
|
15
|
+
"bot",
|
|
16
|
+
"gateway",
|
|
17
|
+
"chat",
|
|
18
|
+
"littlespace"
|
|
19
|
+
],
|
|
20
|
+
"author": "",
|
|
21
|
+
"license": "MIT",
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"ws": "^8.23.0"
|
|
24
|
+
},
|
|
25
|
+
"type": "module",
|
|
26
|
+
"exports": "./index.js",
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=18"
|
|
29
|
+
},
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public"
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"index.js",
|
|
35
|
+
"src",
|
|
36
|
+
"README.md",
|
|
37
|
+
"LICENSE"
|
|
38
|
+
]
|
|
39
|
+
}
|
package/src/client.js
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// Ties discovery, REST and the gateway together. A bot passes an instance origin
|
|
2
|
+
// (https://littlespace.chat) and a token, and gets events plus a REST handle.
|
|
3
|
+
|
|
4
|
+
import { EventEmitter } from 'node:events';
|
|
5
|
+
import { discover } from './discovery.js';
|
|
6
|
+
import { REST } from './rest.js';
|
|
7
|
+
import { Gateway } from './gateway.js';
|
|
8
|
+
import { Commands } from './commands.js';
|
|
9
|
+
|
|
10
|
+
const DEFAULT_IGNORED = ['TYPING_START', 'PRESENCE_UPDATE'];
|
|
11
|
+
|
|
12
|
+
export class FluxerClient extends EventEmitter {
|
|
13
|
+
constructor({ instance, token, prefix = '!', ignoredEvents, presence, shard, fetchImpl, WebSocketImpl }) {
|
|
14
|
+
super();
|
|
15
|
+
if (!instance) throw new Error('instance origin is required, e.g. https://littlespace.chat');
|
|
16
|
+
if (!token) throw new Error('bot token is required');
|
|
17
|
+
this.instance = instance;
|
|
18
|
+
this.token = token.replace(/^Bot\s+/i, '');
|
|
19
|
+
this.opts = { ignoredEvents: ignoredEvents ?? DEFAULT_IGNORED, presence, shard, fetchImpl, WebSocketImpl };
|
|
20
|
+
this.commands = new Commands({ prefix });
|
|
21
|
+
this.user = null;
|
|
22
|
+
this.guilds = new Map();
|
|
23
|
+
this.rest = null;
|
|
24
|
+
this.gateway = null;
|
|
25
|
+
this.endpoints = null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async login() {
|
|
29
|
+
this.endpoints = await discover(this.instance, { fetchImpl: this.opts.fetchImpl ?? fetch });
|
|
30
|
+
this.rest = new REST({ api: this.endpoints.api, token: this.token, fetchImpl: this.opts.fetchImpl ?? fetch });
|
|
31
|
+
this.gateway = new Gateway({
|
|
32
|
+
url: this.endpoints.gateway,
|
|
33
|
+
token: this.token,
|
|
34
|
+
ignoredEvents: this.opts.ignoredEvents,
|
|
35
|
+
presence: this.opts.presence,
|
|
36
|
+
shard: this.opts.shard,
|
|
37
|
+
WebSocketImpl: this.opts.WebSocketImpl,
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
this.gateway.on('debug', (m) => this.emit('debug', m));
|
|
41
|
+
this.gateway.on('fatal', (e) => this.emit('error', e));
|
|
42
|
+
this.gateway.on('dispatch', (t, d) => this.#dispatch(t, d));
|
|
43
|
+
|
|
44
|
+
return new Promise((resolve, reject) => {
|
|
45
|
+
const onFatal = (e) => reject(e);
|
|
46
|
+
this.gateway.once('fatal', onFatal);
|
|
47
|
+
this.once('ready', () => { this.gateway.off('fatal', onFatal); resolve(this); });
|
|
48
|
+
this.gateway.connect();
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
destroy() {
|
|
53
|
+
this.gateway?.destroy();
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
command(name, opts, handler) {
|
|
57
|
+
this.commands.add(name, opts, handler);
|
|
58
|
+
return this;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async #dispatch(t, d) {
|
|
62
|
+
switch (t) {
|
|
63
|
+
case 'READY':
|
|
64
|
+
this.user = d.user;
|
|
65
|
+
this.commands.botId = d.user?.id;
|
|
66
|
+
for (const g of d.guilds ?? []) this.guilds.set(g.id, g);
|
|
67
|
+
this.emit('ready', d);
|
|
68
|
+
break;
|
|
69
|
+
case 'GUILD_CREATE':
|
|
70
|
+
case 'GUILD_UPDATE':
|
|
71
|
+
this.guilds.set(d.id, { ...this.guilds.get(d.id), ...d });
|
|
72
|
+
break;
|
|
73
|
+
case 'GUILD_DELETE':
|
|
74
|
+
if (!d.unavailable) this.guilds.delete(d.id);
|
|
75
|
+
break;
|
|
76
|
+
case 'MESSAGE_CREATE':
|
|
77
|
+
if (d.author?.id === this.user?.id) break;
|
|
78
|
+
this.emit('message', d);
|
|
79
|
+
if (!d.author?.bot && !d.webhook_id) {
|
|
80
|
+
try {
|
|
81
|
+
await this.commands.handle({ client: this, message: d, reply: (c) => this.reply(d, c) });
|
|
82
|
+
} catch (err) {
|
|
83
|
+
this.emit('commandError', err, d);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
break;
|
|
87
|
+
}
|
|
88
|
+
this.emit('raw', t, d);
|
|
89
|
+
this.emit(t, d);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
reply(message, content) {
|
|
93
|
+
const body = typeof content === 'string' ? { content } : { ...content };
|
|
94
|
+
body.message_reference = { message_id: message.id, channel_id: message.channel_id };
|
|
95
|
+
body.allowed_mentions ??= { parse: [], replied_user: false };
|
|
96
|
+
return this.rest.sendMessage(message.channel_id, body);
|
|
97
|
+
}
|
|
98
|
+
}
|
package/src/commands.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// Prefix command router. Fluxer has no bot slash commands yet, so this is how
|
|
2
|
+
// every ported bot takes commands. Triggers on "!name" or "@Bot name".
|
|
3
|
+
|
|
4
|
+
export class Commands {
|
|
5
|
+
constructor({ prefix = '!', caseInsensitive = true } = {}) {
|
|
6
|
+
this.prefixes = Array.isArray(prefix) ? prefix : [prefix];
|
|
7
|
+
this.caseInsensitive = caseInsensitive;
|
|
8
|
+
this.map = new Map();
|
|
9
|
+
this.botId = null;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
add(name, opts, handler) {
|
|
13
|
+
if (typeof opts === 'function') { handler = opts; opts = {}; }
|
|
14
|
+
const cmd = { name, handler, description: opts.description ?? '', aliases: opts.aliases ?? [], guildOnly: !!opts.guildOnly, check: opts.check };
|
|
15
|
+
for (const n of [name, ...cmd.aliases]) this.map.set(this.#norm(n), cmd);
|
|
16
|
+
return this;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
list() {
|
|
20
|
+
return [...new Set(this.map.values())];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
parse(content) {
|
|
24
|
+
if (!content) return null;
|
|
25
|
+
let rest = null;
|
|
26
|
+
for (const p of this.prefixes) if (content.startsWith(p)) { rest = content.slice(p.length); break; }
|
|
27
|
+
if (rest === null && this.botId) {
|
|
28
|
+
const m = content.match(new RegExp(`^<@!?${this.botId}>\\s*`));
|
|
29
|
+
if (m) rest = content.slice(m[0].length);
|
|
30
|
+
}
|
|
31
|
+
if (rest === null) return null;
|
|
32
|
+
const args = splitArgs(rest.trim());
|
|
33
|
+
const name = args.shift();
|
|
34
|
+
if (!name) return null;
|
|
35
|
+
const cmd = this.map.get(this.#norm(name));
|
|
36
|
+
return cmd ? { cmd, name, args, argText: rest.trim().slice(name.length).trim() } : null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async handle(ctx) {
|
|
40
|
+
const parsed = this.parse(ctx.message.content);
|
|
41
|
+
if (!parsed) return false;
|
|
42
|
+
const { cmd } = parsed;
|
|
43
|
+
if (cmd.guildOnly && !ctx.message.guild_id) return true;
|
|
44
|
+
if (cmd.check && !(await cmd.check(ctx))) return true;
|
|
45
|
+
await cmd.handler({ ...ctx, args: parsed.args, argText: parsed.argText, command: parsed.name });
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
#norm(n) {
|
|
50
|
+
return this.caseInsensitive ? n.toLowerCase() : n;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Splits on spaces but keeps "quoted strings" together.
|
|
55
|
+
export function splitArgs(s) {
|
|
56
|
+
const out = [];
|
|
57
|
+
const re = /"([^"]*)"|'([^']*)'|(\S+)/g;
|
|
58
|
+
let m;
|
|
59
|
+
while ((m = re.exec(s))) out.push(m[1] ?? m[2] ?? m[3]);
|
|
60
|
+
return out;
|
|
61
|
+
}
|
package/src/discovery.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Finds an instance's API and gateway URLs from /.well-known/fluxer.
|
|
2
|
+
// Fluxer's docs say not to build these from the origin, so every bot goes through here.
|
|
3
|
+
|
|
4
|
+
const cache = new Map();
|
|
5
|
+
|
|
6
|
+
export async function discover(origin, { fetchImpl = fetch, maxAgeMs = 10 * 60 * 1000 } = {}) {
|
|
7
|
+
const base = new URL(origin).origin;
|
|
8
|
+
const hit = cache.get(base);
|
|
9
|
+
if (hit && Date.now() - hit.at < maxAgeMs) return hit.value;
|
|
10
|
+
|
|
11
|
+
const res = await fetchImpl(`${base}/.well-known/fluxer`, { headers: { accept: 'application/json' } });
|
|
12
|
+
if (!res.ok) throw new Error(`discovery failed for ${base}: HTTP ${res.status}`);
|
|
13
|
+
const doc = await res.json();
|
|
14
|
+
const ep = doc.endpoints ?? {};
|
|
15
|
+
|
|
16
|
+
const api = trimSlash(ep.api_public ?? ep.api);
|
|
17
|
+
const gateway = ep.gateway;
|
|
18
|
+
if (!api || !gateway) throw new Error(`discovery for ${base} is missing api_public/gateway`);
|
|
19
|
+
|
|
20
|
+
const value = { origin: base, api, gateway, media: ep.media ?? null, raw: doc };
|
|
21
|
+
cache.set(base, { at: Date.now(), value });
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function clearDiscoveryCache() {
|
|
26
|
+
cache.clear();
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function trimSlash(u) {
|
|
30
|
+
return u ? u.replace(/\/+$/, '') : u;
|
|
31
|
+
}
|
package/src/gateway.js
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
// Gateway client written against docs.fluxer.com/gateway/overview.
|
|
2
|
+
// Differences from Discord that matter here: no intents, raw token with no prefix,
|
|
3
|
+
// v=1 required, no resume_gateway_url (resume on the same URL), op 9 is always d:false,
|
|
4
|
+
// and a session can only be resumed for 60s after the socket drops.
|
|
5
|
+
|
|
6
|
+
import { EventEmitter } from 'node:events';
|
|
7
|
+
import WebSocket from 'ws';
|
|
8
|
+
|
|
9
|
+
export const Op = {
|
|
10
|
+
DISPATCH: 0,
|
|
11
|
+
HEARTBEAT: 1,
|
|
12
|
+
IDENTIFY: 2,
|
|
13
|
+
PRESENCE_UPDATE: 3,
|
|
14
|
+
RESUME: 6,
|
|
15
|
+
RECONNECT: 7,
|
|
16
|
+
INVALID_SESSION: 9,
|
|
17
|
+
HELLO: 10,
|
|
18
|
+
HEARTBEAT_ACK: 11,
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
// Close codes after which reconnecting with the same settings can't work.
|
|
22
|
+
const FATAL = new Map([
|
|
23
|
+
[4004, 'invalid bot token'],
|
|
24
|
+
[4010, 'invalid shard'],
|
|
25
|
+
[4011, 'sharding required (more than 2,500 guilds on one shard)'],
|
|
26
|
+
[4012, 'invalid API version'],
|
|
27
|
+
]);
|
|
28
|
+
|
|
29
|
+
const RESUME_WINDOW_MS = 60_000;
|
|
30
|
+
|
|
31
|
+
export class Gateway extends EventEmitter {
|
|
32
|
+
constructor({ url, token, ignoredEvents = [], presence, shard, properties, WebSocketImpl = WebSocket }) {
|
|
33
|
+
super();
|
|
34
|
+
this.baseUrl = url;
|
|
35
|
+
this.token = token;
|
|
36
|
+
this.ignoredEvents = ignoredEvents;
|
|
37
|
+
this.presence = presence;
|
|
38
|
+
this.shard = shard;
|
|
39
|
+
this.properties = properties ?? { os: process.platform, browser: 'fluxkit', device: 'fluxkit' };
|
|
40
|
+
this.WS = WebSocketImpl;
|
|
41
|
+
|
|
42
|
+
this.ws = null;
|
|
43
|
+
this.seq = null;
|
|
44
|
+
this.sessionId = null;
|
|
45
|
+
this.droppedAt = 0;
|
|
46
|
+
this.heartbeatTimer = null;
|
|
47
|
+
this.acked = true;
|
|
48
|
+
this.attempts = 0;
|
|
49
|
+
this.closing = false;
|
|
50
|
+
this.lastHeartbeatAt = 0;
|
|
51
|
+
this.ping = null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
connect() {
|
|
55
|
+
this.closing = false;
|
|
56
|
+
const u = new URL(this.baseUrl);
|
|
57
|
+
u.searchParams.set('v', '1');
|
|
58
|
+
u.searchParams.set('encoding', 'json');
|
|
59
|
+
const ws = new this.WS(u.toString());
|
|
60
|
+
this.ws = ws;
|
|
61
|
+
|
|
62
|
+
ws.on('message', (data) => {
|
|
63
|
+
let msg;
|
|
64
|
+
try { msg = JSON.parse(data.toString()); } catch { return; }
|
|
65
|
+
this.#handle(msg);
|
|
66
|
+
});
|
|
67
|
+
ws.on('close', (code, reason) => this.#onClose(ws, code, reason?.toString()));
|
|
68
|
+
ws.on('error', (err) => this.emit('debug', `socket error: ${err.message}`));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
destroy() {
|
|
72
|
+
this.closing = true;
|
|
73
|
+
this.#stopHeartbeat();
|
|
74
|
+
this.ws?.close(1000);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
send(op, d) {
|
|
78
|
+
if (this.ws?.readyState !== 1) return false;
|
|
79
|
+
this.ws.send(JSON.stringify({ op, d }));
|
|
80
|
+
return true;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
setPresence(presence) {
|
|
84
|
+
this.presence = presence;
|
|
85
|
+
return this.send(Op.PRESENCE_UPDATE, presence);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
#handle(msg) {
|
|
89
|
+
switch (msg.op) {
|
|
90
|
+
case Op.HELLO:
|
|
91
|
+
this.#startHeartbeat(msg.d.heartbeat_interval);
|
|
92
|
+
this.#identifyOrResume();
|
|
93
|
+
break;
|
|
94
|
+
case Op.HEARTBEAT:
|
|
95
|
+
// Server asked for one early (90% of the interval passed without an ack).
|
|
96
|
+
this.#beat();
|
|
97
|
+
break;
|
|
98
|
+
case Op.HEARTBEAT_ACK:
|
|
99
|
+
this.acked = true;
|
|
100
|
+
this.ping = Date.now() - this.lastHeartbeatAt;
|
|
101
|
+
break;
|
|
102
|
+
case Op.RECONNECT:
|
|
103
|
+
this.emit('debug', 'server asked us to reconnect');
|
|
104
|
+
this.#reconnect(true);
|
|
105
|
+
break;
|
|
106
|
+
case Op.INVALID_SESSION:
|
|
107
|
+
// Fluxer always sends d:false. The socket stays open and accepts a fresh Identify.
|
|
108
|
+
this.emit('debug', 'session invalid, identifying again');
|
|
109
|
+
this.sessionId = null;
|
|
110
|
+
this.seq = null;
|
|
111
|
+
setTimeout(() => this.#identify(), 1000 + Math.random() * 4000);
|
|
112
|
+
break;
|
|
113
|
+
case Op.DISPATCH:
|
|
114
|
+
if (typeof msg.s === 'number' && (this.seq === null || msg.s > this.seq)) this.seq = msg.s;
|
|
115
|
+
if (msg.t === 'READY') {
|
|
116
|
+
this.sessionId = msg.d.session_id;
|
|
117
|
+
this.attempts = 0;
|
|
118
|
+
}
|
|
119
|
+
if (msg.t === 'RESUMED') this.attempts = 0;
|
|
120
|
+
this.emit('dispatch', msg.t, msg.d);
|
|
121
|
+
this.emit(msg.t, msg.d);
|
|
122
|
+
break;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
#identifyOrResume() {
|
|
127
|
+
const canResume = this.sessionId && this.seq !== null && Date.now() - this.droppedAt < RESUME_WINDOW_MS;
|
|
128
|
+
if (canResume) {
|
|
129
|
+
this.emit('debug', `resuming session at seq ${this.seq}`);
|
|
130
|
+
this.send(Op.RESUME, { token: this.token, session_id: this.sessionId, seq: this.seq });
|
|
131
|
+
} else {
|
|
132
|
+
this.#identify();
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
#identify() {
|
|
137
|
+
const d = { token: this.token, properties: this.properties };
|
|
138
|
+
if (this.ignoredEvents.length) d.ignored_events = this.ignoredEvents;
|
|
139
|
+
if (this.presence) d.presence = this.presence;
|
|
140
|
+
if (this.shard) d.shard = this.shard;
|
|
141
|
+
this.sessionId = null;
|
|
142
|
+
this.seq = null;
|
|
143
|
+
this.send(Op.IDENTIFY, d);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
#startHeartbeat(interval) {
|
|
147
|
+
this.#stopHeartbeat();
|
|
148
|
+
this.acked = true;
|
|
149
|
+
// First beat after a random fraction of the interval, like the reference clients.
|
|
150
|
+
const first = setTimeout(() => {
|
|
151
|
+
this.#beat();
|
|
152
|
+
this.heartbeatTimer = setInterval(() => {
|
|
153
|
+
if (!this.acked) {
|
|
154
|
+
this.emit('debug', 'heartbeat not acked, reconnecting');
|
|
155
|
+
this.#reconnect(true);
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
this.#beat();
|
|
159
|
+
}, interval);
|
|
160
|
+
}, Math.floor(interval * Math.random()));
|
|
161
|
+
this.heartbeatTimer = first;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
#beat() {
|
|
165
|
+
this.acked = false;
|
|
166
|
+
this.lastHeartbeatAt = Date.now();
|
|
167
|
+
this.send(Op.HEARTBEAT, this.seq);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
#stopHeartbeat() {
|
|
171
|
+
clearTimeout(this.heartbeatTimer);
|
|
172
|
+
clearInterval(this.heartbeatTimer);
|
|
173
|
+
this.heartbeatTimer = null;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
#reconnect(resumable) {
|
|
177
|
+
const old = this.ws;
|
|
178
|
+
this.#stopHeartbeat();
|
|
179
|
+
this.droppedAt = Date.now();
|
|
180
|
+
if (!resumable) { this.sessionId = null; this.seq = null; }
|
|
181
|
+
// 4000 (not 1000/1001) so the server keeps the session open for Resume.
|
|
182
|
+
old?.removeAllListeners('close');
|
|
183
|
+
try { old?.close(4000); } catch {}
|
|
184
|
+
this.#scheduleConnect();
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
#onClose(ws, code, reason) {
|
|
188
|
+
if (ws !== this.ws) return;
|
|
189
|
+
this.#stopHeartbeat();
|
|
190
|
+
this.droppedAt = Date.now();
|
|
191
|
+
this.emit('debug', `closed ${code} ${reason ?? ''}`.trim());
|
|
192
|
+
if (this.closing) return this.emit('close', code, reason);
|
|
193
|
+
|
|
194
|
+
if (FATAL.has(code)) {
|
|
195
|
+
const err = new Error(`gateway closed ${code}: ${FATAL.get(code)}`);
|
|
196
|
+
err.code = code;
|
|
197
|
+
return this.emit('fatal', err);
|
|
198
|
+
}
|
|
199
|
+
// 4007 means our seq is unusable; start fresh.
|
|
200
|
+
if (code === 4007) { this.sessionId = null; this.seq = null; }
|
|
201
|
+
this.#scheduleConnect();
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
#scheduleConnect() {
|
|
205
|
+
const delay = Math.min(30_000, 1000 * 2 ** this.attempts) + Math.random() * 1000;
|
|
206
|
+
this.attempts++;
|
|
207
|
+
this.emit('debug', `reconnecting in ${Math.round(delay)}ms`);
|
|
208
|
+
setTimeout(() => { if (!this.closing) this.connect(); }, this.attempts === 1 ? 250 : delay);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// Copied from fluxer packages/constants/src/ChannelConstants.ts. Don't assume Discord's values.
|
|
2
|
+
export const Permissions = Object.freeze({
|
|
3
|
+
CREATE_INSTANT_INVITE: 1n << 0n,
|
|
4
|
+
KICK_MEMBERS: 1n << 1n,
|
|
5
|
+
BAN_MEMBERS: 1n << 2n,
|
|
6
|
+
ADMINISTRATOR: 1n << 3n,
|
|
7
|
+
MANAGE_CHANNELS: 1n << 4n,
|
|
8
|
+
MANAGE_GUILD: 1n << 5n,
|
|
9
|
+
ADD_REACTIONS: 1n << 6n,
|
|
10
|
+
VIEW_AUDIT_LOG: 1n << 7n,
|
|
11
|
+
PRIORITY_SPEAKER: 1n << 8n,
|
|
12
|
+
STREAM: 1n << 9n,
|
|
13
|
+
VIEW_CHANNEL: 1n << 10n,
|
|
14
|
+
SEND_MESSAGES: 1n << 11n,
|
|
15
|
+
SEND_TTS_MESSAGES: 1n << 12n,
|
|
16
|
+
MANAGE_MESSAGES: 1n << 13n,
|
|
17
|
+
EMBED_LINKS: 1n << 14n,
|
|
18
|
+
ATTACH_FILES: 1n << 15n,
|
|
19
|
+
READ_MESSAGE_HISTORY: 1n << 16n,
|
|
20
|
+
MENTION_EVERYONE: 1n << 17n,
|
|
21
|
+
USE_EXTERNAL_EMOJIS: 1n << 18n,
|
|
22
|
+
CONNECT: 1n << 20n,
|
|
23
|
+
SPEAK: 1n << 21n,
|
|
24
|
+
MUTE_MEMBERS: 1n << 22n,
|
|
25
|
+
DEAFEN_MEMBERS: 1n << 23n,
|
|
26
|
+
MOVE_MEMBERS: 1n << 24n,
|
|
27
|
+
USE_VAD: 1n << 25n,
|
|
28
|
+
CHANGE_NICKNAME: 1n << 26n,
|
|
29
|
+
MANAGE_NICKNAMES: 1n << 27n,
|
|
30
|
+
MANAGE_ROLES: 1n << 28n,
|
|
31
|
+
MANAGE_WEBHOOKS: 1n << 29n,
|
|
32
|
+
MANAGE_EXPRESSIONS: 1n << 30n,
|
|
33
|
+
USE_EXTERNAL_STICKERS: 1n << 37n,
|
|
34
|
+
MODERATE_MEMBERS: 1n << 40n,
|
|
35
|
+
CREATE_EXPRESSIONS: 1n << 43n,
|
|
36
|
+
PIN_MESSAGES: 1n << 51n,
|
|
37
|
+
BYPASS_SLOWMODE: 1n << 52n,
|
|
38
|
+
UPDATE_RTC_REGION: 1n << 53n,
|
|
39
|
+
VIEW_CHANNEL_MEMBERS: 1n << 54n,
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
// Works out a member's permissions in a channel from a cached guild
|
|
43
|
+
// (roles + owner_id), the member's role IDs, and the channel's overwrites.
|
|
44
|
+
export function computePermissions(guild, memberUserId, memberRoleIds = [], channel) {
|
|
45
|
+
if (guild.owner_id === memberUserId) return allBits();
|
|
46
|
+
const roles = new Map((guild.roles ?? []).map((r) => [r.id, r]));
|
|
47
|
+
let perms = BigInt(roles.get(guild.id)?.permissions ?? 0);
|
|
48
|
+
for (const id of memberRoleIds) perms |= BigInt(roles.get(id)?.permissions ?? 0);
|
|
49
|
+
if (perms & Permissions.ADMINISTRATOR) return allBits();
|
|
50
|
+
if (!channel?.permission_overwrites) return perms;
|
|
51
|
+
|
|
52
|
+
const ow = channel.permission_overwrites;
|
|
53
|
+
const everyone = ow.find((o) => o.id === guild.id);
|
|
54
|
+
if (everyone) perms = (perms & ~BigInt(everyone.deny)) | BigInt(everyone.allow);
|
|
55
|
+
let allow = 0n, deny = 0n;
|
|
56
|
+
for (const o of ow) {
|
|
57
|
+
if (o.type === 0 && memberRoleIds.includes(o.id)) { allow |= BigInt(o.allow); deny |= BigInt(o.deny); }
|
|
58
|
+
}
|
|
59
|
+
perms = (perms & ~deny) | allow;
|
|
60
|
+
const mine = ow.find((o) => o.type === 1 && o.id === memberUserId);
|
|
61
|
+
if (mine) perms = (perms & ~BigInt(mine.deny)) | BigInt(mine.allow);
|
|
62
|
+
return perms;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function hasPermission(perms, flag) {
|
|
66
|
+
return (BigInt(perms) & Permissions.ADMINISTRATOR) !== 0n || (BigInt(perms) & flag) === flag;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function allBits() {
|
|
70
|
+
return Object.values(Permissions).reduce((a, b) => a | b, 0n);
|
|
71
|
+
}
|
package/src/rest.js
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
// Small REST client for the Fluxer HTTP API.
|
|
2
|
+
// Handles 429s the way the rate-limit docs describe: retry_after from the body wins,
|
|
3
|
+
// a global denial pauses every request on this token, and route buckets are tracked
|
|
4
|
+
// from X-RateLimit-* headers so we slow down before hitting 0.
|
|
5
|
+
|
|
6
|
+
export class FluxerAPIError extends Error {
|
|
7
|
+
constructor(status, body, method, path) {
|
|
8
|
+
super(`${method} ${path} -> ${status} ${body?.code ?? ''} ${body?.message ?? ''}`.trim());
|
|
9
|
+
this.status = status;
|
|
10
|
+
this.code = body?.code;
|
|
11
|
+
this.body = body;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
16
|
+
|
|
17
|
+
export class REST {
|
|
18
|
+
constructor({ api, token, fetchImpl = fetch, maxRetries = 3, userAgent = '@littlespace/fluxkit (0.1.0)' }) {
|
|
19
|
+
if (!api) throw new Error('REST needs the api base URL from discovery');
|
|
20
|
+
this.api = api;
|
|
21
|
+
this.token = token;
|
|
22
|
+
this.fetch = fetchImpl;
|
|
23
|
+
this.maxRetries = maxRetries;
|
|
24
|
+
this.userAgent = userAgent;
|
|
25
|
+
this.globalUntil = 0;
|
|
26
|
+
this.buckets = new Map(); // routeKey -> { remaining, resetAt }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async request(method, path, { body, query, reason, headers = {}, auth = true } = {}) {
|
|
30
|
+
const url = new URL(this.api + (path.startsWith('/v1') ? path : `/v1${path}`));
|
|
31
|
+
if (query) for (const [k, v] of Object.entries(query)) if (v !== undefined) url.searchParams.set(k, String(v));
|
|
32
|
+
const key = routeKey(method, path);
|
|
33
|
+
|
|
34
|
+
// Reuse one nonce across retries so a retried send can't double-post.
|
|
35
|
+
if (method === 'POST' && body && typeof body === 'object' && /\/messages$/.test(path) && body.nonce === undefined) {
|
|
36
|
+
body = { ...body, nonce: makeNonce() };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
for (let attempt = 0; ; attempt++) {
|
|
40
|
+
await this.#waitFor(key);
|
|
41
|
+
|
|
42
|
+
const h = { 'user-agent': this.userAgent, ...headers };
|
|
43
|
+
if (auth && this.token) h.authorization = `Bot ${this.token}`;
|
|
44
|
+
if (reason) h['x-audit-log-reason'] = encodeURIComponent(reason);
|
|
45
|
+
let payload;
|
|
46
|
+
if (body instanceof FormData) payload = body;
|
|
47
|
+
else if (body !== undefined) {
|
|
48
|
+
h['content-type'] = 'application/json';
|
|
49
|
+
payload = JSON.stringify(body);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
let res;
|
|
53
|
+
try {
|
|
54
|
+
res = await this.fetch(url, { method, headers: h, body: payload });
|
|
55
|
+
} catch (err) {
|
|
56
|
+
if (attempt >= this.maxRetries) throw err;
|
|
57
|
+
await sleep(500 * 2 ** attempt);
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
this.#track(key, res.headers);
|
|
62
|
+
|
|
63
|
+
if (res.status === 429) {
|
|
64
|
+
const data = await safeJson(res);
|
|
65
|
+
const wait = data?.retry_after != null ? data.retry_after * 1000 : Number(res.headers.get('retry-after') ?? 1) * 1000;
|
|
66
|
+
if (data?.global || res.headers.get('x-ratelimit-global') === 'true') this.globalUntil = Date.now() + wait;
|
|
67
|
+
else this.buckets.set(key, { remaining: 0, resetAt: Date.now() + wait });
|
|
68
|
+
if (attempt >= this.maxRetries) throw new FluxerAPIError(429, data, method, path);
|
|
69
|
+
await sleep(wait);
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
if (res.status >= 500 && attempt < this.maxRetries) {
|
|
74
|
+
await sleep(1000 * 2 ** attempt);
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
if (res.status === 204) return null;
|
|
79
|
+
const data = await safeJson(res);
|
|
80
|
+
if (!res.ok) throw new FluxerAPIError(res.status, data, method, path);
|
|
81
|
+
return data;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
get(p, o) { return this.request('GET', p, o); }
|
|
86
|
+
post(p, body, o = {}) { return this.request('POST', p, { ...o, body }); }
|
|
87
|
+
patch(p, body, o = {}) { return this.request('PATCH', p, { ...o, body }); }
|
|
88
|
+
put(p, body, o = {}) { return this.request('PUT', p, { ...o, body }); }
|
|
89
|
+
delete(p, o) { return this.request('DELETE', p, o); }
|
|
90
|
+
|
|
91
|
+
// Common calls the fleet bots use.
|
|
92
|
+
me() { return this.get('/users/@me'); }
|
|
93
|
+
sendMessage(channelId, content) {
|
|
94
|
+
const body = typeof content === 'string' ? { content } : content;
|
|
95
|
+
return this.post(`/channels/${channelId}/messages`, body);
|
|
96
|
+
}
|
|
97
|
+
editMessage(channelId, messageId, content) {
|
|
98
|
+
const body = typeof content === 'string' ? { content } : content;
|
|
99
|
+
return this.patch(`/channels/${channelId}/messages/${messageId}`, body);
|
|
100
|
+
}
|
|
101
|
+
deleteMessage(channelId, messageId, reason) {
|
|
102
|
+
return this.delete(`/channels/${channelId}/messages/${messageId}`, { reason });
|
|
103
|
+
}
|
|
104
|
+
react(channelId, messageId, emoji) {
|
|
105
|
+
return this.put(`/channels/${channelId}/messages/${messageId}/reactions/${encodeURIComponent(emoji)}/@me`);
|
|
106
|
+
}
|
|
107
|
+
createDM(recipientId) {
|
|
108
|
+
return this.post('/users/@me/channels', { recipient_id: recipientId });
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async #waitFor(key) {
|
|
112
|
+
const now = Date.now();
|
|
113
|
+
if (this.globalUntil > now) await sleep(this.globalUntil - now);
|
|
114
|
+
const b = this.buckets.get(key);
|
|
115
|
+
if (b && b.remaining <= 0 && b.resetAt > Date.now()) await sleep(b.resetAt - Date.now());
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
#track(key, headers) {
|
|
119
|
+
const remaining = headers.get('x-ratelimit-remaining');
|
|
120
|
+
const after = headers.get('x-ratelimit-reset-after');
|
|
121
|
+
if (remaining == null || after == null) return;
|
|
122
|
+
this.buckets.set(key, { remaining: Number(remaining), resetAt: Date.now() + Number(after) * 1000 });
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Group requests the way buckets usually work: by method plus path with
|
|
127
|
+
// IDs collapsed, except the top-level channel/guild/webhook ID which is a major parameter.
|
|
128
|
+
export function routeKey(method, path) {
|
|
129
|
+
const p = path.replace(/^\/v1/, '').split('?')[0];
|
|
130
|
+
const parts = p.split('/');
|
|
131
|
+
const out = parts.map((seg, i) => {
|
|
132
|
+
if (!/^\d{5,}$/.test(seg)) return seg;
|
|
133
|
+
const prev = parts[i - 1];
|
|
134
|
+
return prev === 'channels' || prev === 'guilds' || prev === 'webhooks' ? seg : ':id';
|
|
135
|
+
});
|
|
136
|
+
return `${method} ${out.join('/')}`;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function makeNonce() {
|
|
140
|
+
return `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 10)}`.slice(0, 32);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function safeJson(res) {
|
|
144
|
+
const text = await res.text();
|
|
145
|
+
if (!text) return null;
|
|
146
|
+
try { return JSON.parse(text); } catch { return { message: text.slice(0, 200) }; }
|
|
147
|
+
}
|
package/src/webhook.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Post through a webhook URL with no bot account (good for go-live announcements).
|
|
2
|
+
// Webhook execution takes no Authorization header and doesn't count against the global rate limit.
|
|
3
|
+
|
|
4
|
+
export async function executeWebhook(url, body, { wait = true, fetchImpl = fetch } = {}) {
|
|
5
|
+
const u = new URL(url);
|
|
6
|
+
if (wait) u.searchParams.set('wait', 'true');
|
|
7
|
+
const payload = typeof body === 'string' ? { content: body } : body;
|
|
8
|
+
|
|
9
|
+
for (let attempt = 0; attempt < 4; attempt++) {
|
|
10
|
+
const res = await fetchImpl(u, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(payload) });
|
|
11
|
+
if (res.status === 429) {
|
|
12
|
+
const data = await res.json().catch(() => ({}));
|
|
13
|
+
await new Promise((r) => setTimeout(r, (data.retry_after ?? 1) * 1000));
|
|
14
|
+
continue;
|
|
15
|
+
}
|
|
16
|
+
if (res.status === 204) return null;
|
|
17
|
+
const data = await res.json().catch(() => null);
|
|
18
|
+
if (!res.ok) throw new Error(`webhook failed: HTTP ${res.status} ${data?.code ?? ''}`.trim());
|
|
19
|
+
return data;
|
|
20
|
+
}
|
|
21
|
+
throw new Error('webhook rate limited too many times');
|
|
22
|
+
}
|