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