@fluxerjs/core 1.4.0 → 2.0.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/dist/message.mjs CHANGED
@@ -1,15 +1,25 @@
1
- // src/structures/Base.ts
2
- var Base = class {
3
- };
4
-
5
- // src/structures/Message.ts
1
+ // src/structures/message/Message.ts
6
2
  import { Collection as Collection2 } from "@fluxerjs/collection";
7
- import { MessageType, Routes } from "@fluxerjs/types";
8
3
  import { EmbedBuilder as EmbedBuilder2 } from "@fluxerjs/builders";
4
+ import {
5
+ MessageType,
6
+ Routes as Routes3
7
+ } from "@fluxerjs/types";
9
8
 
10
- // src/util/messageUtils.ts
11
- import { MessageFlags } from "@fluxerjs/types";
12
- import { EmbedBuilder } from "@fluxerjs/builders";
9
+ // src/client/sdkOptions.ts
10
+ function toMessageAttachmentEditWire(attachments) {
11
+ return attachments.map((a) => {
12
+ const out = { id: a.id };
13
+ if (a.filename !== void 0) out.filename = a.filename;
14
+ if (a.uploadFilename !== void 0) out.upload_filename = a.uploadFilename;
15
+ if (a.fileSize !== void 0) out.file_size = a.fileSize;
16
+ if (a.contentType !== void 0) out.content_type = a.contentType;
17
+ if (a.title !== void 0) out.title = a.title;
18
+ if (a.description !== void 0) out.description = a.description;
19
+ if (a.flags !== void 0) out.flags = a.flags;
20
+ return out;
21
+ });
22
+ }
13
23
 
14
24
  // src/errors/ErrorCodes.ts
15
25
  import { ErrorCodes } from "@fluxerjs/util";
@@ -17,8 +27,30 @@ import { ErrorCodes } from "@fluxerjs/util";
17
27
  // src/errors/FluxerError.ts
18
28
  import { FluxerError } from "@fluxerjs/util";
19
29
 
20
- // src/util/messageUtils.ts
30
+ // src/util/messageUtils/files.ts
21
31
  var FILE_FETCH_TIMEOUT_MS = 3e4;
