@fluxerjs/core 1.2.4 → 1.3.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.
@@ -0,0 +1,484 @@
1
+ // src/structures/Base.ts
2
+ var Base = class {
3
+ };
4
+
5
+ // src/structures/Message.ts
6
+ import { Collection as Collection2 } from "@fluxerjs/collection";
7
+ import { MessageType, MessageFlags, Routes } from "@fluxerjs/types";
8
+ import { EmbedBuilder as EmbedBuilder2 } from "@fluxerjs/builders";
9
+
10
+ // src/util/messageUtils.ts
11
+ import { EmbedBuilder } from "@fluxerjs/builders";
12
+
13
+ // src/errors/ErrorCodes.ts
14
+ import { ErrorCodes } from "@fluxerjs/util";
15
+
16
+ // src/errors/FluxerError.ts
17
+ import { FluxerError } from "@fluxerjs/util";
18
+
19
+ // src/util/messageUtils.ts
20
+ var FILE_FETCH_TIMEOUT_MS = 3e4;
21
+ async function resolveMessageFiles(files) {
22
+ const result = [];
23
+ for (let i = 0; i < files.length; i++) {
24
+ const f = files[i];
25
+ const filename = f.filename ?? f.name;
26
+ if ("url" in f && f.url) {
27
+ if (!URL.canParse(f.url)) {
28
+ throw new FluxerError(`Invalid file URL at index ${i}: ${f.url}`, {
29
+ code: ErrorCodes.InvalidFileUrl
30
+ });
31
+ }
32
+ let res;
33
+ try {
34
+ res = await fetch(f.url, {
35
+ signal: AbortSignal.timeout(FILE_FETCH_TIMEOUT_MS)
36
+ });
37
+ } catch (err) {
38
+ throw new FluxerError(`Failed to fetch file from ${f.url}`, {
39
+ code: ErrorCodes.FileFetchFailed,
40
+ cause: err instanceof Error ? err : void 0
41
+ });
42
+ }
43
+ if (!res.ok) {
44
+ throw new FluxerError(
45
+ `Failed to fetch file from ${f.url}: ${res.status} ${res.statusText}`,
46
+ {
47
+ code: ErrorCodes.FileFetchFailed
48
+ }
49
+ );
50
+ }
51
+ const data = await res.arrayBuffer();
52
+ result.push({ name: f.name, data, filename });
53
+ } else if ("data" in f && f.data != null) {
54
+ result.push({ name: f.name, data: f.data, filename });
55
+ } else {
56
+ throw new FluxerError(`File at index ${i} must have either "data" or "url"`, {
57
+ code: ErrorCodes.InvalidAttachment
58
+ });
59
+ }
60
+ }
61
+ return result;
62
+ }
63
+ function buildSendBody(options) {
64
+ const body = typeof options === "string" ? { content: options } : options;
65
+ const result = {};
66
+ if (body.content !== void 0) result.content = body.content;
67
+ if (body.embeds?.length) {
68
+ result.embeds = body.embeds.map((e) => e instanceof EmbedBuilder ? e.toJSON() : e);
69
+ }
70
+ if (body.files?.length && body.attachments) {
71
+ result.attachments = body.attachments.map((a) => ({
72
+ id: a.id,
73
+ filename: a.filename,
74
+ ...a.title != null && { title: a.title },
75
+ ...a.description != null && { description: a.description },
76
+ ...a.flags != null && { flags: a.flags }
77
+ }));
78
+ } else if (body.files?.length) {
79
+ result.attachments = body.files.map((f, i) => ({
80
+ id: i,
81
+ filename: f.filename ?? f.name
82
+ }));
83
+ }
84
+ if (body.flags !== void 0) result.flags = body.flags;
85
+ return result;
86
+ }
87
+
88
+ // src/util/ReactionCollector.ts
89
+ import { EventEmitter } from "events";
90
+ import { Collection } from "@fluxerjs/collection";
91
+
92
+ // src/util/Events.ts
93
+ var Events = {
94
+ Ready: "ready",
95
+ MessageCreate: "messageCreate",
96
+ MessageUpdate: "messageUpdate",
97
+ MessageDelete: "messageDelete",
98
+ MessageDeleteBulk: "messageDeleteBulk",
99
+ MessageReactionAdd: "messageReactionAdd",
100
+ MessageReactionRemove: "messageReactionRemove",
101
+ MessageReactionRemoveAll: "messageReactionRemoveAll",
102
+ MessageReactionRemoveEmoji: "messageReactionRemoveEmoji",
103
+ InteractionCreate: "interactionCreate",
104
+ GuildCreate: "guildCreate",
105
+ GuildUpdate: "guildUpdate",
106
+ GuildDelete: "guildDelete",
107
+ GuildBanAdd: "guildBanAdd",
108
+ GuildBanRemove: "guildBanRemove",
109
+ GuildEmojisUpdate: "guildEmojisUpdate",
110
+ GuildStickersUpdate: "guildStickersUpdate",
111
+ GuildIntegrationsUpdate: "guildIntegrationsUpdate",
112
+ GuildMemberAdd: "guildMemberAdd",
113
+ GuildMemberUpdate: "guildMemberUpdate",
114
+ GuildMemberRemove: "guildMemberRemove",
115
+ GuildMembersChunk: "guildMembersChunk",
116
+ GuildRoleCreate: "guildRoleCreate",
117
+ GuildRoleUpdate: "guildRoleUpdate",
118
+ GuildRoleDelete: "guildRoleDelete",
119
+ GuildScheduledEventCreate: "guildScheduledEventCreate",
120
+ GuildScheduledEventUpdate: "guildScheduledEventUpdate",
121
+ GuildScheduledEventDelete: "guildScheduledEventDelete",
122
+ ChannelCreate: "channelCreate",
123
+ ChannelUpdate: "channelUpdate",
124
+ ChannelDelete: "channelDelete",
125
+ ChannelPinsUpdate: "channelPinsUpdate",
126
+ InviteCreate: "inviteCreate",
127
+ InviteDelete: "inviteDelete",
128
+ TypingStart: "typingStart",
129
+ UserUpdate: "userUpdate",
130
+ PresenceUpdate: "presenceUpdate",
131
+ VoiceStateUpdate: "voiceStateUpdate",
132
+ VoiceServerUpdate: "voiceServerUpdate",
133
+ VoiceStatesSync: "voiceStatesSync",
134
+ WebhooksUpdate: "webhooksUpdate",
135
+ Resumed: "resumed",
136
+ Error: "error",
137
+ Debug: "debug"
138
+ };
139
+
140
+ // src/util/ReactionCollector.ts
141
+ var ReactionCollector = class extends EventEmitter {
142
+ client;
143
+ messageId;
144
+ channelId;
145
+ options;
146
+ collected = new Collection();
147
+ _timeout = null;
148
+ _ended = false;
149
+ _listener;
150
+ constructor(client, messageId, channelId, options = {}) {
151
+ super();
152
+ this.client = client;
153
+ this.messageId = messageId;
154
+ this.channelId = channelId;
155
+ this.options = {
156
+ filter: options.filter ?? (() => true),
157
+ time: options.time ?? 0,
158
+ max: options.max ?? 0
159
+ };
160
+ this._listener = (reaction, user, _msgId, chId, _emoji, userId) => {
161
+ if (this._ended || reaction.messageId !== this.messageId || chId !== this.channelId) return;
162
+ if (!this.options.filter(reaction, user)) return;
163
+ const key = `${userId}:${reaction.emoji.id ?? reaction.emoji.name}`;
164
+ this.collected.set(key, { reaction, user });
165
+ this.emit("collect", reaction, user);
166
+ if (this.options.max > 0 && this.collected.size >= this.options.max) {
167
+ this.stop("limit");
168
+ }
169
+ };
170
+ this.client.on(Events.MessageReactionAdd, this._listener);
171
+ if (this.options.time > 0) {
172
+ this._timeout = setTimeout(() => this.stop("time"), this.options.time);
173
+ }
174
+ }
175
+ stop(reason = "user") {
176
+ if (this._ended) return;
177
+ this._ended = true;
178
+ this.client.off(Events.MessageReactionAdd, this._listener);
179
+ if (this._timeout) {
180
+ clearTimeout(this._timeout);
181
+ this._timeout = null;
182
+ }
183
+ this.emit("end", this.collected, reason);
184
+ }
185
+ on(event, listener) {
186
+ return super.on(event, listener);
187
+ }
188
+ emit(event, ...args) {
189
+ return super.emit(event, ...args);
190
+ }
191
+ };
192
+
193
+ // src/structures/Message.ts
194
+ var Message = class _Message extends Base {
195
+ client;
196
+ id;
197
+ channelId;
198
+ guildId;
199
+ author;
200
+ content;
201
+ createdAt;
202
+ editedAt;
203
+ pinned;
204
+ attachments;
205
+ type;
206
+ flags;
207
+ mentionEveryone;
208
+ tts;
209
+ embeds;
210
+ stickers;
211
+ reactions;
212
+ messageReference;
213
+ messageSnapshots;
214
+ call;
215
+ referencedMessage;
216
+ /** Webhook ID if this message was sent via webhook. Null otherwise. */
217
+ webhookId;
218
+ /** Users mentioned in this message. */
219
+ mentions;
220
+ /** Role IDs mentioned in this message. */
221
+ mentionRoles;
222
+ /** Client-side nonce for acknowledgment. Null if not provided. */
223
+ nonce;
224
+ /**
225
+ * Channel where this message was sent. Resolved from cache; null if not cached.
226
+ * Messages can only exist in text-based channels (text, DM, announcement), so this always has send() when non-null.
227
+ */
228
+ get channel() {
229
+ return this.client.channels.get(this.channelId) ?? null;
230
+ }
231
+ /** Guild where this message was sent. Resolved from cache; null for DMs or if not cached. */
232
+ get guild() {
233
+ return this.guildId ? this.client.guilds.get(this.guildId) ?? null : null;
234
+ }
235
+ /**
236
+ * Resolve the channel (from cache or API). Use when you need the channel and it may not be cached.
237
+ * @returns The channel
238
+ * @throws FluxerError with CHANNEL_NOT_FOUND if the channel does not exist
239
+ */
240
+ async resolveChannel() {
241
+ return this.client.channels.resolve(this.channelId);
242
+ }
243
+ /**
244
+ * Resolve the guild (from cache or API). Returns null for DMs.
245
+ * @returns The guild, or null if this is a DM or guild not found
246
+ */
247
+ async resolveGuild() {
248
+ return this.guildId ? this.client.guilds.resolve(this.guildId) : null;
249
+ }
250
+ /** @param data - API message from POST/PATCH /channels/{id}/messages or gateway MESSAGE_CREATE */
251
+ constructor(client, data) {
252
+ super();
253
+ this.client = client;
254
+ this.id = data.id;
255
+ this.channelId = data.channel_id;
256
+ this.guildId = data.guild_id ?? null;
257
+ this.author = client.getOrCreateUser(data.author);
258
+ this.content = data.content;
259
+ this.createdAt = new Date(data.timestamp);
260
+ this.editedAt = data.edited_timestamp ? new Date(data.edited_timestamp) : null;
261
+ this.pinned = data.pinned;
262
+ this.attachments = new Collection2();
263
+ for (const a of data.attachments ?? []) this.attachments.set(a.id, a);
264
+ this.type = data.type ?? MessageType.Default;
265
+ this.flags = data.flags ?? 0;
266
+ this.mentionEveryone = data.mention_everyone ?? false;
267
+ this.tts = data.tts ?? false;
268
+ this.embeds = data.embeds ?? [];
269
+ this.stickers = data.stickers ?? [];
270
+ this.reactions = data.reactions ?? [];
271
+ this.messageReference = data.message_reference ?? null;
272
+ this.messageSnapshots = data.message_snapshots ?? [];
273
+ this.call = data.call ?? null;
274
+ this.referencedMessage = data.referenced_message ? new _Message(client, data.referenced_message) : null;
275
+ this.webhookId = data.webhook_id ?? null;
276
+ this.mentions = (data.mentions ?? []).map((u) => client.getOrCreateUser(u));
277
+ this.mentionRoles = data.mention_roles ?? [];
278
+ this.nonce = data.nonce ?? null;
279
+ }
280
+ /**
281
+ * Send a message to this channel without replying. Use when you want a standalone message.
282
+ * @param options - Text content or object with content, embeds, and/or files
283
+ * @example
284
+ * await message.send('Pong!');
285
+ * await message.send({ embeds: [embed] }); // EmbedBuilder auto-converted
286
+ * await message.send({ content: 'File', files: [{ name: 'data.txt', data }] });
287
+ */
288
+ async send(options) {
289
+ const payload = await _Message._createMessageBody(options);
290
+ return this._send(payload);
291
+ }
292
+ /**
293
+ * Send a message to a specific channel. Use for logging, forwarding, or sending to another channel in the guild.
294
+ * @param channelId - Snowflake of the target channel (e.g. log channel ID)
295
+ * @param options - Text content or object with content and/or embeds
296
+ * @example
297
+ * await message.sendTo(logChannelId, 'User ' + message.author.username + ' said: ' + message.content);
298
+ * await message.sendTo(announceChannelId, { embeds: [embed] });
299
+ */
300
+ async sendTo(channelId, options) {
301
+ return this.client.channels.send(channelId, options);
302
+ }
303
+ /**
304
+ * Reply to this message (shows as a reply in the client).
305
+ * @param options - Text content or object with content, embeds, and/or reply options (ping, replyTo)
306
+ * @example
307
+ * await message.reply('Pong!');
308
+ * await message.reply({ embeds: [embed] });
309
+ * await message.reply('No ping!', { ping: false });
310
+ * await message.reply({ content: 'Reply to other', replyTo: otherMessage });
311
+ */
312
+ async reply(options, replyOptions) {
313
+ const opts = typeof options === "string" ? { content: options } : options;
314
+ const mergedReply = replyOptions ?? (opts.ping !== void 0 || opts.replyTo !== void 0) ? { ping: opts.ping, replyTo: opts.replyTo } : void 0;
315
+ const refMessage = mergedReply?.replyTo ?? this;
316
+ const ref = refMessage instanceof _Message ? {
317
+ channel_id: refMessage.channelId,
318
+ message_id: refMessage.id,
319
+ guild_id: refMessage.guildId ?? void 0
320
+ } : {
321
+ channel_id: refMessage.channelId,
322
+ message_id: refMessage.messageId,
323
+ guild_id: void 0
324
+ };
325
+ const payload = await _Message._createMessageBody(opts, ref, mergedReply?.ping !== false);
326
+ return this._send(payload);
327
+ }
328
+ /** Exposed for testing purposes, use Message.reply() or send() for normal use */
329
+ static async _createMessageBody(content, referenced_message, ping) {
330
+ if (typeof content === "string") {
331
+ if (content.length === 0) {
332
+ throw new RangeError("Cannot send an empty message");
333
+ }
334
+ content = { content };
335
+ }
336
+ const base = buildSendBody(content);
337
+ const files = content.files?.length ? await resolveMessageFiles(content.files) : void 0;
338
+ const body = { ...base };
339
+ if (referenced_message) {
340
+ body.message_reference = referenced_message;
341
+ if (ping === false) {
342
+ body.flags = (body.flags ?? 0) | MessageFlags.SuppressNotifications;
343
+ }
344
+ }
345
+ return { files, body };
346
+ }
347
+ async _send(payload) {
348
+ const data = await this.client.rest.post(
349
+ Routes.channelMessages(this.channelId),
350
+ payload
351
+ );
352
+ this.client._addMessageToCache(this.channelId, data);
353
+ return new _Message(this.client, data);
354
+ }
355
+ /**
356
+ * Edit this message. Only the author (or admins) can edit.
357
+ * @param options - New content and/or embeds
358
+ */
359
+ async edit(options) {
360
+ const body = {};
361
+ if (options.content !== void 0) body.content = options.content;
362
+ if (options.embeds?.length) {
363
+ body.embeds = options.embeds.map((e) => e instanceof EmbedBuilder2 ? e.toJSON() : e);
364
+ }
365
+ const data = await this.client.rest.patch(Routes.channelMessage(this.channelId, this.id), {
366
+ body
367
+ });
368
+ return new _Message(this.client, data);
369
+ }
370
+ /**
371
+ * Create a reaction collector for this message.
372
+ * Collects reactions matching the filter until time expires or max is reached.
373
+ * @param options - Filter, time (ms), and max count
374
+ * @example
375
+ * const collector = message.createReactionCollector({ filter: (r, u) => u.id === userId, time: 10000 });
376
+ * collector.on('collect', (reaction, user) => console.log(user.username, 'reacted with', reaction.emoji.name));
377
+ * collector.on('end', (collected, reason) => { ... });
378
+ */
379
+ createReactionCollector(options) {
380
+ return new ReactionCollector(this.client, this.id, this.channelId, options);
381
+ }
382
+ /**
383
+ * Re-fetch this message from the API to get the latest content, embeds, reactions, etc.
384
+ * Use when you have a stale Message (e.g. from an old event or cache) and need fresh data.
385
+ * @returns The updated message
386
+ * @throws FluxerError with MESSAGE_NOT_FOUND if the message was deleted or does not exist
387
+ * @example
388
+ * const updated = await message.fetch();
389
+ * console.log('Latest content:', updated.content);
390
+ */
391
+ async fetch() {
392
+ return this.client.channels.fetchMessage(this.channelId, this.id);
393
+ }
394
+ /** Delete this message. */
395
+ async delete() {
396
+ await this.client.rest.delete(Routes.channelMessage(this.channelId, this.id));
397
+ }
398
+ /**
399
+ * Delete a specific attachment from this message.
400
+ * DELETE /channels/{id}/messages/{id}/attachments/{attachmentId}.
401
+ */
402
+ async deleteAttachment(attachmentId) {
403
+ await this.client.rest.delete(
404
+ Routes.channelMessageAttachment(this.channelId, this.id, attachmentId),
405
+ { auth: true }
406
+ );
407
+ this.attachments.delete(attachmentId);
408
+ }
409
+ /** Pin this message to the channel. Requires Manage Messages permission. */
410
+ async pin() {
411
+ await this.client.rest.put(Routes.channelPinMessage(this.channelId, this.id));
412
+ this.pinned = true;
413
+ }
414
+ /** Unpin this message from the channel. Requires Manage Messages permission. */
415
+ async unpin() {
416
+ await this.client.rest.delete(Routes.channelPinMessage(this.channelId, this.id));
417
+ this.pinned = false;
418
+ }
419
+ /**
420
+ * Format emoji for reaction API: unicode string or "name:id" for custom.
421
+ * For string resolution (e.g. :name:), use client.resolveEmoji; Message methods resolve automatically when guildId is available.
422
+ */
423
+ static formatEmoji(emoji) {
424
+ if (typeof emoji === "string") return emoji;
425
+ return `${emoji.name}:${emoji.id}`;
426
+ }
427
+ resolveEmojiForReaction(emoji) {
428
+ return this.client.resolveEmoji(emoji, this.guildId);
429
+ }
430
+ /**
431
+ * Add a reaction to this message (as the bot).
432
+ * @param emoji - Unicode emoji, custom `{ name, id }`, `:name:`, `name:id`, or `<:name:id>`
433
+ */
434
+ async react(emoji) {
435
+ const emojiStr = await this.resolveEmojiForReaction(emoji);
436
+ const route = `${Routes.channelMessageReaction(this.channelId, this.id, emojiStr)}/@me`;
437
+ await this.client.rest.put(route);
438
+ }
439
+ /**
440
+ * Remove the bot's reaction, or a specific user's reaction if userId is provided.
441
+ * @param emoji - Unicode emoji, custom `{ name, id }`, `:name:`, `name:id`, or `<:name:id>`
442
+ * @param userId - If provided, removes that user's reaction (requires moderator permissions)
443
+ */
444
+ async removeReaction(emoji, userId) {
445
+ const emojiStr = await this.resolveEmojiForReaction(emoji);
446
+ const route = `${Routes.channelMessageReaction(this.channelId, this.id, emojiStr)}/${userId ?? "@me"}`;
447
+ await this.client.rest.delete(route);
448
+ }
449
+ /**
450
+ * Remove all reactions from this message.
451
+ * Requires moderator permissions.
452
+ */
453
+ async removeAllReactions() {
454
+ await this.client.rest.delete(Routes.channelMessageReactions(this.channelId, this.id));
455
+ }
456
+ /**
457
+ * Remove all reactions of a specific emoji from this message.
458
+ * @param emoji - Unicode emoji, custom `{ name, id }`, `:name:`, `name:id`, or `<:name:id>`. Requires moderator permissions.
459
+ */
460
+ async removeReactionEmoji(emoji) {
461
+ const emojiStr = await this.resolveEmojiForReaction(emoji);
462
+ await this.client.rest.delete(Routes.channelMessageReaction(this.channelId, this.id, emojiStr));
463
+ }
464
+ /**
465
+ * Fetch users who reacted with the given emoji.
466
+ * @param emoji - Unicode emoji or custom `{ name, id }`
467
+ * @param options - limit (1–100), after (user ID for pagination)
468
+ * @returns Array of User objects
469
+ */
470
+ async fetchReactionUsers(emoji, options) {
471
+ const emojiStr = await this.resolveEmojiForReaction(emoji);
472
+ const params = new URLSearchParams();
473
+ if (options?.limit != null) params.set("limit", String(options.limit));
474
+ if (options?.after) params.set("after", options.after);
475
+ const qs = params.toString();
476
+ const route = Routes.channelMessageReaction(this.channelId, this.id, emojiStr) + (qs ? `?${qs}` : "");
477
+ const data = await this.client.rest.get(route);
478
+ const list = Array.isArray(data) ? data : data?.users ?? [];
479
+ return list.map((u) => this.client.getOrCreateUser(u));
480
+ }
481
+ };
482
+ export {
483
+ Message
484
+ };