@imvu/bot 0.0.0-stage → 0.1.1
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/README.md +120 -2
- package/dist/Bot.d.ts +239 -0
- package/dist/Bot.d.ts.map +1 -0
- package/dist/Bot.js +496 -0
- package/dist/Bot.js.map +1 -0
- package/dist/RateLimiter.d.ts +28 -0
- package/dist/RateLimiter.d.ts.map +1 -0
- package/dist/RateLimiter.js +66 -0
- package/dist/RateLimiter.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/parse.d.ts +11 -0
- package/dist/parse.d.ts.map +1 -0
- package/dist/parse.js +19 -0
- package/dist/parse.js.map +1 -0
- package/package.json +44 -5
- package/src/Bot.ts +702 -0
- package/src/RateLimiter.ts +76 -0
- package/src/index.ts +3 -0
- package/src/parse.ts +27 -0
package/src/Bot.ts
ADDED
|
@@ -0,0 +1,702 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
|
|
3
|
+
import type {
|
|
4
|
+
ChatMessage,
|
|
5
|
+
ChatParticipant,
|
|
6
|
+
ChatSession,
|
|
7
|
+
ChatSessionCloseReason,
|
|
8
|
+
Client,
|
|
9
|
+
Conversation,
|
|
10
|
+
ConversationMessage,
|
|
11
|
+
ConversationObserver,
|
|
12
|
+
JoinOptions,
|
|
13
|
+
ParticipantChange,
|
|
14
|
+
ParticipantLeave,
|
|
15
|
+
Room,
|
|
16
|
+
User,
|
|
17
|
+
} from '@imvu/client';
|
|
18
|
+
|
|
19
|
+
import { parseCommand } from './parse.js';
|
|
20
|
+
import { RateLimiter, type RateLimit } from './RateLimiter.js';
|
|
21
|
+
|
|
22
|
+
/** Who may run a command, lowest to highest. Each level includes the ones below it. */
|
|
23
|
+
export type Role = 'everyone' | 'moderator' | 'owner' | 'admin';
|
|
24
|
+
const RANK: Record<Role, number> = { everyone: 0, moderator: 1, owner: 2, admin: 3 };
|
|
25
|
+
|
|
26
|
+
/** Where a message came from: a room, or an IM conversation. Check `source.type`. */
|
|
27
|
+
export type MessageSource = BotRoom | BotConversation;
|
|
28
|
+
export type SourceType = MessageSource['type'];
|
|
29
|
+
|
|
30
|
+
export interface BotOptions {
|
|
31
|
+
client: Client;
|
|
32
|
+
/** Command prefix. Default `!`. */
|
|
33
|
+
prefix?: string;
|
|
34
|
+
/** Bot operators: allowed every command everywhere. */
|
|
35
|
+
admins?: Array<string | number>;
|
|
36
|
+
/** Outgoing chat budget per room. Default 3 lines per 5 s. */
|
|
37
|
+
rateLimit?: RateLimit;
|
|
38
|
+
/** Outgoing chat budget for the whole account, across all rooms. Default 20 lines per 10 s. */
|
|
39
|
+
globalRateLimit?: RateLimit;
|
|
40
|
+
/** Lines allowed to wait for a room's rate limit before new ones are rejected. Default 20. */
|
|
41
|
+
maxQueue?: number;
|
|
42
|
+
/** Pause between room joins, so joining hundreds of rooms doesn't burst. Default 1.5 s. */
|
|
43
|
+
joinInterval?: number;
|
|
44
|
+
/**
|
|
45
|
+
* Rejoin when the server drops the bot (expired presence, network). Default `true`.
|
|
46
|
+
* `afterBoot` also rejoins after being booted (default `false`; staying out is polite).
|
|
47
|
+
*/
|
|
48
|
+
rejoin?: boolean | { afterBoot?: boolean; delays?: number[] };
|
|
49
|
+
/** Register a built-in `help` command. Default `true`. */
|
|
50
|
+
help?: boolean;
|
|
51
|
+
/** How long a room's moderator list is trusted before re-reading it. Default 5 min. */
|
|
52
|
+
moderatorCacheMs?: number;
|
|
53
|
+
/** Passed to every `room.join()`. */
|
|
54
|
+
join?: JoinOptions;
|
|
55
|
+
/** Answer IMs (private and group conversations) as well as room chat. Default `true`. */
|
|
56
|
+
ims?: boolean;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** A chat line the bot received, with its author resolved. */
|
|
60
|
+
export interface BotMessage {
|
|
61
|
+
text: string;
|
|
62
|
+
/** The sender. Resolved from the cache (participant reads embed users), fetched only on a miss. */
|
|
63
|
+
author: User;
|
|
64
|
+
/** The sender's presence in the room; null for IMs, and when not known yet. */
|
|
65
|
+
participant: ChatParticipant | null;
|
|
66
|
+
source: MessageSource;
|
|
67
|
+
/** `/me …` narration. */
|
|
68
|
+
action: boolean;
|
|
69
|
+
/** Whispered to the bot rather than said publicly. Always false for IMs. */
|
|
70
|
+
whisper: boolean;
|
|
71
|
+
receivedAt: Date;
|
|
72
|
+
/** The underlying room chat line or IM. */
|
|
73
|
+
raw: ChatMessage | ConversationMessage;
|
|
74
|
+
/** Answer in kind: a whisper gets a whisper back, public chat a public reply. */
|
|
75
|
+
reply(text: string): Promise<void>;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The source type for a `type`: `SourceOf<'room'>` is `BotRoom`. */
|
|
79
|
+
export type SourceOf<T extends SourceType> = Extract<MessageSource, { type: T }>;
|
|
80
|
+
|
|
81
|
+
export interface CommandOptions<T extends SourceType = SourceType> {
|
|
82
|
+
description?: string;
|
|
83
|
+
/** Shown by `help <command>`, e.g. `<user> [reason]`. */
|
|
84
|
+
usage?: string;
|
|
85
|
+
aliases?: string[];
|
|
86
|
+
/** Minimum role, or a custom check. Default `'everyone'`. */
|
|
87
|
+
permission?: Role | ((context: CommandContext<SourceOf<T>>) => boolean | Promise<boolean>);
|
|
88
|
+
/** Per-user cooldown in milliseconds (per source). */
|
|
89
|
+
cooldown?: number;
|
|
90
|
+
/**
|
|
91
|
+
* Where the command may run. Default: everywhere. Also narrows `ctx.source` in the
|
|
92
|
+
* handler: with `['room']` it is a `BotRoom`.
|
|
93
|
+
*/
|
|
94
|
+
sources?: T[];
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export type CommandHandler<S extends MessageSource = MessageSource> = (
|
|
98
|
+
context: CommandContext<S>
|
|
99
|
+
) => void | Promise<void>;
|
|
100
|
+
export type Middleware = (context: CommandContext, next: () => Promise<void>) => void | Promise<void>;
|
|
101
|
+
|
|
102
|
+
export interface CommandContext<S extends MessageSource = MessageSource> {
|
|
103
|
+
bot: Bot;
|
|
104
|
+
message: BotMessage;
|
|
105
|
+
source: S;
|
|
106
|
+
author: User;
|
|
107
|
+
participant: ChatParticipant | null;
|
|
108
|
+
/** The canonical command name (not the alias that was typed). */
|
|
109
|
+
command: string;
|
|
110
|
+
args: string[];
|
|
111
|
+
argText: string;
|
|
112
|
+
/** The author's role in this source. */
|
|
113
|
+
role: Role;
|
|
114
|
+
reply(text: string): Promise<void>;
|
|
115
|
+
/** Whisper the author. */
|
|
116
|
+
whisper(text: string): Promise<void>;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
interface Command {
|
|
120
|
+
name: string;
|
|
121
|
+
options: CommandOptions;
|
|
122
|
+
handler: CommandHandler;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export interface JoinFailure {
|
|
126
|
+
target: Room | string;
|
|
127
|
+
error: Error;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export interface BotEvents {
|
|
131
|
+
message: [message: BotMessage];
|
|
132
|
+
roomJoin: [room: BotRoom];
|
|
133
|
+
/** The bot is out of the room for good (booted, or rejoining failed). Not emitted for `leave()`. */
|
|
134
|
+
roomLeave: [room: BotRoom, reason: ChatSessionCloseReason];
|
|
135
|
+
roomRejoin: [room: BotRoom];
|
|
136
|
+
booted: [room: BotRoom, by: string];
|
|
137
|
+
participantJoin: [participant: ChatParticipant, room: BotRoom];
|
|
138
|
+
participantLeave: [event: ParticipantLeave, room: BotRoom];
|
|
139
|
+
participantUpdate: [participant: ChatParticipant, changes: ParticipantChange[], room: BotRoom];
|
|
140
|
+
/** A command was refused for lack of permission. */
|
|
141
|
+
denied: [context: CommandContext];
|
|
142
|
+
commandError: [error: Error, context: CommandContext];
|
|
143
|
+
error: [error: Error, source?: MessageSource];
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** One room the bot is in (the IMVU counterpart of a discord.js guild). Survives rejoins. */
|
|
147
|
+
export class BotRoom {
|
|
148
|
+
public readonly type = 'room' as const;
|
|
149
|
+
readonly #limiter: RateLimiter;
|
|
150
|
+
#moderators?: { ids: Set<string>; at: number };
|
|
151
|
+
#ownerId?: string;
|
|
152
|
+
|
|
153
|
+
public constructor(
|
|
154
|
+
private readonly bot: Bot,
|
|
155
|
+
public readonly room: Room,
|
|
156
|
+
public session: ChatSession,
|
|
157
|
+
limit: RateLimit,
|
|
158
|
+
maxQueue: number
|
|
159
|
+
) {
|
|
160
|
+
this.#limiter = new RateLimiter(limit, maxQueue);
|
|
161
|
+
Object.defineProperty(this, 'bot', { enumerable: false });
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
public get id(): string {
|
|
165
|
+
return this.room.id;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
public get name(): string {
|
|
169
|
+
return this.room.name;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Everyone present, by user id (the counterpart of `guild.members.cache`). A live view, not a copy. */
|
|
173
|
+
public get participants(): ReadonlyMap<string, ChatParticipant> {
|
|
174
|
+
return this.session.participants;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
public participant(userId: string | number): ChatParticipant | undefined {
|
|
178
|
+
return this.session.participant(userId);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Say something in public chat (rate limited per room and per account). */
|
|
182
|
+
public say(text: string): Promise<void> {
|
|
183
|
+
return this.#limiter.schedule(() => this.bot._send(() => this.session.send(text)));
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Whisper one participant (rate limited). */
|
|
187
|
+
public whisper(userId: string | number, text: string): Promise<void> {
|
|
188
|
+
return this.#limiter.schedule(() => this.bot._send(() => this.session.whisper(userId, text)));
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Boot a participant. Needs owner or moderator rights in the room. */
|
|
192
|
+
public boot(userId: string | number): Promise<void> {
|
|
193
|
+
return this.#limiter.schedule(() => this.bot._send(() => this.session.boot(userId)));
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** The highest role `userId` holds here. */
|
|
197
|
+
public async roleOf(userId: string | number): Promise<Role> {
|
|
198
|
+
const id = String(userId);
|
|
199
|
+
if (this.bot.isAdmin(id)) return 'admin';
|
|
200
|
+
if (id === (await this.ownerId())) return 'owner';
|
|
201
|
+
if ((await this.moderatorIds()).has(id)) return 'moderator';
|
|
202
|
+
return 'everyone';
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
public leave(): Promise<void> {
|
|
206
|
+
return this.bot.leave(this.id);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** @internal */
|
|
210
|
+
public _stop(): void {
|
|
211
|
+
this.#limiter.stop();
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
private async ownerId(): Promise<string> {
|
|
215
|
+
if (this.#ownerId === undefined) {
|
|
216
|
+
const owner = this.room.relations.owner;
|
|
217
|
+
this.#ownerId = owner ? await this.bot.client.utils.id(owner) : '';
|
|
218
|
+
}
|
|
219
|
+
return this.#ownerId;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
private async moderatorIds(): Promise<Set<string>> {
|
|
223
|
+
const cached = this.#moderators;
|
|
224
|
+
if (cached && Date.now() - cached.at < this.bot.moderatorCacheMs) return cached.ids;
|
|
225
|
+
|
|
226
|
+
const moderators = await this.room.moderators().catch(() => []);
|
|
227
|
+
const ids = new Set(moderators.map((user) => user.id));
|
|
228
|
+
this.#moderators = { ids, at: Date.now() };
|
|
229
|
+
return ids;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* One IM conversation the bot is part of (the counterpart of a discord.js DM channel,
|
|
235
|
+
* or a group DM). Created when its first message arrives.
|
|
236
|
+
*/
|
|
237
|
+
export class BotConversation {
|
|
238
|
+
public readonly type = 'conversation' as const;
|
|
239
|
+
readonly #limiter: RateLimiter;
|
|
240
|
+
|
|
241
|
+
public constructor(
|
|
242
|
+
private readonly bot: Bot,
|
|
243
|
+
public conversation: Conversation,
|
|
244
|
+
limit: RateLimit,
|
|
245
|
+
maxQueue: number
|
|
246
|
+
) {
|
|
247
|
+
this.#limiter = new RateLimiter(limit, maxQueue);
|
|
248
|
+
Object.defineProperty(this, 'bot', { enumerable: false });
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
public get id(): string {
|
|
252
|
+
return this.conversation.id;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** The other members' names, e.g. for logs. */
|
|
256
|
+
public get name(): string {
|
|
257
|
+
return this.conversation
|
|
258
|
+
.others(this.bot.client.rest.cid)
|
|
259
|
+
.map((member) => member.name)
|
|
260
|
+
.join(', ');
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** True for a conversation with more than one other person. */
|
|
264
|
+
public get group(): boolean {
|
|
265
|
+
return this.conversation.others(this.bot.client.rest.cid).length > 1;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** Send a message to the conversation (rate limited per conversation and per account). */
|
|
269
|
+
public say(text: string): Promise<void> {
|
|
270
|
+
return this.#limiter.schedule(() => this.bot._send(() => this.conversation.send(text)));
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Message one member privately: the conversation itself when it is one-to-one, a
|
|
275
|
+
* separate one-to-one IM when it is a group.
|
|
276
|
+
*/
|
|
277
|
+
public whisper(userId: string | number, text: string): Promise<void> {
|
|
278
|
+
if (!this.group) return this.say(text);
|
|
279
|
+
return this.#limiter.schedule(() => this.bot._send(() => this.bot.client.account.conversations.send(userId, text)));
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** In IMs there are no room roles: bot admins are `admin`, everyone else `everyone`. */
|
|
283
|
+
public async roleOf(userId: string | number): Promise<Role> {
|
|
284
|
+
return this.bot.isAdmin(userId) ? 'admin' : 'everyone';
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** Conversations have no participants in the room sense. */
|
|
288
|
+
public participant(): undefined {
|
|
289
|
+
return undefined;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** @internal */
|
|
293
|
+
public _stop(): void {
|
|
294
|
+
this.#limiter.stop();
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** What the bot heard, from either source, before its author is resolved. */
|
|
299
|
+
interface Incoming {
|
|
300
|
+
userId: string;
|
|
301
|
+
text: string;
|
|
302
|
+
action: boolean;
|
|
303
|
+
whisper: boolean;
|
|
304
|
+
toMe: boolean;
|
|
305
|
+
receivedAt: Date;
|
|
306
|
+
raw: ChatMessage | ConversationMessage;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* A chat bot for any number of rooms and IM conversations: routes `!commands` to handlers with permissions,
|
|
311
|
+
* cooldowns and middleware, rate-limits what it says per room and per account, paces
|
|
312
|
+
* its joins, and rejoins when the server drops it.
|
|
313
|
+
*
|
|
314
|
+
* ```ts
|
|
315
|
+
* const bot = new Bot({ client, admins: [myCid] });
|
|
316
|
+
* bot.command('ping', (ctx) => ctx.reply('pong'));
|
|
317
|
+
* await bot.joinAll(roomIds);
|
|
318
|
+
* ```
|
|
319
|
+
*/
|
|
320
|
+
export class Bot extends EventEmitter<BotEvents> {
|
|
321
|
+
public readonly client: Client;
|
|
322
|
+
public readonly prefix: string;
|
|
323
|
+
/** @internal */
|
|
324
|
+
public readonly moderatorCacheMs: number;
|
|
325
|
+
|
|
326
|
+
readonly #rooms = new Map<string, BotRoom>();
|
|
327
|
+
readonly #commands = new Map<string, Command>();
|
|
328
|
+
readonly #aliases = new Map<string, string>();
|
|
329
|
+
readonly #middleware: Middleware[] = [];
|
|
330
|
+
readonly #cooldowns = new Map<string, number>();
|
|
331
|
+
readonly #dispatch = new WeakMap<MessageSource, Promise<void>>();
|
|
332
|
+
readonly #admins: Set<string>;
|
|
333
|
+
readonly #options: BotOptions;
|
|
334
|
+
readonly #global: RateLimiter;
|
|
335
|
+
readonly #joining = new Map<string, Promise<BotRoom>>();
|
|
336
|
+
readonly #conversations = new Map<string, BotConversation>();
|
|
337
|
+
#ims?: Promise<ConversationObserver | undefined>;
|
|
338
|
+
#joinQueue: Promise<unknown> = Promise.resolve();
|
|
339
|
+
#lastJoinAt = 0;
|
|
340
|
+
|
|
341
|
+
public constructor(options: BotOptions) {
|
|
342
|
+
super();
|
|
343
|
+
this.client = options.client;
|
|
344
|
+
this.prefix = options.prefix ?? '!';
|
|
345
|
+
this.moderatorCacheMs = options.moderatorCacheMs ?? 5 * 60_000;
|
|
346
|
+
this.#admins = new Set((options.admins ?? []).map(String));
|
|
347
|
+
this.#options = options;
|
|
348
|
+
this.#global = new RateLimiter(options.globalRateLimit ?? { messages: 20, perMs: 10_000 }, Infinity);
|
|
349
|
+
|
|
350
|
+
if (options.help ?? true) {
|
|
351
|
+
this.command('help', { description: 'List commands, or explain one', usage: '[command]' }, (context) =>
|
|
352
|
+
this.help(context)
|
|
353
|
+
);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** The rooms the bot is in, by room id (the counterpart of `client.guilds.cache`). */
|
|
358
|
+
public get rooms(): ReadonlyMap<string, BotRoom> {
|
|
359
|
+
return this.#rooms;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** IM conversations the bot has heard from, by conversation id. */
|
|
363
|
+
public get conversations(): ReadonlyMap<string, BotConversation> {
|
|
364
|
+
return this.#conversations;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* Start answering IMs (unless `ims: false`). Joining a room does this too, so call
|
|
369
|
+
* it yourself only for a bot that is in no rooms. Safe to call more than once.
|
|
370
|
+
*/
|
|
371
|
+
public async start(): Promise<void> {
|
|
372
|
+
this.#ims ??= this.startIms();
|
|
373
|
+
await this.#ims;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
public isAdmin(userId: string | number): boolean {
|
|
377
|
+
return this.#admins.has(String(userId));
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
public command(name: string, handler: CommandHandler): this;
|
|
381
|
+
public command<T extends SourceType = SourceType>(
|
|
382
|
+
name: string,
|
|
383
|
+
options: CommandOptions<T>,
|
|
384
|
+
handler: CommandHandler<SourceOf<T>>
|
|
385
|
+
): this;
|
|
386
|
+
public command(
|
|
387
|
+
name: string,
|
|
388
|
+
optionsOrHandler: CommandOptions<any> | CommandHandler<any>,
|
|
389
|
+
maybeHandler?: CommandHandler<any>
|
|
390
|
+
): this {
|
|
391
|
+
// The handler only ever runs for the declared sources, so the narrowed types hold.
|
|
392
|
+
const options = (typeof optionsOrHandler === 'function' ? {} : optionsOrHandler) as CommandOptions;
|
|
393
|
+
const handler = (typeof optionsOrHandler === 'function' ? optionsOrHandler : maybeHandler!) as CommandHandler;
|
|
394
|
+
const key = name.toLowerCase();
|
|
395
|
+
|
|
396
|
+
this.#commands.set(key, { name: key, options, handler });
|
|
397
|
+
for (const alias of options.aliases ?? []) this.#aliases.set(alias.toLowerCase(), key);
|
|
398
|
+
return this;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/** Run `middleware` before every command handler; call `next()` to continue. */
|
|
402
|
+
public use(middleware: Middleware): this {
|
|
403
|
+
this.#middleware.push(middleware);
|
|
404
|
+
return this;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* Join a room by id (e.g. `'123456-1'`) or {@link Room}. Joins are paced by
|
|
409
|
+
* `joinInterval`; joining a room the bot is in (or joining) returns that room.
|
|
410
|
+
*/
|
|
411
|
+
public join(target: Room | string): Promise<BotRoom> {
|
|
412
|
+
const key = typeof target === 'string' ? target : target.id;
|
|
413
|
+
const existing = this.#rooms.get(key);
|
|
414
|
+
if (existing) return Promise.resolve(existing);
|
|
415
|
+
|
|
416
|
+
this.start().catch((error: Error) => this.emitError(error));
|
|
417
|
+
|
|
418
|
+
let pending = this.#joining.get(key);
|
|
419
|
+
if (!pending) {
|
|
420
|
+
pending = this.paced(() => this.joinNow(target)).finally(() => this.#joining.delete(key));
|
|
421
|
+
this.#joining.set(key, pending);
|
|
422
|
+
}
|
|
423
|
+
return pending;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* Join many rooms, paced, without stopping at the first failure. Full rooms
|
|
428
|
+
* (`CHAT_PARTICIPANT-002`), private rooms and missing rooms end up in `failed`.
|
|
429
|
+
*/
|
|
430
|
+
public async joinAll(targets: Iterable<Room | string>): Promise<{ joined: BotRoom[]; failed: JoinFailure[] }> {
|
|
431
|
+
const list = [...targets];
|
|
432
|
+
const results = await Promise.allSettled(list.map((target) => this.join(target)));
|
|
433
|
+
const joined: BotRoom[] = [];
|
|
434
|
+
const failed: JoinFailure[] = [];
|
|
435
|
+
results.forEach((result, index) => {
|
|
436
|
+
if (result.status === 'fulfilled') joined.push(result.value);
|
|
437
|
+
else failed.push({ target: list[index], error: result.reason as Error });
|
|
438
|
+
});
|
|
439
|
+
return { joined, failed };
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
public async leave(roomId: string): Promise<void> {
|
|
443
|
+
const botRoom = this.#rooms.get(roomId);
|
|
444
|
+
if (!botRoom) return;
|
|
445
|
+
this.#rooms.delete(roomId);
|
|
446
|
+
botRoom._stop();
|
|
447
|
+
await botRoom.session.leave();
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** Leave every room and stop answering IMs. */
|
|
451
|
+
public async stop(): Promise<void> {
|
|
452
|
+
const ims = this.#ims;
|
|
453
|
+
this.#ims = undefined;
|
|
454
|
+
(await ims?.catch(() => undefined))?.close();
|
|
455
|
+
for (const conversation of this.#conversations.values()) conversation._stop();
|
|
456
|
+
this.#conversations.clear();
|
|
457
|
+
await Promise.all([...this.#rooms.keys()].map((id) => this.leave(id)));
|
|
458
|
+
this.#global.stop();
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
private async startIms(): Promise<ConversationObserver | undefined> {
|
|
462
|
+
if (this.#options.ims === false) return undefined;
|
|
463
|
+
const observer = await this.client.account.conversations.observe();
|
|
464
|
+
observer.on('message', (message, conversation) => {
|
|
465
|
+
let source = this.#conversations.get(conversation.id);
|
|
466
|
+
if (source) source.conversation = conversation;
|
|
467
|
+
else {
|
|
468
|
+
source = new BotConversation(
|
|
469
|
+
this,
|
|
470
|
+
conversation,
|
|
471
|
+
this.#options.rateLimit ?? { messages: 3, perMs: 5_000 },
|
|
472
|
+
this.#options.maxQueue ?? 20
|
|
473
|
+
);
|
|
474
|
+
this.#conversations.set(conversation.id, source);
|
|
475
|
+
}
|
|
476
|
+
this.enqueue(source, {
|
|
477
|
+
userId: message.senderId,
|
|
478
|
+
text: message.text,
|
|
479
|
+
action: false,
|
|
480
|
+
whisper: false,
|
|
481
|
+
toMe: true,
|
|
482
|
+
receivedAt: new Date(message.created),
|
|
483
|
+
raw: message,
|
|
484
|
+
});
|
|
485
|
+
});
|
|
486
|
+
observer.on('error', (error) => this.emitError(error));
|
|
487
|
+
return observer;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/** @internal Every outgoing line passes the account-wide budget. */
|
|
491
|
+
public _send(task: () => Promise<void>): Promise<void> {
|
|
492
|
+
return this.#global.schedule(task);
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
private paced<T>(task: () => Promise<T>): Promise<T> {
|
|
496
|
+
const run = this.#joinQueue.then(async () => {
|
|
497
|
+
const wait = this.#lastJoinAt + (this.#options.joinInterval ?? 1_500) - Date.now();
|
|
498
|
+
if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait));
|
|
499
|
+
this.#lastJoinAt = Date.now();
|
|
500
|
+
return task();
|
|
501
|
+
});
|
|
502
|
+
this.#joinQueue = run.catch(() => {});
|
|
503
|
+
return run;
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
private async joinNow(target: Room | string): Promise<BotRoom> {
|
|
507
|
+
const room = typeof target === 'string' ? await this.client.rooms.fetch(target) : target;
|
|
508
|
+
if (!room) throw new Error(`Room '${typeof target === 'string' ? target : target.id}' was not found`);
|
|
509
|
+
|
|
510
|
+
const session = await room.join(this.#options.join);
|
|
511
|
+
const botRoom = new BotRoom(
|
|
512
|
+
this,
|
|
513
|
+
room,
|
|
514
|
+
session,
|
|
515
|
+
this.#options.rateLimit ?? { messages: 3, perMs: 5_000 },
|
|
516
|
+
this.#options.maxQueue ?? 20
|
|
517
|
+
);
|
|
518
|
+
this.#rooms.set(room.id, botRoom);
|
|
519
|
+
this.attach(botRoom, session);
|
|
520
|
+
this.emit('roomJoin', botRoom);
|
|
521
|
+
return botRoom;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
private attach(botRoom: BotRoom, session: ChatSession): void {
|
|
525
|
+
session.on('message', (message) => {
|
|
526
|
+
// Whispers between other people are not for us.
|
|
527
|
+
if (message.whisper && !message.toMe) return;
|
|
528
|
+
this.enqueue(botRoom, {
|
|
529
|
+
userId: message.userId,
|
|
530
|
+
text: message.text,
|
|
531
|
+
action: message.action,
|
|
532
|
+
whisper: message.whisper,
|
|
533
|
+
toMe: message.toMe,
|
|
534
|
+
receivedAt: message.receivedAt,
|
|
535
|
+
raw: message,
|
|
536
|
+
});
|
|
537
|
+
});
|
|
538
|
+
session.on('join', (participant) => this.emit('participantJoin', participant, botRoom));
|
|
539
|
+
session.on('leave', (event) => this.emit('participantLeave', event, botRoom));
|
|
540
|
+
session.on('update', (participant, changes) => this.emit('participantUpdate', participant, changes, botRoom));
|
|
541
|
+
session.on('booted', ({ by }) => this.emit('booted', botRoom, by));
|
|
542
|
+
session.on('error', (error) => this.emitError(error, botRoom));
|
|
543
|
+
session.on('close', ({ reason }) => void this.onClose(botRoom, reason));
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
private async onClose(botRoom: BotRoom, reason: ChatSessionCloseReason): Promise<void> {
|
|
547
|
+
// We left on purpose (leave() already removed it), or another BotRoom took its place.
|
|
548
|
+
if (this.#rooms.get(botRoom.id) !== botRoom) return;
|
|
549
|
+
|
|
550
|
+
const rejoin = this.#options.rejoin ?? true;
|
|
551
|
+
const settings = typeof rejoin === 'object' ? rejoin : {};
|
|
552
|
+
const allowed = rejoin !== false && (reason === 'removed' || (reason === 'booted' && settings.afterBoot === true));
|
|
553
|
+
|
|
554
|
+
if (allowed) {
|
|
555
|
+
for (const delay of settings.delays ?? [5_000, 15_000, 60_000]) {
|
|
556
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
557
|
+
if (this.#rooms.get(botRoom.id) !== botRoom) return;
|
|
558
|
+
try {
|
|
559
|
+
const session = await this.paced(() => botRoom.room.join(this.#options.join));
|
|
560
|
+
botRoom.session = session;
|
|
561
|
+
this.attach(botRoom, session);
|
|
562
|
+
this.emit('roomRejoin', botRoom);
|
|
563
|
+
return;
|
|
564
|
+
} catch (error) {
|
|
565
|
+
this.emitError(error as Error, botRoom);
|
|
566
|
+
// A definite refusal (e.g. "Not authorized" after the room removed us) will not
|
|
567
|
+
// change on retry; a full room might.
|
|
568
|
+
const code = (error as { apiCode?: unknown }).apiCode;
|
|
569
|
+
if (typeof code === 'string' && code !== 'CHAT_PARTICIPANT-002') break;
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
this.#rooms.delete(botRoom.id);
|
|
575
|
+
botRoom._stop();
|
|
576
|
+
this.emit('roomLeave', botRoom, reason);
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/**
|
|
580
|
+
* Messages are handled in arrival order per source (author and role lookups are
|
|
581
|
+
* async), then each command handler runs on its own so a slow one doesn't hold up
|
|
582
|
+
* the next.
|
|
583
|
+
*/
|
|
584
|
+
private enqueue(source: MessageSource, incoming: Incoming): void {
|
|
585
|
+
const previous = this.#dispatch.get(source) ?? Promise.resolve();
|
|
586
|
+
this.#dispatch.set(
|
|
587
|
+
source,
|
|
588
|
+
previous.then(() => this.onMessage(source, incoming))
|
|
589
|
+
);
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
private async onMessage(source: MessageSource, incoming: Incoming): Promise<void> {
|
|
593
|
+
try {
|
|
594
|
+
const author = this.client.users.resolve(incoming.userId) ?? (await this.client.users.fetch(incoming.userId));
|
|
595
|
+
if (!author) throw new Error(`Could not resolve the author ${incoming.userId}`);
|
|
596
|
+
|
|
597
|
+
const message: BotMessage = {
|
|
598
|
+
text: incoming.text,
|
|
599
|
+
author,
|
|
600
|
+
participant: source.participant(incoming.userId) ?? null,
|
|
601
|
+
source,
|
|
602
|
+
action: incoming.action,
|
|
603
|
+
whisper: incoming.whisper,
|
|
604
|
+
receivedAt: incoming.receivedAt,
|
|
605
|
+
raw: incoming.raw,
|
|
606
|
+
// Rooms: a whisper is answered with a whisper. IMs: the answer goes to the conversation.
|
|
607
|
+
reply: (text) =>
|
|
608
|
+
source.type === 'room' && incoming.toMe ? source.whisper(incoming.userId, text) : source.say(text),
|
|
609
|
+
};
|
|
610
|
+
this.emit('message', message);
|
|
611
|
+
await this.dispatchCommand(message);
|
|
612
|
+
} catch (error) {
|
|
613
|
+
this.emitError(error as Error, source);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
private async dispatchCommand(message: BotMessage): Promise<void> {
|
|
618
|
+
const parsed = parseCommand(message.text, this.prefix);
|
|
619
|
+
if (!parsed) return;
|
|
620
|
+
const command = this.#commands.get(this.#aliases.get(parsed.name) ?? parsed.name);
|
|
621
|
+
if (!command) return;
|
|
622
|
+
if (command.options.sources && !command.options.sources.includes(message.source.type)) return;
|
|
623
|
+
|
|
624
|
+
const context: CommandContext = {
|
|
625
|
+
bot: this,
|
|
626
|
+
message,
|
|
627
|
+
source: message.source,
|
|
628
|
+
author: message.author,
|
|
629
|
+
participant: message.participant,
|
|
630
|
+
command: command.name,
|
|
631
|
+
args: parsed.args,
|
|
632
|
+
argText: parsed.argText,
|
|
633
|
+
role: await message.source.roleOf(message.author.id),
|
|
634
|
+
reply: (text) => message.reply(text),
|
|
635
|
+
whisper: (text) => message.source.whisper(message.author.id, text),
|
|
636
|
+
};
|
|
637
|
+
|
|
638
|
+
if (!(await this.permitted(command, context))) {
|
|
639
|
+
this.emit('denied', context);
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
if (this.coolingDown(command, context)) return;
|
|
643
|
+
|
|
644
|
+
void this.run(command, context);
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
private async run(command: Command, context: CommandContext): Promise<void> {
|
|
648
|
+
const step = async (index: number): Promise<void> => {
|
|
649
|
+
const middleware = this.#middleware[index];
|
|
650
|
+
if (middleware) await middleware(context, () => step(index + 1));
|
|
651
|
+
else await command.handler(context);
|
|
652
|
+
};
|
|
653
|
+
try {
|
|
654
|
+
await step(0);
|
|
655
|
+
} catch (error) {
|
|
656
|
+
if (this.listenerCount('commandError') > 0) this.emit('commandError', error as Error, context);
|
|
657
|
+
else this.emitError(error as Error, context.source);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
private async permitted(command: Command, context: CommandContext): Promise<boolean> {
|
|
662
|
+
const permission = command.options.permission ?? 'everyone';
|
|
663
|
+
if (typeof permission === 'function') return permission(context);
|
|
664
|
+
return RANK[context.role] >= RANK[permission];
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
private coolingDown(command: Command, context: CommandContext): boolean {
|
|
668
|
+
const cooldown = command.options.cooldown;
|
|
669
|
+
if (!cooldown || context.role === 'admin') return false;
|
|
670
|
+
|
|
671
|
+
const key = `${context.source.type}:${context.source.id}\0${command.name}\0${context.author.id}`;
|
|
672
|
+
const now = Date.now();
|
|
673
|
+
const last = this.#cooldowns.get(key);
|
|
674
|
+
if (last !== undefined && now - last < cooldown) return true;
|
|
675
|
+
this.#cooldowns.set(key, now);
|
|
676
|
+
return false;
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
private async help(context: CommandContext): Promise<void> {
|
|
680
|
+
const name = context.args[0]?.replace(this.prefix, '').toLowerCase();
|
|
681
|
+
if (name) {
|
|
682
|
+
const command = this.#commands.get(this.#aliases.get(name) ?? name);
|
|
683
|
+
if (!command) return context.reply(`No command "${name}".`);
|
|
684
|
+
const usage = command.options.usage ? ` ${command.options.usage}` : '';
|
|
685
|
+
const description = command.options.description ? ` — ${command.options.description}` : '';
|
|
686
|
+
return context.reply(`${this.prefix}${command.name}${usage}${description}`);
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
const visible: string[] = [];
|
|
690
|
+
for (const command of this.#commands.values()) {
|
|
691
|
+
if (command.options.sources && !command.options.sources.includes(context.source.type)) continue;
|
|
692
|
+
const permission = command.options.permission ?? 'everyone';
|
|
693
|
+
if (typeof permission === 'string' && RANK[context.role] < RANK[permission]) continue;
|
|
694
|
+
visible.push(`${this.prefix}${command.name}`);
|
|
695
|
+
}
|
|
696
|
+
return context.reply(`Commands: ${visible.join(', ')}`);
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
private emitError(error: Error, source?: MessageSource): void {
|
|
700
|
+
if (this.listenerCount('error') > 0) this.emit('error', error, source);
|
|
701
|
+
}
|
|
702
|
+
}
|