32
+ async function fetchFileBuffer(url, index) {
33
+ if (!URL.canParse(url)) {
34
+ throw new FluxerError(`Invalid file URL at index ${index}: ${url}`, {
35
+ code: ErrorCodes.InvalidFileUrl
36
+ });
37
+ }
38
+ let res;
39
+ try {
40
+ res = await fetch(url, { signal: AbortSignal.timeout(FILE_FETCH_TIMEOUT_MS) });
41
+ } catch (err) {
42
+ throw new FluxerError(`Failed to fetch file from ${url}`, {
43
+ code: ErrorCodes.FileFetchFailed,
44
+ cause: err instanceof Error ? err : void 0
45
+ });
46
+ }
47
+ if (!res.ok) {
48
+ throw new FluxerError(`Failed to fetch file from ${url}: ${res.status} ${res.statusText}`, {
49
+ code: ErrorCodes.FileFetchFailed
50
+ });
51
+ }
52
+ return res.arrayBuffer();
53
+ }
22
54
  async function resolveMessageFiles(files) {
23
55
  const result = [];
24
56
  for (let i = 0; i < files.length; i++) {
@@ -26,32 +58,7 @@ async function resolveMessageFiles(files) {
26
58
  if (!f) continue;
27
59
  const filename = f.filename ?? f.name;
28
60
  if ("url" in f && f.url) {
29
- if (!URL.canParse(f.url)) {
30
- throw new FluxerError(`Invalid file URL at index ${i}: ${f.url}`, {
31
- code: ErrorCodes.InvalidFileUrl
32
- });
33
- }
34
- let res;
35
- try {
36
- res = await fetch(f.url, {
37
- signal: AbortSignal.timeout(FILE_FETCH_TIMEOUT_MS)
38
- });
39
- } catch (err) {
40
- throw new FluxerError(`Failed to fetch file from ${f.url}`, {
41
- code: ErrorCodes.FileFetchFailed,
42
- cause: err instanceof Error ? err : void 0
43
- });
44
- }
45
- if (!res.ok) {
46
- throw new FluxerError(
47
- `Failed to fetch file from ${f.url}: ${res.status} ${res.statusText}`,
48
- {
49
- code: ErrorCodes.FileFetchFailed
50
- }
51
- );
52
- }
53
- const data = await res.arrayBuffer();
54
- result.push({ name: f.name, data, filename });
61
+ result.push({ name: f.name, data: await fetchFileBuffer(f.url, i), filename });
55
62
  } else if ("data" in f && f.data != null) {
56
63
  result.push({ name: f.name, data: f.data, filename });
57
64
  } else {
@@ -62,74 +69,141 @@ async function resolveMessageFiles(files) {
62
69
  }
63
70
  return result;
64
71
  }
72
+
73
+ // src/util/messageUtils/body.ts
74
+ import { MessageReferenceType } from "@fluxerjs/types";
75
+ import { EmbedBuilder, MessagePayload } from "@fluxerjs/builders";
65
76
  function toAPIAllowedMentions(options) {
66
77
  const result = {};
67
- if (options.parse?.length) result.parse = options.parse;
78
+ if (options.parse !== void 0) result.parse = options.parse;
68
79
  if (options.users?.length) result.users = options.users;
69
80
  if (options.roles?.length) result.roles = options.roles;
70
81
  if (options.repliedUser !== void 0) result.replied_user = options.repliedUser;
71
82
  return result;
72
83
  }
73
84
  function applyReplyPingSuppression(body) {
74
- body.flags = (body.flags ?? 0) | MessageFlags.SuppressNotifications;
75
85
  body.allowed_mentions = {
76
86
  ...body.allowed_mentions ?? {},
77
87
  replied_user: false
78
88
  };
79
89
  }
90
+ function assignIfDefined(target, key, value) {
91
+ if (value !== void 0) target[key] = value;
92
+ }
80
93
  function buildSendBody(options) {
81
94
  const body = typeof options === "string" ? { content: options } : options;
82
95
  const result = {};
83
- if (body.content !== void 0) result.content = body.content;
96
+ assignIfDefined(result, "content", body.content);
84
97
  if (body.embeds?.length) {
85
98
  result.embeds = body.embeds.map((e) => e instanceof EmbedBuilder ? e.toJSON() : e);
86
99
  }
87
- if (body.files?.length && body.attachments) {
88
- result.attachments = body.attachments.map((a) => ({
100
+ if (body.uploadedAttachments?.length) {
101
+ result.attachments = body.uploadedAttachments;
102
+ } else if (body.files?.length) {
103
+ result.attachments = body.attachments?.length ? body.attachments.map((a) => ({
89
104
  id: a.id,
90
105
  filename: a.filename,
91
106
  ...a.title != null && { title: a.title },
92
107
  ...a.description != null && { description: a.description },
93
108
  ...a.flags != null && { flags: a.flags }
94
- }));
95
- } else if (body.files?.length) {
96
- result.attachments = body.files.map((f, i) => ({
97
- id: i,
98
- filename: f.filename ?? f.name
99
- }));
109
+ })) : body.files.map((f, i) => ({ id: i, filename: f.filename ?? f.name }));
100
110
  }
101
111
  if (body.allowedMentions) result.allowed_mentions = toAPIAllowedMentions(body.allowedMentions);
102
112
  if (body.stickerIds?.length) result.sticker_ids = body.stickerIds;
103
- if (body.nonce !== void 0) result.nonce = body.nonce;
104
- if (body.favoriteMemeId !== void 0) result.favorite_meme_id = body.favoriteMemeId;
105
- if (body.tts !== void 0) result.tts = body.tts;
106
- if (body.flags !== void 0) result.flags = body.flags;
113
+ assignIfDefined(result, "nonce", body.nonce);
114
+ assignIfDefined(result, "favorite_meme_id", body.favoriteMemeId);
115
+ assignIfDefined(result, "tts", body.tts);
116
+ assignIfDefined(result, "flags", body.flags);
107
117
  return result;
108
118
  }
109
- function toMessageReference(target) {
119
+ function toMessageReference(target, forceForward = false) {
110
120
  const ref = {
111
121
  channel_id: target.channelId,
112
122
  message_id: target.messageId
113
123
  };
114
- if (target.guildId != null && target.guildId !== "") ref.guild_id = target.guildId;
124
+ if (target.guildId) ref.guild_id = target.guildId;
125
+ const type = forceForward ? MessageReferenceType.Forward : target.type ?? MessageReferenceType.Default;
126
+ if (type !== MessageReferenceType.Default) ref.type = type;
127
+ if (target.attachmentIds?.length) ref.attachment_ids = target.attachmentIds;
128
+ if (target.embedIndices?.length) ref.embed_indices = target.embedIndices;
115
129
  return ref;
116
130
  }
117
- async function prepareMessagePostPayload(options) {
118
- if (typeof options === "string") {
119
- if (options.length === 0) throw new RangeError("Cannot send an empty message");
120
- options = { content: options };
121
- }
122
- const { replyTo, ping, files, allowedMentions, ...sendFields } = options;
123
- const body = buildSendBody({ ...sendFields, files, allowedMentions });
124
- if (replyTo) {
131
+ function shouldSuppressReplyPing(ping, allowedMentions, body) {
132
+ return ping === false || allowedMentions?.repliedUser === false || body.allowed_mentions?.replied_user === false;
133
+ }
134
+ function messagePayloadToSendOptions(payload) {
135
+ const json = payload.toJSON();
136
+ const options = {};
137
+ if (json.content != null) options.content = json.content;
138
+ if (json.embeds?.length) options.embeds = json.embeds;
139
+ if (json.tts !== void 0) options.tts = json.tts;
140
+ if (json.flags !== void 0) options.flags = json.flags;
141
+ if (json.allowed_mentions) {
142
+ options.allowedMentions = {
143
+ parse: json.allowed_mentions.parse,
144
+ users: json.allowed_mentions.users,
145
+ roles: json.allowed_mentions.roles,
146
+ repliedUser: json.allowed_mentions.replied_user
147
+ };
148
+ }
149
+ if (json.message_reference?.channel_id && json.message_reference.message_id) {
150
+ options.replyTo = {
151
+ channelId: json.message_reference.channel_id,
152
+ messageId: json.message_reference.message_id,
153
+ guildId: json.message_reference.guild_id
154
+ };
155
+ }
156
+ if (json.attachments?.length) {
157
+ options.attachments = json.attachments.map((a) => ({
158
+ id: a.id,
159
+ filename: a.filename,
160
+ description: a.description ?? void 0
161
+ }));
162
+ }
163
+ return options;
164
+ }
165
+ async function prepareMessagePostPayload(options, defaults) {
166
+ let normalized = options instanceof MessagePayload ? messagePayloadToSendOptions(options) : options;
167
+ if (typeof normalized === "string") {
168
+ if (normalized.length === 0) {
169
+ throw new FluxerError("Cannot send an empty message", { code: ErrorCodes.EmptyMessage });
170
+ }
171
+ normalized = { content: normalized };
172
+ } else {
173
+ normalized = { ...normalized };
174
+ if (!normalized.allowedMentions && defaults?.defaultAllowedMentions) {
175
+ normalized.allowedMentions = defaults.defaultAllowedMentions;
176
+ }
177
+ }
178
+ const { replyTo, forward, ping, files, allowedMentions, uploadedAttachments, ...sendFields } = normalized;
179
+ if (files?.length && uploadedAttachments?.length) {
180
+ throw new FluxerError("Cannot combine multipart files with uploadedAttachments", {
181
+ code: ErrorCodes.InvalidMessageOptions
182
+ });
183
+ }
184
+ if (replyTo && forward) {
185
+ throw new FluxerError("Cannot combine replyTo and forward", {
186
+ code: ErrorCodes.InvalidMessageOptions
187
+ });
188
+ }
189
+ const body = buildSendBody({ ...sendFields, files, allowedMentions, uploadedAttachments });
190
+ if (forward) {
191
+ if (!forward.channelId || !forward.messageId) {
192
+ throw new FluxerError("forward requires channelId and messageId", {
193
+ code: ErrorCodes.InvalidMessageOptions
194
+ });
195
+ }
196
+ body.message_reference = toMessageReference(forward, true);
197
+ } else if (replyTo) {
125
198
  body.message_reference = toMessageReference(replyTo);
126
- const suppressPing = ping === false || allowedMentions?.repliedUser === false || body.allowed_mentions?.replied_user === false;
127
- if (suppressPing) applyReplyPingSuppression(body);
199
+ if (shouldSuppressReplyPing(ping, allowedMentions, body)) applyReplyPingSuppression(body);
128
200
  } else if (allowedMentions?.repliedUser === false) {
129
201
  applyReplyPingSuppression(body);
130
202
  }
131
- const resolvedFiles = files?.length ? await resolveMessageFiles(files) : void 0;
132
- return { body, files: resolvedFiles };
203
+ return {
204
+ body,
205
+ files: !uploadedAttachments?.length && files?.length ? await resolveMessageFiles(files) : void 0
206
+ };
133
207
  }
134
208
 
135
209
  // src/util/ReactionCollector.ts
@@ -144,18 +218,20 @@ var Events = {
144
218
  MessageDelete: "messageDelete",
145
219
  MessageDeleteBulk: "messageDeleteBulk",
146
220
  MessageReactionAdd: "messageReactionAdd",
221
+ MessageReactionAddMany: "messageReactionAddMany",
147
222
  MessageReactionRemove: "messageReactionRemove",
148
223
  MessageReactionRemoveAll: "messageReactionRemoveAll",
149
224
  MessageReactionRemoveEmoji: "messageReactionRemoveEmoji",
150
- InteractionCreate: "interactionCreate",
151
225
  GuildCreate: "guildCreate",
152
226
  GuildUpdate: "guildUpdate",
153
227
  GuildDelete: "guildDelete",
154
228
  GuildBanAdd: "guildBanAdd",
155
229
  GuildBanRemove: "guildBanRemove",
230
+ GuildAuditLogEntryCreate: "guildAuditLogEntryCreate",
156
231
  GuildEmojisUpdate: "guildEmojisUpdate",
157
232
  GuildStickersUpdate: "guildStickersUpdate",
158
- GuildIntegrationsUpdate: "guildIntegrationsUpdate",
233
+ GuildCountsUpdate: "guildCountsUpdate",
234
+ ChannelMemberCountsUpdate: "channelMemberCountsUpdate",
159
235
  GuildMemberAdd: "guildMemberAdd",
160
236
  GuildMemberUpdate: "guildMemberUpdate",
161
237
  GuildMemberRemove: "guildMemberRemove",
@@ -163,9 +239,6 @@ var Events = {
163
239
  GuildRoleCreate: "guildRoleCreate",
164
240
  GuildRoleUpdate: "guildRoleUpdate",
165
241
  GuildRoleDelete: "guildRoleDelete",
166
- GuildScheduledEventCreate: "guildScheduledEventCreate",
167
- GuildScheduledEventUpdate: "guildScheduledEventUpdate",
168
- GuildScheduledEventDelete: "guildScheduledEventDelete",
169
242
  ChannelCreate: "channelCreate",
170
243
  ChannelUpdate: "channelUpdate",
171
244
  ChannelDelete: "channelDelete",
@@ -174,9 +247,14 @@ var Events = {
174
247
  InviteDelete: "inviteDelete",
175
248
  TypingStart: "typingStart",
176
249
  UserUpdate: "userUpdate",
250
+ UserConnectionsUpdate: "userConnectionsUpdate",
251
+ WebAuthnCredentialsUpdate: "webauthnCredentialsUpdate",
177
252
  PresenceUpdate: "presenceUpdate",
253
+ PresenceUpdateBulk: "presenceUpdateBulk",
178
254
  VoiceStateUpdate: "voiceStateUpdate",
255
+ VoiceStateAck: "voiceStateAck",
179
256
  VoiceServerUpdate: "voiceServerUpdate",
257
+ EntranceSoundPlay: "entranceSoundPlay",
180
258
  VoiceStatesSync: "voiceStatesSync",
181
259
  WebhooksUpdate: "webhooksUpdate",
182
260
  Resumed: "resumed",
@@ -204,12 +282,14 @@ var ReactionCollector = class extends EventEmitter {
204
282
  time: options.time ?? 0,
205
283
  max: options.max ?? 0
206
284
  };
207
- this._listener = (reaction, user, _msgId, chId, _emoji, userId) => {
208
- if (this._ended || reaction.messageId !== this.messageId || chId !== this.channelId) return;
209
- if (!this.options.filter(reaction, user)) return;
210
- const key = `${userId}:${reaction.emoji.id ?? reaction.emoji.name}`;
211
- this.collected.set(key, { reaction, user });
212
- this.emit("collect", reaction, user);
285
+ this._listener = (payload) => {
286
+ if (this._ended || payload.reaction.messageId !== this.messageId || payload.channelId !== this.channelId) {
287
+ return;
288
+ }
289
+ if (!this.options.filter(payload.reaction, payload.user)) return;
290
+ const key = `${payload.userId}:${payload.reaction.emoji.id ?? payload.reaction.emoji.name}`;
291
+ this.collected.set(key, { reaction: payload.reaction, user: payload.user });
292
+ this.emit("collect", payload.reaction, payload.user);
213
293
  if (this.options.max > 0 && this.collected.size >= this.options.max) {
214
294
  this.stop("limit");
215
295
  }
@@ -237,64 +317,199 @@ var ReactionCollector = class extends EventEmitter {
237
317
  }
238
318
  };
239
319
 
240
- // src/structures/Message.ts
320
+ // src/structures/Base.ts
321
+ var Base = class {
322
+ };
323
+
324
+ // src/structures/message/reactions.ts
325
+ import { Routes } from "@fluxerjs/types";
326
+ async function emojiPath(message, emoji) {
327
+ return message.client.resolveEmoji(emoji, message.guildId);
328
+ }
329
+ async function reactToMessage(message, emoji) {
330
+ const e = await emojiPath(message, emoji);
331
+ await message.client.rest.put(Routes.channelMessageReactionMe(message.channelId, message.id, e));
332
+ }
333
+ async function removeMessageReaction(message, emoji, userId) {
334
+ const e = await emojiPath(message, emoji);
335
+ const route = userId ? Routes.channelMessageReactionUser(message.channelId, message.id, e, userId) : Routes.channelMessageReactionMe(message.channelId, message.id, e);
336
+ await message.client.rest.delete(route);
337
+ }
338
+ async function removeAllMessageReactions(message) {
339
+ await message.client.rest.delete(Routes.channelMessageReactions(message.channelId, message.id));
340
+ }
341
+ async function removeMessageReactionEmoji(message, emoji) {
342
+ const e = await emojiPath(message, emoji);
343
+ await message.client.rest.delete(Routes.channelMessageReaction(message.channelId, message.id, e));
344
+ }
345
+ async function fetchMessageReactionUsers(message, emoji, options) {
346
+ return (await fetchMessageReactionUsersPage(message, emoji, options)).users;
347
+ }
348
+ async function fetchMessageReactionUsersPage(message, emoji, options) {
349
+ const e = await emojiPath(message, emoji);
350
+ const params = new URLSearchParams();
351
+ if (options?.limit != null) params.set("limit", String(options.limit));
352
+ if (options?.after) params.set("after", options.after);
353
+ const qs = params.toString();
354
+ const route = Routes.channelMessageReactionUsers(message.channelId, message.id, e) + (qs ? `?${qs}` : "");
355
+ const data = await message.client.rest.get(route);
356
+ if (Array.isArray(data)) {
357
+ return {
358
+ users: data.map((u) => message.client.getOrCreateUser(u)),
359
+ hasMore: false,
360
+ nextAfter: null
361
+ };
362
+ }
363
+ const list = data.items ?? data.users ?? [];
364
+ return {
365
+ users: list.map((u) => message.client.getOrCreateUser(u)),
366
+ hasMore: data.has_more ?? false,
367
+ nextAfter: data.next_after ?? null
368
+ };
369
+ }
370
+
371
+ // src/structures/message/send.ts
372
+ import { MessagePayload as MessagePayloadBuilder } from "@fluxerjs/builders";
373
+ import { Routes as Routes2 } from "@fluxerjs/types";
374
+ function toReplyTarget(ref) {
375
+ return {
376
+ channelId: ref.channel_id,
377
+ messageId: ref.message_id,
378
+ ...ref.guild_id != null ? { guildId: ref.guild_id } : {}
379
+ };
380
+ }
381
+ function toSendOptions(content) {
382
+ if (typeof content === "string") return { content };
383
+ if (content instanceof MessagePayloadBuilder) return messagePayloadToSendOptions(content);
384
+ return { ...content };
385
+ }
386
+ async function createMessageBody(content, referenced_message, ping) {
387
+ if (typeof content === "string" && content.length === 0) {
388
+ throw new FluxerError("Cannot send an empty message", { code: ErrorCodes.EmptyMessage });
389
+ }
390
+ const opts = toSendOptions(content);
391
+ if (referenced_message) {
392
+ opts.replyTo = toReplyTarget(referenced_message);
393
+ if (ping !== void 0) opts.ping = ping;
394
+ }
395
+ return prepareMessagePostPayload(opts);
396
+ }
397
+ function asReplyTarget(value) {
398
+ if ("messageId" in value) return value;
399
+ return {
400
+ channelId: value.channelId,
401
+ messageId: value.id,
402
+ guildId: value.guildId
403
+ };
404
+ }
405
+ async function sendPrepared(message, payload) {
406
+ const data = await message.client.rest.post(
407
+ Routes2.channelMessages(message.channelId),
408
+ payload
409
+ );
410
+ message.client._addMessageToCache(message.channelId, data);
411
+ return new message.constructor(message.client, data);
412
+ }
413
+ async function sendMessage(message, options) {
414
+ return message._send(
415
+ await prepareMessagePostPayload(options, {
416
+ defaultAllowedMentions: message.client.options.defaultAllowedMentions
417
+ })
418
+ );
419
+ }
420
+ async function sendMessageTo(message, channelId, options) {
421
+ return message.client.channels.send(channelId, options);
422
+ }
423
+ async function replyToMessage(message, options, replyOptions) {
424
+ const opts = typeof options === "string" ? { content: options } : { ...options };
425
+ const { replyTo: inlineReplyTo, ping: inlinePing, ...sendOpts } = opts;
426
+ const ping = replyOptions?.ping ?? inlinePing ?? message.client.options.defaultReplyPing;
427
+ const replyTo = asReplyTarget(replyOptions?.replyTo ?? inlineReplyTo ?? message);
428
+ return message._send(
429
+ await prepareMessagePostPayload(
430
+ { ...sendOpts, replyTo, ping },
431
+ { defaultAllowedMentions: message.client.options.defaultAllowedMentions }
432
+ )
433
+ );
434
+ }
435
+
436
+ // src/structures/message/Message.ts
241
437
  var Message = class _Message extends Base {
438
+ /** The {@link Client} that instantiated this message. */
242
439
  client;
440
+ /** Snowflake ID of this message. */
243
441
  id;
442
+ /** Channel ID where this message was sent. */
244
443
  channelId;
444
+ /** Guild ID if in a guild channel, null for DMs. */
245
445
  guildId;
446
+ /** The user who sent this message. */
246
447
  author;
448
+ /** Text content of the message. */
247
449
  content;
450
+ /** When the message was created. */
248
451
  createdAt;
452
+ /** When the message was last edited, or null if never edited. */
249
453
  editedAt;
454
+ /** Whether the message is pinned. */
250
455
  pinned;
456
+ /** Attached files (images, videos, etc.). */
251
457
  attachments;
458
+ /** Message type (Default, Reply, etc.). */
252
459
  type;
460
+ /** Message flags bitfield. */
253
461
  flags;
462
+ /** Whether `@everyone` or `@here` was mentioned. */
254
463
  mentionEveryone;
464
+ /** Whether this is a text-to-speech message. */
255
465
  tts;
466
+ /** Embedded content (rich previews, etc.). */
256
467
  embeds;
468
+ /** Stickers sent with the message. */
257
469
  stickers;
470
+ /** Reactions on the message. */
258
471
  reactions;
472
+ /** Reference to a replied-to message, if any. */
259
473
  messageReference;
474
+ /** Message snapshots for forwarded messages. */
260
475
  messageSnapshots;
476
+ /** Call data if this message represents a call event. */
261
477
  call;
478
+ /** The full referenced (replied-to) message, or null. */
262
479
  referencedMessage;
263
- /** Webhook ID if this message was sent via webhook. Null otherwise. */
480
+ /** Webhook ID if sent by a webhook. */
264
481
  webhookId;
265
- /** Users mentioned in this message. */
482
+ /** Users mentioned in the message. */
266
483
  mentions;
267
- /** Role IDs mentioned in this message. */
484
+ /** Role IDs mentioned in the message. */
268
485
  mentionRoles;
269
- /** Client-side nonce for acknowledgment. Null if not provided. */
486
+ /** Client-side nonce for deduplication. */
270
487
  nonce;
271
- /**
272
- * Channel where this message was sent. Resolved from cache; null if not cached.
273
- * Messages can only exist in text-based channels (text, DM, announcement), so this always has send() when non-null.
274
- */
488
+ /** Cached text/DM/guild channel, or null if uncached. */
275
489
  get channel() {
276
490
  return this.client.channels.get(this.channelId) ?? null;
277
491
  }
278
- /** Guild where this message was sent. Resolved from cache; null for DMs or if not cached. */
492
+ /** Cached guild, or null for DMs / uncached. */
279
493
  get guild() {
280
494
  return this.guildId ? this.client.guilds.get(this.guildId) ?? null : null;
281
495
  }
282
- /**
283
- * Resolve the channel (from cache or API). Use when you need the channel and it may not be cached.
284
- * @returns The channel
285
- * @throws FluxerError with CHANNEL_NOT_FOUND if the channel does not exist
286
- */
496
+ /** Fetch and resolve the channel this message is in. */
287
497
  async resolveChannel() {
288
498
  return this.client.channels.resolve(this.channelId);
289
499
  }
290
- /**
291
- * Resolve the guild (from cache or API). Returns null for DMs.
292
- * @returns The guild, or null if this is a DM or guild not found
293
- */
500
+ /** Fetch and resolve the guild, or null if a DM. */
294
501
  async resolveGuild() {
295
- return this.guildId ? this.client.guilds.resolve(this.guildId) : null;
502
+ if (!this.guildId) return null;
503
+ try {
504
+ return await this.client.guilds.resolve(this.guildId);
505
+ } catch {
506
+ return null;
507
+ }
296
508
  }
297
- /** @param data - API message from POST/PATCH /channels/{id}/messages or gateway MESSAGE_CREATE */
509
+ /**
510
+ * Construct a message from API data.
511
+ * @param data - API message from REST or MESSAGE_CREATE
512
+ */
298
513
  constructor(client, data) {
299
514
  super();
300
515
  this.client = client;
@@ -324,220 +539,109 @@ var Message = class _Message extends Base {
324
539
  this.mentionRoles = data.mention_roles ?? [];
325
540
  this.nonce = data.nonce ?? null;
326
541
  }
327
- /**
328
- * Send a message to this channel without replying. Use when you want a standalone message.
329
- * @param options - Text content or object with content, embeds, and/or files
330
- * @example
331
- * await message.send('Pong!');
332
- * await message.send({ embeds: [embed] }); // EmbedBuilder auto-converted
333
- * await message.send({ content: 'File', files: [{ name: 'data.txt', data }] });
334
- */
542
+ /** Send a message in this channel without replying. */
335
543
  async send(options) {
336
- const payload = await prepareMessagePostPayload(options);
337
- return this._send(payload);
544
+ return sendMessage(this, options);
338
545
  }
339
- /**
340
- * Send a message to a specific channel. Use for logging, forwarding, or sending to another channel in the guild.
341
- * @param channelId - Snowflake of the target channel (e.g. log channel ID)
342
- * @param options - Text content or object with content and/or embeds
343
- * @example
344
- * await message.sendTo(logChannelId, 'User ' + message.author.username + ' said: ' + message.content);
345
- * await message.sendTo(announceChannelId, { embeds: [embed] });
346
- */
546
+ /** Send a message to another channel by ID. */
347
547
  async sendTo(channelId, options) {
348
- return this.client.channels.send(channelId, options);
548
+ return sendMessageTo(this, channelId, options);
349
549
  }
350
550
  /**
351
- * Reply to this message (shows as a reply in the client).
352
- * @param options - Text content or object with content, embeds, and/or reply options (ping, replyTo)
551
+ * Reply to this message.
353
552
  * @example
354
553
  * await message.reply('Pong!');
355
- * await message.reply({ embeds: [embed] });
356
554
  * await message.reply('No ping!', { ping: false });
357
- * await message.reply({ content: 'Silent reply', allowedMentions: AllowedMentions.suppressReplyPing });
358
- * await message.reply({ content: 'Reply to other', replyTo: otherMessage });
555
+ * await message.reply({ content: 'Silent', allowedMentions: AllowedMentions.suppressReplyPing });
359
556
  */
360
557
  async reply(options, replyOptions) {
361
- const opts = typeof options === "string" ? { content: options } : options;
362
- const mergedReply = replyOptions ?? (opts.ping !== void 0 || opts.replyTo !== void 0) ? { ping: opts.ping, replyTo: opts.replyTo } : void 0;
363
- const refMessage = mergedReply?.replyTo ?? this;
364
- const replyTo = refMessage instanceof _Message ? {
365
- channelId: refMessage.channelId,
366
- messageId: refMessage.id,
367
- guildId: refMessage.guildId
368
- } : refMessage;
369
- const { replyTo: _ignored, ping: _ping, ...sendOpts } = opts;
370
- const payload = await prepareMessagePostPayload({
371
- ...sendOpts,
372
- replyTo,
373
- ping: mergedReply?.ping
374
- });
375
- return this._send(payload);
558
+ return replyToMessage(this, options, replyOptions);
376
559
  }
377
- /** Exposed for testing — prefer `message.reply()` / `prepareMessagePostPayload()`. */
560
+ /** Test helper — prefer {@link reply} / `prepareMessagePostPayload()`. */
378
561
  static async _createMessageBody(content, referenced_message, ping) {
379
- if (typeof content === "string" && content.length === 0) {
380
- throw new RangeError("Cannot send an empty message");
381
- }
382
- if (typeof content === "string") {
383
- const opts2 = { content };
384
- if (referenced_message) {
385
- opts2.replyTo = {
386
- channelId: referenced_message.channel_id,
387
- messageId: referenced_message.message_id,
388
- ...referenced_message.guild_id != null ? { guildId: referenced_message.guild_id } : {}
389
- };
390
- if (ping !== void 0) opts2.ping = ping;
391
- }
392
- return prepareMessagePostPayload(opts2);
393
- }
394
- const opts = { ...content };
395
- if (referenced_message) {
396
- opts.replyTo = {
397
- channelId: referenced_message.channel_id,
398
- messageId: referenced_message.message_id,
399
- ...referenced_message.guild_id != null ? { guildId: referenced_message.guild_id } : {}
400
- };
401
- if (ping !== void 0) opts.ping = ping;
402
- }
403
- return prepareMessagePostPayload(opts);
562
+ return createMessageBody(content, referenced_message, ping);
404
563
  }
564
+ /** Send a prepared payload (internal helper). */
405
565
  async _send(payload) {
406
- const data = await this.client.rest.post(
407
- Routes.channelMessages(this.channelId),
408
- payload
409
- );
410
- this.client._addMessageToCache(this.channelId, data);
411
- return new _Message(this.client, data);
566
+ return sendPrepared(this, payload);
412
567
  }
413
- /**
414
- * Edit this message. Only the author (or admins) can edit.
415
- * @param options - New content and/or embeds
416
- */
568
+ /** Edit this message (requires author or admin permissions). */
417
569
  async edit(options) {
418
570
  const body = {};
419
571
  if (options.content !== void 0) body.content = options.content;
420
572
  if (options.embeds?.length) {
421
- body.embeds = options.embeds.map((e) => e instanceof EmbedBuilder2 ? e.toJSON() : e);
573
+ body.embeds = options.embeds.map(
574
+ (e) => e instanceof EmbedBuilder2 ? e.toJSON() : e
575
+ );
422
576
  }
423
577
  if (options.allowedMentions) {
424
578
  body.allowed_mentions = toAPIAllowedMentions(options.allowedMentions);
425
579
  }
426
- const data = await this.client.rest.patch(Routes.channelMessage(this.channelId, this.id), {
580
+ if (options.flags !== void 0) body.flags = options.flags;
581
+ if (options.attachments !== void 0) {
582
+ body.attachments = toMessageAttachmentEditWire(options.attachments);
583
+ }
584
+ const data = await this.client.rest.patch(Routes3.channelMessage(this.channelId, this.id), {
427
585
  body
428
586
  });
429
- return new _Message(this.client, data);
587
+ const updated = new _Message(this.client, data);
588
+ this.client._addMessageToCache(this.channelId, data);
589
+ return updated;
430
590
  }
431
- /**
432
- * Create a reaction collector for this message.
433
- * Collects reactions matching the filter until time expires or max is reached.
434
- * @param options - Filter, time (ms), and max count
435
- * @example
436
- * const collector = message.createReactionCollector({ filter: (r, u) => u.id === userId, time: 10000 });
437
- * collector.on('collect', (reaction, user) => console.log(user.username, 'reacted with', reaction.emoji.name));
438
- * collector.on('end', (collected, reason) => { ... });
439
- */
591
+ /** Create a {@link ReactionCollector} for this message. */
440
592
  createReactionCollector(options) {
441
593
  return new ReactionCollector(this.client, this.id, this.channelId, options);
442
594
  }
443
- /**
444
- * Re-fetch this message from the API to get the latest content, embeds, reactions, etc.
445
- * Use when you have a stale Message (e.g. from an old event or cache) and need fresh data.
446
- * @returns The updated message
447
- * @throws FluxerError with MESSAGE_NOT_FOUND if the message was deleted or does not exist
448
- * @example
449
- * const updated = await message.fetch();
450
- * console.log('Latest content:', updated.content);
451
- */
595
+ /** Fetch the latest version of this message from the API. */
452
596
  async fetch() {
453
597
  return this.client.channels.fetchMessage(this.channelId, this.id);
454
598
  }
455
599
  /** Delete this message. */
456
600
  async delete() {
457
- await this.client.rest.delete(Routes.channelMessage(this.channelId, this.id));
601
+ await this.client.rest.delete(Routes3.channelMessage(this.channelId, this.id));
602
+ this.client._removeMessageFromCache(this.channelId, this.id);
458
603
  }
459
- /**
460
- * Delete a specific attachment from this message.
461
- * DELETE /channels/{id}/messages/{id}/attachments/{attachmentId}.
462
- */
604
+ /** Delete a specific attachment from this message. */
463
605
  async deleteAttachment(attachmentId) {
464
606
  await this.client.rest.delete(
465
- Routes.channelMessageAttachment(this.channelId, this.id, attachmentId),
607
+ Routes3.channelMessageAttachment(this.channelId, this.id, attachmentId),
466
608
  { auth: true }
467
609
  );
468
610
  this.attachments.delete(attachmentId);
469
611
  }
470
- /** Pin this message to the channel. Requires Manage Messages permission. */
612
+ /** Pin this message in the channel. */
471
613
  async pin() {
472
- await this.client.rest.put(Routes.channelPinMessage(this.channelId, this.id));
614
+ await this.client.rest.put(Routes3.channelPinMessage(this.channelId, this.id));
473
615
  this.pinned = true;
474
616
  }
475
- /** Unpin this message from the channel. Requires Manage Messages permission. */
617
+ /** Unpin this message from the channel. */
476
618
  async unpin() {
477
- await this.client.rest.delete(Routes.channelPinMessage(this.channelId, this.id));
619
+ await this.client.rest.delete(Routes3.channelPinMessage(this.channelId, this.id));
478
620
  this.pinned = false;
479
621
  }
480
- /**
481
- * Format emoji for reaction API: unicode string or "name:id" for custom.
482
- * For string resolution (e.g. :name:), use client.resolveEmoji; Message methods resolve automatically when guildId is available.
483
- */
484
- static formatEmoji(emoji) {
485
- if (typeof emoji === "string") return emoji;
486
- return `${emoji.name}:${emoji.id}`;
487
- }
488
- resolveEmojiForReaction(emoji) {
489
- return this.client.resolveEmoji(emoji, this.guildId);
490
- }
491
- /**
492
- * Add a reaction to this message (as the bot).
493
- * @param emoji - Unicode emoji, custom `{ name, id }`, `:name:`, `name:id`, or `<:name:id>`
494
- */
622
+ /** React to this message with an emoji. */
495
623
  async react(emoji) {
496
- const emojiStr = await this.resolveEmojiForReaction(emoji);
497
- const route = `${Routes.channelMessageReaction(this.channelId, this.id, emojiStr)}/@me`;
498
- await this.client.rest.put(route);
624
+ return reactToMessage(this, emoji);
499
625
  }
500
- /**
501
- * Remove the bot's reaction, or a specific user's reaction if userId is provided.
502
- * @param emoji - Unicode emoji, custom `{ name, id }`, `:name:`, `name:id`, or `<:name:id>`
503
- * @param userId - If provided, removes that user's reaction (requires moderator permissions)
504
- */
626
+ /** Remove a reaction (bot's own or a user's if ID is provided). */
505
627
  async removeReaction(emoji, userId) {
506
- const emojiStr = await this.resolveEmojiForReaction(emoji);
507
- const route = `${Routes.channelMessageReaction(this.channelId, this.id, emojiStr)}/${userId ?? "@me"}`;
508
- await this.client.rest.delete(route);
628
+ return removeMessageReaction(this, emoji, userId);
509
629
  }
510
- /**
511
- * Remove all reactions from this message.
512
- * Requires moderator permissions.
513
- */
630
+ /** Remove all reactions from this message. */
514
631
  async removeAllReactions() {
515
- await this.client.rest.delete(Routes.channelMessageReactions(this.channelId, this.id));
632
+ return removeAllMessageReactions(this);
516
633
  }
517
- /**
518
- * Remove all reactions of a specific emoji from this message.
519
- * @param emoji - Unicode emoji, custom `{ name, id }`, `:name:`, `name:id`, or `<:name:id>`. Requires moderator permissions.
520
- */
634
+ /** Remove all reactions of a specific emoji. */
521
635
  async removeReactionEmoji(emoji) {
522
- const emojiStr = await this.resolveEmojiForReaction(emoji);
523
- await this.client.rest.delete(Routes.channelMessageReaction(this.channelId, this.id, emojiStr));
636
+ return removeMessageReactionEmoji(this, emoji);
524
637
  }
525
- /**
526
- * Fetch users who reacted with the given emoji.
527
- * @param emoji - Unicode emoji or custom `{ name, id }`
528
- * @param options - limit (1–100), after (user ID for pagination)
529
- * @returns Array of User objects
530
- */
638
+ /** Fetch users who reacted with a specific emoji. */
531
639
  async fetchReactionUsers(emoji, options) {
532
- const emojiStr = await this.resolveEmojiForReaction(emoji);
533
- const params = new URLSearchParams();
534
- if (options?.limit != null) params.set("limit", String(options.limit));
535
- if (options?.after) params.set("after", options.after);
536
- const qs = params.toString();
537
- const route = Routes.channelMessageReaction(this.channelId, this.id, emojiStr) + (qs ? `?${qs}` : "");
538
- const data = await this.client.rest.get(route);
539
- const list = Array.isArray(data) ? data : data?.users ?? [];
540
- return list.map((u) => this.client.getOrCreateUser(u));
640
+ return fetchMessageReactionUsers(this, emoji, options);
641
+ }
642
+ /** Fetch reaction users with pagination metadata. */
643
+ async fetchReactionUsersPage(emoji, options) {
644
+ return fetchMessageReactionUsersPage(this, emoji, options);
541
645
  }
542
646
  };
543
647
  export {