import { Client, ClientOptions, Listener } from "@wolfstar/http-framework"; import { OptionalWebSocketManagerOptions, ShardRange, WebSocketManager } from "@discordjs/ws"; import { API, Client as Client$1 } from "@discordjs/core"; import { Awaitable, Cache as Cache$1, CacheEntityName, CacheEntityTypes, CacheFactory, CachePolicies, EntityCache, GatewaySessionStore, IterableEntityCache } from "@wolfstar/plugin-cache"; import { APIActionRowComponent, APIAllowedMentions, APIApplication, APIApplicationCommand, APIApplicationCommandOption, APIApplicationCommandPermission, APIApplicationEmoji, APIAttachment, APIAuditLogChange, APIAuthorizingIntegrationOwnersMap, APIAutoModerationAction, APIAutoModerationRule, APIAutoModerationRuleTriggerMetadata, APIAvatarDecorationData, APIButtonComponentWithCustomId, APIButtonComponentWithSKUId, APIButtonComponentWithURL, APIChannel, APIChannelMention, APIChannelSelectComponent, APICheckboxComponent, APICheckboxGroupComponent, APICheckboxGroupOption, APICollectibles, APIComponentInActionRow, APIComponentInMessageActionRow, APIContainerComponent, APIEmbed, APIEmbedAuthor, APIEmbedField, APIEmbedFooter, APIEmbedImage, APIEmbedProvider, APIEmbedThumbnail, APIEmbedVideo, APIEmoji, APIEntitlement, APIExtendedInvite, APIFileComponent, APIFileUploadComponent, APIGuild, APIGuildForumDefaultReactionEmoji, APIGuildForumTag, APIGuildMember, APIGuildOnboarding, APIGuildOnboardingPrompt, APIGuildOnboardingPromptOption, APIGuildPreview, APIGuildScheduledEvent, APIGuildScheduledEventEntityMetadata, APIGuildScheduledEventRecurrenceRule, APIGuildScheduledEventRecurrenceRuleNWeekday, APIGuildWelcomeScreen, APIGuildWidget, APIGuildWidgetMember, APIIncidentsData, APIInviteChannel, APIInviteGuild, APILabelComponent, APIMediaGalleryComponent, APIMediaGalleryItem, APIMentionableSelectComponent, APIMessage, APIMessageActivity, APIMessageCall, APIMessageComponent, APIMessageComponentEmoji, APIMessageInteractionMetadata, APIMessageReference, APIMessageRoleSubscriptionData, APIMessageSharedClientTheme, APIMessageTopLevelComponent, APIModalComponent, APIOverwrite, APIPartialEmoji, APIPoll, APIPollAnswer, APIRadioGroupComponent, APIRadioGroupOption, APIReaction, APIRole, APIRoleSelectComponent, APIRoleTags, APISKU, APISectionComponent, APISelectMenuDefaultValue, APISelectMenuOption, APISeparatorComponent, APISoundboardSound, APIStageInstance, APISticker, APIStickerPack, APIStringSelectComponent, APISubscription, APITeam, APITeamMember, APITemplate, APITextDisplayComponent, APITextInputComponent, APIThreadChannel, APIThreadMember, APIThumbnailComponent, APIUnfurledMediaItem, APIUser, APIUserPrimaryGuild, APIUserSelectComponent, APIVoiceRegion, APIWebhook, ActivityFlags, ActivityType, AllowedMentionsTypes, ApplicationCommandOptionType, ApplicationCommandPermissionType, ApplicationCommandType, ApplicationFlags, ApplicationIntegrationType, ApplicationRoleConnectionMetadataType, ApplicationWebhookEventStatus, ApplicationWebhookEventType, AttachmentFlags, AuditLogEvent, AutoModerationActionType, AutoModerationRuleEventType, AutoModerationRuleKeywordPresetType, AutoModerationRuleTriggerType, ButtonStyle, ChannelFlags, ChannelType, EntryPointCommandHandlerType, FileUploadType, ForumLayoutType, GatewayActivity, GatewayActivityAssets, GatewayActivityUpdateData, GatewayAutoModerationActionExecutionDispatchData, GatewayChannelInfoDispatchData, GatewayChannelPinsUpdateDispatchData, GatewayDispatchEvents, GatewayDispatchPayload, GatewayGuildDeleteDispatchData, GatewayGuildIntegrationsUpdateDispatchData, GatewayGuildMemberRemoveDispatchData, GatewayGuildMembersChunkDispatchData, GatewayGuildRoleDeleteDispatchData, GatewayGuildScheduledEventUserAddDispatchData, GatewayGuildScheduledEventUserRemoveDispatchData, GatewayGuildSoundboardSoundDeleteDispatchData, GatewayIntegrationDeleteDispatchData, GatewayIntentBits, GatewayInviteCreateDispatchData, GatewayInviteDeleteDispatchData, GatewayMessageDeleteBulkDispatchData, GatewayMessageDeleteDispatchData, GatewayMessageReactionRemoveAllDispatchData, GatewayPresenceClientStatus, GatewayPresenceUpdateData, GatewayRateLimitedDispatchData, GatewayReadyDispatchData, GatewayRequestChannelInfoField, GatewayThreadDeleteDispatchData, GatewayThreadListSync, GatewayThreadMembersUpdateDispatchData, GatewayTypingStartDispatchData, GatewayVoiceServerUpdateDispatchData, GatewayWebhooksUpdateDispatchData, GuildDefaultMessageNotifications, GuildExplicitContentFilter, GuildMemberFlags, GuildOnboardingMode, GuildOnboardingPromptType, GuildPremiumTier, GuildScheduledEventEntityType, GuildScheduledEventPrivacyLevel, GuildScheduledEventRecurrenceRuleFrequency, GuildScheduledEventRecurrenceRuleMonth, GuildScheduledEventRecurrenceRuleWeekday, GuildScheduledEventStatus, GuildSystemChannelFlags, GuildVerificationLevel, GuildWidgetStyle, InteractionContextType, InteractionType, InviteTargetType, InviteType, Locale, LocalizationMap, MessageActivityType, MessageFlags, MessageReferenceType, MessageSearchAuthorType, MessageSearchEmbedType, MessageSearchHasType, MessageSearchSortMode, NameplatePalette, OAuth2Scopes, OverwriteType, PermissionFlagsBits, PollLayoutType, PresenceUpdateReceiveStatus, PresenceUpdateStatus, RESTAPIPoll, RESTGetAPIGuildVanityUrlResult, RESTPatchAPIChannelJSONBody, RESTPatchAPIGuildJSONBody, RESTPostAPIApplicationCommandsJSONBody, RESTPostAPIChannelMessageJSONBody, RESTPostAPIGuildsJSONBody, ReactionType, RoleFlags, SKUFlags, SelectMenuDefaultValueType, SeparatorSpacingSize, Snowflake, SortOrderType, StageInstancePrivacyLevel, StickerFormatType, TeamMemberMembershipState, TeamMemberRole, ThreadAutoArchiveDuration, ThreadChannelType, UserFlags, VideoQualityMode } from "discord-api-types/v10"; import { APIActualInvite, ActionRowComponent, Activity as Activity$1, ActivityFlagsBitField as ActivityFlagsBitField$1, AnnouncementChannel as AnnouncementChannel$1, AnnouncementThreadChannel as AnnouncementThreadChannel$1, Attachment as Attachment$1, AttachmentFlagsBitField as AttachmentFlagsBitField$1, AutoModerationRule as AutoModerationRule$1, BitField, BitField as BitField$1, BitFieldResolvable, BitFieldResolvable as BitFieldResolvable$1, CategoryChannel as CategoryChannel$1, Channel as Channel$1, ChannelFlagsBitField as ChannelFlagsBitField$1, ChannelSelectMenuComponent as ChannelSelectMenuComponent$1, Component as Component$1, ContainerComponent as ContainerComponent$1, DMChannel as DMChannel$1, Embed as Embed$1, Emoji as Emoji$1, Entitlement as Entitlement$1, FileComponent as FileComponent$1, FileUploadComponent as FileUploadComponent$1, ForumChannel as ForumChannel$1, GroupDMChannel as GroupDMChannel$1, InteractiveButtonComponent as InteractiveButtonComponent$1, Invite, LinkButtonComponent as LinkButtonComponent$1, MediaChannel as MediaChannel$1, MediaGalleryComponent as MediaGalleryComponent$1, MediaGalleryItem as MediaGalleryItem$1, MentionableSelectMenuComponent as MentionableSelectMenuComponent$1, Message as Message$1, MessageFlagsBitField as MessageFlagsBitField$1, Partialize as Partialize$1, PermissionsBitField, Poll as Poll$1, PollAnswer as PollAnswer$1, PremiumButtonComponent as PremiumButtonComponent$1, Presence as Presence$1, PrivateThreadChannel as PrivateThreadChannel$1, PublicThreadChannel as PublicThreadChannel$1, Reaction, RoleSelectMenuComponent as RoleSelectMenuComponent$1, SKU as SKU$1, SectionComponent as SectionComponent$1, SeparatorComponent as SeparatorComponent$1, SoundboardSound as SoundboardSound$1, StageChannel as StageChannel$1, StageInstance as StageInstance$1, Sticker as Sticker$1, StickerPack as StickerPack$1, StringSelectMenuComponent as StringSelectMenuComponent$1, Structure as Structure$1, Subscription as Subscription$1, TextChannel as TextChannel$1, TextDisplayComponent as TextDisplayComponent$1, TextInputComponent as TextInputComponent$1, ThumbnailComponent as ThumbnailComponent$1, UnfurledMediaItem as UnfurledMediaItem$1, User as User$1, UserSelectMenuComponent as UserSelectMenuComponent$1, VoiceChannel as VoiceChannel$1, VoiceState as VoiceState$1, Webhook as Webhook$1 } from "@discordjs/structures"; import { BaseImageURLOptions, EmojiURLOptions, ImageURLOptions, REST, RawFile } from "@discordjs/rest"; import { Collection, ReadonlyCollection } from "@discordjs/collection"; /** * The name of any permission. */ export type PermissionsString = keyof typeof PermissionFlagsBits; /** * Anything a `PermissionsBitField` can be built from. */ export type PermissionResolvable = BitFieldResolvable$1; /** * A 32-bit flags bitfield, resolving flag names to `bigint`s and serializing to a `number`. */ export declare abstract class NumberFlagsBitField extends BitField$1 { static resolve(bit: BitFieldResolvable$1): bigint; toJSON(): number; } export type ActivityFlagsString = keyof typeof ActivityFlags; export type ActivityFlagsResolvable = BitFieldResolvable$1; /** * The flags of a presence activity. */ export declare class ActivityFlagsBitField extends ActivityFlagsBitField$1 { static resolve(bit: BitFieldResolvable$1): bigint; } export type AttachmentFlagsString = keyof typeof AttachmentFlags; export type AttachmentFlagsResolvable = BitFieldResolvable$1; /** * The flags of a message attachment. */ export declare class AttachmentFlagsBitField extends AttachmentFlagsBitField$1 { static resolve(bit: BitFieldResolvable$1): bigint; } export type ChannelFlagsString = keyof typeof ChannelFlags; export type ChannelFlagsResolvable = BitFieldResolvable$1; /** * The flags of a channel. */ export declare class ChannelFlagsBitField extends ChannelFlagsBitField$1 { static resolve(bit: BitFieldResolvable$1): bigint; } export type MessageFlagsString = keyof typeof MessageFlags; export type MessageFlagsResolvable = BitFieldResolvable$1; /** * The flags of a message. */ export declare class MessageFlagsBitField extends MessageFlagsBitField$1 { static resolve(bit: BitFieldResolvable$1): bigint; } export type GuildMemberFlagsString = keyof typeof GuildMemberFlags; export type GuildMemberFlagsResolvable = BitFieldResolvable$1; /** * The flags of a guild member. */ export declare class GuildMemberFlagsBitField extends NumberFlagsBitField { static readonly Flags: typeof GuildMemberFlags; } export type IntentsString = keyof typeof GatewayIntentBits; export type IntentsResolvable = BitFieldResolvable$1; /** * The gateway intents to identify with. */ export declare class IntentsBitField extends NumberFlagsBitField { static readonly Flags: typeof GatewayIntentBits; } export type RoleFlagsString = keyof typeof RoleFlags; export type RoleFlagsResolvable = BitFieldResolvable$1; /** * The flags of a role. */ export declare class RoleFlagsBitField extends NumberFlagsBitField { static readonly Flags: typeof RoleFlags; } export type SystemChannelFlagsString = keyof typeof GuildSystemChannelFlags; export type SystemChannelFlagsResolvable = BitFieldResolvable$1; /** * The flags of a guild's system channel, deciding which system messages are suppressed. */ export declare class SystemChannelFlagsBitField extends NumberFlagsBitField { static readonly Flags: typeof GuildSystemChannelFlags; } export type UserFlagsString = keyof typeof UserFlags; export type UserFlagsResolvable = BitFieldResolvable$1; /** * The flags (badges) of a user. */ export declare class UserFlagsBitField extends NumberFlagsBitField { static readonly Flags: typeof UserFlags; } export type ApplicationFlagsString = keyof typeof ApplicationFlags; export type ApplicationFlagsResolvable = BitFieldResolvable$1; /** * The flags of an application. */ export declare class ApplicationFlagsBitField extends NumberFlagsBitField { static readonly Flags: typeof ApplicationFlags; } export type SKUFlagsString = keyof typeof SKUFlags; export type SKUFlagsResolvable = BitFieldResolvable$1; /** * The flags of a SKU. */ export declare class SKUFlagsBitField extends NumberFlagsBitField { static readonly Flags: typeof SKUFlags; } /** * Anything with a `toJSON` method, like the builders of `@discordjs/builders` and the structures of this package. */ interface JSONEncodable { toJSON(): Value; } /** * Data a file can be resolved from: its contents, a path on disk, a URL, a stream, or a blob. */ type BufferResolvable = Uint8Array | ArrayBuffer | string | Blob | AsyncIterable; /** * A file described along with its attachment metadata, like discord.js's `AttachmentPayload`. */ interface AttachmentPayload { /** * The contents of the file. */ attachment: BufferResolvable; /** * The name of the file, inferred from a path or URL when omitted. */ name?: string; /** * The description (alt text) of the file. */ description?: string; /** * The title of the file. */ title?: string; /** * Whether to mark the file as a spoiler, by prefixing its name with `SPOILER_`. */ spoiler?: boolean; /** * The duration of a voice message, in seconds. */ duration?: number; /** * The waveform of a voice message, base64-encoded. */ waveform?: string; } /** * A file to attach to a message: a {@link RawFile} of `@discordjs/rest`, an {@link AttachmentPayload}, anything with * a `toJSON` returning one (e.g. an attachment builder), or its raw contents. */ type AttachmentResolvable = RawFile | AttachmentPayload | JSONEncodable | BufferResolvable; /** * The mentions a message may ping, in camel case like discord.js's `MessageMentionOptions`, or the raw API object. */ type MessageMentionOptions = APIAllowedMentions | { parse?: readonly AllowedMentionsTypes[]; roles?: readonly string[]; users?: readonly string[]; /** * Whether to ping the author of the message replied to. */ repliedUser?: boolean; }; /** * The message a message replies to. */ interface ReplyOptions { /** * The message, or its ID. */ messageReference: string | { readonly id: string; readonly channelId?: string; }; /** * Whether to fail when the message no longer exists, rather than sending a regular message. * * @default GatewayClientOptions.failIfNotExists ?? true */ failIfNotExists?: boolean; } /** * The message a message forwards. */ interface ForwardOptions { /** * The message, or its ID along with `channel`. */ message: string | { readonly id: string; readonly channelId: string; readonly guildId?: string | null; }; /** * The channel of the message, or its ID, needed when `message` is an ID. */ channel?: string | { readonly id: string; }; /** * The guild of the message, or its ID. */ guild?: string | { readonly id: string; }; } /** * A poll to create, in camel case like discord.js's `PollCreateData`. */ interface PollCreateData { question: { text: string; }; answers: readonly { text?: string; emoji?: string | { id?: string | null; name?: string | null; }; }[]; /** * How long the poll lasts, in hours. */ duration: number; allowMultiselect?: boolean; layoutType?: PollLayoutType; } /** * The options every message payload accepts, when creating and editing. * * @remarks * The keys of the raw REST body (`allowed_mentions`, `message_reference`, `sticker_ids`...) are accepted too, and are * sent as they are: the camel case ones win when both are set. */ interface BaseMessageOptions { content?: string | null; embeds?: readonly (APIEmbed | JSONEncodable)[] | null; components?: readonly (APIMessageTopLevelComponent | JSONEncodable)[] | null; /** * The files to upload. */ files?: readonly AttachmentResolvable[]; /** * The attachments to keep, when editing, or their metadata. */ attachments?: readonly (Partial | JSONEncodable>)[]; allowedMentions?: MessageMentionOptions; flags?: MessageFlagsResolvable; poll?: PollCreateData | RESTAPIPoll | JSONEncodable; } /** * The options to send a message with. */ interface MessageCreateOptions extends BaseMessageOptions, Omit, keyof BaseMessageOptions> { tts?: boolean; nonce?: string | number; /** * Whether to refuse sending a message whose nonce was used recently, deduplicating retries. */ enforceNonce?: boolean; /** * The message to reply to. */ reply?: ReplyOptions; /** * The message to forward. */ forward?: ForwardOptions; /** * The stickers to send, or their IDs. */ stickers?: readonly (string | { readonly id: string; })[]; } /** * The options to edit a message with. */ interface MessageEditOptions extends BaseMessageOptions {} /** * The options only webhooks accept. */ interface WebhookMessageOptions { username?: string; avatarURL?: string; /** * The name of the post to create, for webhooks of forum and media channels. */ threadName?: string; /** * The tags of the post to create, for webhooks of forum and media channels. */ appliedTags?: readonly string[]; /** * Whether to allow components on a message of a webhook not owned by an application. */ withComponents?: boolean; } /** * The thread a webhook message is in, for webhooks of forum and media channels, or of a thread's parent. */ interface WebhookThreadOptions { threadId?: string; } /** * The options to send a message through a webhook with. */ interface WebhookMessageCreateOptions extends BaseMessageOptions, WebhookMessageOptions, WebhookThreadOptions { tts?: boolean; } /** * The options to edit a message sent by a webhook with. */ interface WebhookMessageEditOptions extends MessageEditOptions, WebhookThreadOptions {} /** * Anything with a client, e.g. a structure, which a {@link MessagePayload} reads its defaults from. */ type MessageTarget = { readonly client: GatewayClient; } | GatewayClient; /** * The extra flags telling a {@link MessagePayload} what its target accepts. */ interface MessagePayloadContext { /** * Whether the message is sent through a webhook, which accepts {@link WebhookMessageOptions}. */ webhook?: boolean; /** * Whether the message is edited rather than created: `null` clears fields instead of leaving them out. */ edit?: boolean; } /** * The options of any message payload. */ type MessagePayloadOptions = MessageCreateOptions & WebhookMessageOptions; /** * Anything accepted where a message payload is expected: its content, its options, or a {@link MessagePayload}. */ type MessagePayloadResolvable = string | Options | MessagePayload; /** * The body and files a {@link MessagePayload} resolved to, ready for `@discordjs/core`. */ interface ResolvedMessagePayload { body: Body; files: RawFile[] | undefined; } /** * Normalizes the options of a message into the REST body and files Discord expects, like discord.js's * `MessagePayload`: camel case options, builders, reply and forward shortcuts, stickers, polls, and files from paths, * URLs, streams, or buffers. * * @example * ```typescript * const payload = MessagePayload.create(channel, { * content: "Awoo", * reply: { messageReference: message }, * files: ["./wolf.png", { attachment: buffer, name: "howl.ogg", description: "A howl" }], * }); * await channel.send(payload); * ``` */ export declare class MessagePayload { /** * What the message is sent to: the structure it is sent through, or the client. */ readonly target: MessageTarget; /** * The options the payload was created with. */ readonly options: MessagePayloadOptions; /** * What the target accepts. */ readonly context: Readonly; /** * The resolved REST body, set by {@link MessagePayload.resolveBody}. */ body: RESTPostAPIChannelMessageJSONBody | null; /** * The resolved files, set by {@link MessagePayload.resolveFiles}. */ files: RawFile[] | null; constructor(target: MessageTarget, options: MessagePayloadOptions, context?: MessagePayloadContext); /** * The client the target belongs to. */ get client(): GatewayClient; /** * Whether the message is sent through a webhook. */ get isWebhook(): boolean; /** * Whether the message is edited rather than created. */ get isEdit(): boolean; /** * Resolves the content of the message: `null` clears it when editing, and is left out otherwise. */ makeContent(): string | null | undefined; /** * Resolves the REST body of the message. */ resolveBody(): this; /** * Resolves the files of the message, reading them from disk, the network, or streams. */ resolveFiles(): Promise; /** * Resolves both the body and the files, for `@discordjs/core`. */ resolve(): Promise>; private resolveNonce; private resolveList; private resolveAllowedMentions; private resolveReference; private resolvePoll; private resolveAttachments; private clientOption; /** * Creates a payload, or returns it when it already is one. * * @param target What the message is sent to. * @param options The message, its content, or a payload. * @param context What the target accepts. */ static create(target: MessageTarget, options: MessagePayloadResolvable, context?: MessagePayloadContext): MessagePayload; /** * Resolves a file to upload, reading paths from disk and downloading URLs. * * @param file The file. */ static resolveFile(file: AttachmentResolvable): Promise; private static attachmentPayload; private static toJSON; private static id; } /** * The message defaults read from the client's options. */ interface GatewayClientMessageDefaults { /** * The mentions every message may ping, unless it sets its own. */ allowedMentions?: MessageMentionOptions; /** * Whether replies fail when the message they reply to no longer exists, unless they set it themselves. * * @default true */ failIfNotExists?: boolean; } /** * The symbol under which a {@link Structure} stores its raw API data, shared with `@discordjs/structures`. */ export declare const kData: unique symbol; /** * The symbol of the method patching a {@link Structure}'s raw data in place, shared with `@discordjs/structures`. */ export declare const kPatch: unique symbol; /** * The symbol of the method cloning a {@link Structure}, shared with `@discordjs/structures`. */ export declare const kClone: unique symbol; /** * The symbol under which a {@link Structure} stores its relations: the structures its manager resolved from the cache, * like a message's author or a channel's guild. */ export declare const kRelations: unique symbol; /** * The symbol under which a {@link Structure} stores the client that built it, see {@link StructureMixin.client}. */ export declare const kClient: unique symbol; /** * The symbol of the optional method a mixin defines to drop the relations a patch invalidates, called by * {@link StructureMixin}'s patch before the data is patched. Mixins cannot override the patch itself: the first mixin * defining a member wins, and {@link StructureMixin} comes first. * * @internal */ export declare const kPatchRelations: unique symbol; declare const kTimestamps: unique symbol; /** * The members every structure of this package has on top of `@discordjs/structures`' own: relations resolved from the * cache, public patch/clone methods, and parsed timestamps. * * @remarks * It is mixed into {@link Structure} and into every class extending one of `@discordjs/structures`' structures, which * also have to call {@link initStructure} from their constructor: * * ```typescript * export interface User extends StructureMixin {} * export class User extends BaseUser { * public constructor(data: Partial, relations: object = {}) { * super(data); * initStructure(this, data, relations); * } * } * Mixin(User, [StructureMixin]); * ``` * * @typeParam Data The raw API data the structure wraps. * @typeParam Relations The relations of the structure, resolved from the cache by its manager. */ export declare class StructureMixin { /** * The raw API data of this structure. */ protected [kData]: Readonly; /** * The relations of this structure, resolved from the cache by its manager. Public only so that * {@link StructureMixin.dropRelations} can check relation names against it. * * @internal */ [kRelations]: Relations; private [kTimestamps]?; /** * The client that built this structure, set by its manager. * * @internal */ [kClient]?: GatewayClient; /** * The client that instantiated this structure, like discord.js's `Base#client`: the one whose manager built it, or * the most recently constructed {@link GatewayClient} for structures built by hand from a raw payload. * * @remarks * It is not part of the structure's data, so it is neither serialized by `toJSON` nor stored in the cache. */ get client(): GatewayClient; /** * The ID of this structure, like discord.js's `Base#valueOf`, so that structures compare and sort by ID. Structures * without an ID (a member whose user is unknown, a voice state, ...) are their own value. */ valueOf(): string | this; /** * Resolves a relation like discord.js's getters do: what the manager resolved when it built this structure, else a * synchronous read of the cache. `null` when neither has it, the cache is asynchronous, or no client exists. * * @param name The name of the relation. * @param read Reads the related structure from the client's cache, synchronously. */ protected lazyRelation(name: string, read: (client: GatewayClient) => Result | null | undefined): Result | null; /** * Patches the raw data of this structure in place, with a shallow merge. * * @param data The updated data. * @returns This structure. */ [kPatch](data: Readonly>): this; /** * Creates a copy of this structure, optionally patching the copy. * * @param patch The data to patch the copy with. * @returns The copy. */ [kClone](patch?: Readonly>): this; /** Parses a timestamp once when constructing or patching a structure. */ protected optimizeTimestamp(key: string, value: string | null | undefined): void; /** Gets a timestamp previously parsed by `optimizeData`. */ protected optimizedTimestamp(key: string): number | null; /** * Forgets resolved relations, e.g. when a patch carries fresher data for them. * * @param names The names of the relations. */ protected dropRelations(...names: (keyof this[typeof kRelations] & string)[]): void; /** * Forgets the relations whose ID a patch changes, e.g. a channel's parent when the patch moves it to another * category. A patch carrying the same ID keeps the relation. * * @param data The patch. * @param fields The names of the relations, mapped to the raw field holding their ID. */ protected dropChangedRelations(data: object, fields: Partial>): void; } /** * {@link StructureMixin.lazyRelation} for the channel mixins, which are not structures themselves. * * @param structure The structure. * @param name The name of the relation. * @param read Reads the related structure from the cache of the client, synchronously. * @internal */ export declare function lazyRelation(structure: object, name: string, read: (client: GatewayClient) => Result | null | undefined): Result | null; /** * Sets up the members {@link StructureMixin} adds, from the constructor of a structure extending one of * `@discordjs/structures`'. * * @param structure The structure being constructed. * @param data The raw API data it was constructed with. * @param relations The related structures, resolved from the cache by the structure's manager. */ export declare function initStructure(structure: object, data: object, relations: object): void; export interface Structure extends StructureMixin {} /** * The base class of the structures `@discordjs/structures` has no counterpart for: its `Structure`, with * {@link StructureMixin} mixed in. * * @remarks * Structures can be built from any raw payload, be it a gateway dispatch, a cache hit, or a REST response. Their * {@link StructureMixin.client | client} is the one whose manager built them, the most recently constructed one * otherwise. * * @typeParam Data The raw API data this structure wraps. * @typeParam Omitted The keys the structure's `DataTemplate` strips from the stored data. */ export declare abstract class Structure extends Structure$1 { /** * @param data The raw API data. * @param relations The related structures, resolved from the cache by the structure's manager. */ constructor(data: Readonly>, relations?: object); } /** * Binds a structure to the client that built it, see {@link StructureMixin.client}. * * @param structure The structure. * @param client The client. * @returns The structure. * @internal */ export declare function bindClient(structure: Value, client: GatewayClient): Value; /** * Gets the timestamp, in milliseconds, a snowflake was created at. * * @param id The snowflake. */ export declare function snowflakeTimestamp(id: string): number; /** * The relations of an {@link AutoModerationRule}, resolved from the cache by the guild's rule manager. */ export interface AutoModerationRuleRelations { guild?: Guild | null; } export interface AutoModerationRule extends StructureMixin {} /** * An auto moderation rule of a guild: `@discordjs/structures`' `AutoModerationRule`, with its trigger, actions, and * exemptions, and actions through the client. */ export declare class AutoModerationRule extends AutoModerationRule$1 { /** * @param data The raw rule. * @param relations The guild as resolved from the cache, by the guild's rule manager. */ constructor(data: APIAutoModerationRule, relations?: AutoModerationRuleRelations); /** * The settings of the rule's trigger, camel-cased like discord.js's `AutoModerationRule#triggerMetadata`. */ get triggerMetadata(): AutoModerationTriggerMetadata; /** * The actions of the rule, camel-cased like discord.js's `AutoModerationRule#actions`. */ get actions(): AutoModerationAction[]; get exemptRoles(): readonly string[]; get exemptChannels(): readonly string[]; get guild(): Guild | null; /** * Edits the rule. * * @param options The fields to edit, and the reason for the audit log. */ edit(options: AutoModerationRuleEditOptions): Promise; setName(name: string, reason?: string): Promise; setEventType(eventType: AutoModerationRuleEventType, reason?: string): Promise; setEnabled(enabled?: boolean, reason?: string): Promise; setActions(actions: readonly (AutoModerationActionOptions | APIAutoModerationAction)[], reason?: string): Promise; setExemptRoles(roles: readonly IdResolvable[], reason?: string): Promise; setExemptChannels(channels: readonly IdResolvable[], reason?: string): Promise; /** * Sets the keywords of a keyword rule, keeping the rest of its trigger. */ setKeywordFilter(keywordFilter: readonly string[], reason?: string): Promise; /** * Sets the regular expressions of a keyword rule, keeping the rest of its trigger. */ setRegexPatterns(regexPatterns: readonly string[], reason?: string): Promise; /** * Sets the keyword presets of a keyword preset rule, keeping the rest of its trigger. */ setPresets(presets: readonly AutoModerationRuleKeywordPresetType[], reason?: string): Promise; /** * Sets the keywords exempt from the rule, keeping the rest of its trigger. */ setAllowList(allowList: readonly string[], reason?: string): Promise; /** * Sets how many mentions a message may have, for a mention spam rule. */ setMentionTotalLimit(mentionTotalLimit: number, reason?: string): Promise; /** * Sets whether a mention spam rule detects mention raids. */ setMentionRaidProtectionEnabled(enabled?: boolean, reason?: string): Promise; /** * Deletes the rule. * * @param reason The reason for the audit log. */ delete(reason?: string): Promise; private editTrigger; } /** * The raw API data a {@link StructureMixin | structure} wraps. */ type RawAPIType> = Value extends StructureMixin ? Type : never; /** * A function building a {@link StructureMixin | structure} out of its raw API data. */ type StructureCreator, Raw extends RawAPIType = RawAPIType> = (data: Partial) => Value; /** * Whether an {@link Awaitable} is a promise, rather than the value itself. * * @internal */ declare function isPromiseLike(value: Awaitable): value is Promise; /** * Waits for a list of {@link Awaitable}s like `Promise.all`, then calls a function with their values. Unlike * `Promise.all`, it stays synchronous when none of them is a promise, which is what lets a synchronous cache build * structures without awaiting them. * * @param values The values, some of which may be promises. * @param callback The function to call with the values. * @internal */ declare function whenAll(values: T, callback: (values: { -readonly [Index in keyof T]: Awaited; }) => Awaitable): Awaitable; /** * Resolves the relations of a structure again from its current data, and assigns them to that same structure: what * keeps a long-lived instance from holding the relations of the day it was built. Synchronous when `hydrate` is. * * @param value The structure. * @param hydrate Builds a structure of the same data, with its relations. * @returns The structure it was given. * @internal */ declare function refreshRelations>(value: Value, hydrate: (data: RawAPIType) => Awaitable>): Awaitable; /** * Picks the cached structures of some IDs, in their order, skipping the ones that are not cached: the equivalent of * the collections discord.js fills from its caches, e.g. `MessageMentions#channels`. * * @param ids The IDs. * @param cached The cached structures, by ID. * @internal */ declare function pickCached(ids: readonly string[], cached: ReadonlyMap | undefined): Map; /** * Reads the cached structures of some IDs, synchronously when every read is, skipping duplicates and the IDs that * are not cached. The {@link Awaitable} counterpart of discord.js's collections filled from its caches. * * @param ids The IDs. * @param get Reads the structure of an ID. * @internal */ declare function whenCachedMap(ids: Iterable, get: (id: string) => Awaitable): Awaitable>; /** * The cache of a manager, as in the discord.js RFC #11426: it hands out {@link StructureMixin | structures}. * * @remarks * Every method is {@link Awaitable}: synchronous on an in-memory cache ({@link Cache.synchronous}), a promise on a * remote one. `await` works with both. * * @typeParam Value The structure the cache hands out. * @typeParam Raw The raw API data the structure wraps. */ interface Cache, Raw extends RawAPIType = RawAPIType> { /** * Whether every method answers synchronously, never with a promise. */ readonly synchronous: boolean; /** * The function used to construct instances of the structure this cache holds. */ readonly construct: StructureCreator; /** * Adds or updates data in the cache, returning the instantiated structure. If the item exists, it patches it with * the new data unless `overwrite` is true. If it does not exist, it constructs a new instance and stores it. */ add(data: Partial, overwrite?: boolean): Awaitable; /** * Clears all items from the cache. */ clear(): Awaitable; /** * Deletes an item from the cache. */ delete(key: string): Awaitable; /** * Retrieves an item from the cache. */ get(key: string): Awaitable; /** * Gets the number of items in the cache. */ getSize(): Awaitable; /** * Checks if an item exists in the cache. */ has(key: string): Awaitable; /** * Sets an item in the cache. */ set(key: string, value: Value): Awaitable; } /** * The cache of the manager of one channel or thread: the keyed methods of the {@link Cache} it reads, taking the ID * of the entity alone instead of the key built by `resolveKey`, like the caches of discord.js's channel managers. * * @typeParam Value The structure the cache hands out. */ interface ScopedCache> { /** * Whether every method answers synchronously, never with a promise. */ readonly synchronous: boolean; /** * Deletes an item from the cache. */ delete(id: string): Awaitable; /** * Retrieves an item from the cache. */ get(id: string): Awaitable; /** * Checks if an item exists in the cache. */ has(id: string): Awaitable; } /** * Scopes a {@link Cache} keyed by more than an ID to the entries of one parent. * * @param cache The cache. * @param resolveKey Builds the key of the cache from the ID of an entity. * @internal */ declare function scopeCache>(cache: Cache, resolveKey: (id: string) => string): ScopedCache; /** * The options of the cache of one entity, set per entity through the client's `cacheOptions` option. */ interface CacheEntityOptions { /** * The maximum amount of entries the cache holds, the oldest one being evicted when a new one would exceed it. `0` * holds nothing. * * @default Infinity */ maxSize?: number; /** * Decides which entries `maxSize` never evicts, like discord.js's `LimitedCollection#keepOverLimit`: called with * the oldest entries in turn, the first one it answers `false` for is evicted. When it answers `true` for all of * them, the cache grows past `maxSize`. * * @default undefined */ keepOverLimit?: (value: any, key: string, cache: Map) => boolean; } /** * What a {@link CacheConstructor} receives as its third argument: how the client keys and refreshes the entity, and * the entity's `cacheOptions`. */ interface CacheConstructorOptions, Raw extends RawAPIType = RawAPIType> extends CacheEntityOptions { /** * Gets the cache key of raw data. {@link Cache.add} must store under it: most entities are not keyed by their * `id` alone (a member is keyed by its guild and user, a message by its channel and ID, ...). */ keyOf: (data: Partial) => string; /** * Resolves the relations of an instance again (e.g. `member.voice`), and returns that same instance. Call it on * what {@link Cache.get} and {@link Cache.add} hand out, or long-lived instances keep the relations of the day * they were built. */ refresh: (value: Value) => Value; } /** * A class building the {@link Cache} of an entity, as in the discord.js RFC #11426: what the client's * `cacheConstructor` option takes. It is instantiated once per entity. * * @remarks * The constructor receives `(creator, name, options)`: * * - `creator` builds a structure out of raw data, it is the cache's {@link Cache.construct}; * - `name` is the name of the entity, e.g. `"users"`; * - `options` are the {@link CacheConstructorOptions}: `keyOf`, which `add` must key its entries with, `refresh`, * to call on what `get` and `add` hand out, and the entity's `cacheOptions` (`maxSize`). * * Extending `CollectionCache` and forwarding the three arguments to `super` is the recommended way: it does all of * the above. The cache must be synchronous. * * A cache that is not a `Map` cannot be enumerated, so what needs to list its entries does not work with it: the * dispatch cascades (`GUILD_DELETE` and `CHANNEL_DELETE` leave the entries of the guild or channel behind), the * reconciliation of the guilds left while offline on `READY`, the granular emoji and sticker diff events, and * `listCached`. * * @example * ```typescript * class LoggingCache< * Value extends StructureMixin, * Raw extends RawAPIType = RawAPIType, * > extends CollectionCache { * public override delete(key: string): boolean { * console.log(`${this.name}: ${key} removed`); * return super.delete(key); * } * } * * const client = new GatewayClient({ intents, cacheConstructor: LoggingCache }); * ``` */ type CacheConstructor = new >(creator: StructureCreator, name: CacheEntityName, options: CacheConstructorOptions) => Cache; /** * Reads what a {@link Cache} holds under a key as is: for a cache of instances (a `Map`, e.g. `CollectionCache`), the * instance itself, without re-resolving its relations as `get` does. Other caches are read with `get`. * * @param cache The cache. * @param key The key of the entry. * @internal */ declare function peekCache, Raw extends RawAPIType = RawAPIType>(cache: Cache, key: string): Awaitable; /** * Keeps the value of an {@link Awaitable} that is no promise: what a getter can use without awaiting. * * @param value The value, or a promise of it. * @returns The value, or `undefined` for a promise. * @internal */ declare function syncOnly(value: Awaitable): T | undefined; /** * Reads an entry of a {@link Cache} for a relation getter: as the cache holds it, see {@link peekCache}. * * @param cache The cache. * @param key The key of the entry. * @returns The entry, or `undefined` when it is not cached or the cache is asynchronous. * @internal */ declare function readCached>(cache: Cache, key: string): Value | undefined; type MaybeId = string | null | undefined; /** @internal */ declare function cachedGuild(client: GatewayClient, guildId: MaybeId): Guild | undefined; /** @internal */ declare function cachedChannel(client: GatewayClient, channelId: MaybeId): AnyChannel | undefined; /** @internal */ declare function cachedUser(client: GatewayClient, userId: MaybeId): User | undefined; /** @internal */ declare function cachedMember(client: GatewayClient, guildId: MaybeId, userId: MaybeId): GuildMember | undefined; /** @internal */ declare function cachedRole(client: GatewayClient, guildId: MaybeId, roleId: MaybeId): Role<""> | undefined; /** @internal */ declare function cachedMessage(client: GatewayClient, channelId: MaybeId, messageId: MaybeId): Message | undefined; /** @internal */ declare function cachedVoiceState(client: GatewayClient, guildId: MaybeId, userId: MaybeId): VoiceState | undefined; /** @internal */ declare function cachedPresence(client: GatewayClient, guildId: MaybeId, userId: MaybeId): Presence | undefined; /** * How the cache of the application answers, for the types of the getters reading it. Empty by default: the cache is * synchronous (the default `CollectionCache`, or synchronous `@wolfstar/plugin-cache` stores), and the getters are * typed as their plain value, like discord.js's. * * @remarks * An application whose cache is asynchronous (a Redis store) declares it once, which types every such getter as a * promise, the way it answers at runtime with that cache: * * ```typescript * declare module "@wolfstar/plugin-gateway" { * interface GatewayCacheConfig { * asynchronous: true; * } * } * * if (await member.kickable) await member.kick(); * ``` * * Without the declaration the types still say `boolean` while the getter answers a promise, which is always truthy: * declare it whenever a store is asynchronous. */ interface GatewayCacheConfig {} /** * {@link CacheRead} for a given configuration. */ type CacheReadOf = Config extends { asynchronous: true; } ? Promise : T; /** * What a getter computed from the cache answers: the value itself with a synchronous cache, a promise of it with an * asynchronous one. Its type follows {@link GatewayCacheConfig}; `await` works with both. */ type CacheRead = CacheReadOf; /** * Types what a getter computed from the cache as a {@link CacheRead}. * * @internal */ declare function cacheRead(value: Awaitable): CacheRead; /** * Manages the API methods of a data model, like discord.js's `BaseManager`. */ export declare abstract class BaseManager { /** * The client that instantiated this manager. */ readonly client: GatewayClient; constructor(client: GatewayClient); } /** * Manages the API methods of a data model along with a collection of instances, like discord.js's `DataManager`. * * @typeParam Value The structure this manager holds. * @typeParam Args The arguments identifying an entity, e.g. `[id]` or `[guildId, userId]`. */ export declare abstract class DataManager, Args extends readonly string[]> extends BaseManager { /** * The cache of the items this manager holds. */ abstract readonly cache: Cache; /** * Gets the cache key of an entity, the one {@link DataManager.cache} takes. * * @param args The arguments identifying the entity. */ abstract resolveKey(...args: Args): string; /** * The cache of the items this manager holds, like discord.js's `DataManager#valueOf`. */ valueOf(): Cache; /** * Resolves a structure or a cache key to a structure. * * @param value A structure, returned as is, or the cache key of an entity (its ID, for managers keyed by ID). * @returns The structure, or `null` if the key is not cached. */ resolve(value: Value | string): Awaitable; /** * Resolves a structure or an ID to an ID. * * @param value A structure, or an ID. * @returns The ID, or `null` if the value is neither. */ resolveId(value: Value | string): string | null; } /** * The options to fetch an entity with. */ export interface FetchOptions { /** * Whether to skip the cache lookup and always hit the API. * * @default false */ force?: boolean; /** * Whether to store the entity fetched from the API in the cache. * * @default true */ cache?: boolean; } /** * The options of {@link CachedManager._add}. */ export interface AddOptions { /** * The cache key of the entity, when it cannot be derived from its data. */ id?: string; /** * Extra arguments handed to the manager's `createStructure`. */ extras?: unknown[]; } /** * The arguments of a method of a manager the client holds for every guild: they start with the guild's ID, which a * manager built for one guild (`guild.members`, `client.guilds.members(guildId)`) fills in. * * @typeParam InGuild Whether the manager was built for one guild. * @typeParam Args The arguments after the guild's ID. */ export type GuildArgs = InGuild extends true ? Args : [guildId: string, ...Args]; /** * Types the arguments of a method declared with {@link GuildArgs}, which always start with the guild's ID once * {@link fillGuildId} filled it in. * * @param args The arguments of the method. * @internal */ export declare function withGuildId(args: readonly unknown[]): [guildId: string, ...Args]; /** * Makes methods of a manager the client holds for every guild fill in the guild's ID: on an instance built for one * guild, they call the client's manager, which holds the state and the cache, with that ID first. * * @param target The class of the manager. * @param getManager Gets the client's manager. * @param methods The names of the methods taking the guild's ID first. * @internal */ export declare function fillGuildId(target: abstract new (...args: any[]) => Manager, getManager: (client: GatewayClient) => object, methods: readonly string[]): void; /** * Manages the API methods of a data model with a mutable cache of instances: the `CachedManager` of the discord.js * RFC #11426. * * @remarks * Reads go through {@link CachedManager.cache}: `client.users.cache.get(id)`. The cache is built by the client's * `cacheConstructor` (`CollectionCache` by default) and shared by every manager of the same entity. * * Caches keyed by more than an ID take the key built by `resolveKey`: * `client.members.cache.get(client.members.resolveKey(guildId, userId))`. The managers of a guild, a channel or a * thread take the ID alone: `guild.members.cache.get(userId)`. * * @typeParam Name The name of the entity this manager holds. * @typeParam Value The structure this manager builds. * @typeParam Args The arguments identifying an entity, e.g. `[id]` or `[guildId, userId]`. * @typeParam FetchArgs The arguments `fetch` and `refresh` take, which differ from `Args` on a manager built for one * guild. */ export declare abstract class CachedManager, Args extends readonly string[], FetchArgs extends readonly string[] = Args> extends DataManager { /** * The cache of this manager's entity. * * @example * ```typescript * const user = await client.users.cache.get(userId); * ``` * * @remarks * On a manager built for one guild (`guild.members`), it is the client's cache taking the ID of the entity alone. * `get`, `has`, `set` and `delete` cost the same as on the client's; `getSize` and `clear` scan the keys of every * guild to find the ones of this guild, unlike discord.js's per-guild collections: avoid calling them for every * guild in a loop. */ readonly cache: Cache; /** * The name of the entity this manager holds. */ protected readonly name: Name; /** * Wraps raw data in this manager's structure: the RFC's `StructureCreator`. * * @param data The raw data. * @param extras The extra arguments passed to {@link CachedManager._add}. */ protected abstract createStructure(data: CacheEntityTypes[Name], ...extras: unknown[]): Value; /** * @param client The client. * @param name The name of the entity this manager holds. * @param guildId The guild whose entities {@link CachedManager.cache} is narrowed to, for the managers the client * holds for every guild. */ constructor(client: GatewayClient, name: Name, guildId?: string); private createGuildCache; /** * Gets {@link CachedManager.cache} from the client. Managers whose entity spans several caches override it. */ protected createCache(): Cache; /** * The raw store of this manager's entity, or `undefined` when it is not cached. */ protected get rawStore(): EntityCache | undefined; /** * Adds an API payload to the cache and returns its structure, as in the RFC. * * @remarks * The payload is written with `cache.add`: a cached entry is patched and returned, and with a cache of instances * (`CollectionCache`) that is the very instance the application may already hold. An entity that is not cached is * built and stored. * * With `cache` set to `false`, a patched clone is returned (or the entity is built) and the cache is left * untouched. The same goes for an entry the `filter` of the entity's policy rejects, whose cached entry is deleted * on top of that: a rejected update must not leave the outdated entry behind. * * @param data The raw data. * @param cache Whether to write to the cache. * @param options The cache key, when it cannot be derived from the data, and the extras of `createStructure`. * @internal */ _add(data: CacheEntityTypes[Name], cache?: boolean, { id, extras }?: AddOptions): Promise; /** * Patches the cached entry of a key, if any, with the fields an endpoint answered without the entity itself. * * @remarks * Like every write of the managers, it follows the `filter` of the entity's policy: an entry whose patched data is * rejected is deleted from the cache. * * @param key The cache key of the entry. * @param patch The fields to patch, or a function computing them from the cached entry, `undefined` to leave it. * @internal */ _patchCached(key: string, patch: Partial | ((cached: Value) => Partial | undefined)): Promise; private accepts; private detached; private derivedKey; private resolveRelations; /** * Gets the cached structure of the entity raw data describes, or builds one from the data when it is not cached. * Used to resolve the relations of other structures, e.g. a message's author. Synchronous when the cache is. * * @param data The raw data. * @internal */ _resolveData(data: CacheEntityTypes[Name]): Awaitable; /** * Gets a guild from the cache, to resolve the `guild` of a structure. Synchronous when the guild cache is. * * @remarks * The guild does not resolve its own channel relations, see `GuildManager._getShallow`. * * @param guildId The ID of the guild, if the structure belongs to one. * @returns The guild, or `null` when there is no ID or the guild is not cached. */ protected cachedGuild(guildId: string | null | undefined): Awaitable; /** * Builds the structure of raw data, resolving its relations from the cache; synchronous when every cache the * relations are read from is. Without relations to resolve, the same as `createStructure`. * * @param data The raw data. * @param extras The extra arguments passed to {@link CachedManager._add}. * @internal */ _hydrate(data: CacheEntityTypes[Name], ...extras: unknown[]): Awaitable; /** * Wraps raw data in this manager's structure, bound to this manager's client, without resolving its relations: the * creator handed to this entity's cache, always synchronous. * * @param data The raw data. * @param extras The extra arguments passed to {@link CachedManager._add}. * @internal */ _construct(data: CacheEntityTypes[Name], ...extras: unknown[]): Value; /** * Builds the structure of raw data with {@link CachedManager._hydrate}, bound to this manager's client. * * @param data The raw data. * @param extras The extra arguments passed to {@link CachedManager._add}. * @internal */ _build(data: CacheEntityTypes[Name], extras?: unknown[]): Awaitable; /** * Gets an entity from the cache, fetching it from the API (and caching it) on a cache miss. * * @example * ```typescript * await client.users.fetch(userId); // cache first * await client.users.fetch(userId, { force: true }); // always the API * await client.users.fetch(userId, { force: true, cache: false }); // the API, without storing the result * ``` * * @param args The arguments identifying the entity, optionally followed by {@link FetchOptions}. */ fetch(...args: [...FetchArgs] | [...FetchArgs, FetchOptions]): Promise; /** * Fetches an entity from the API, bypassing and then updating the cache. Same as `fetch(...args, { force: true })`. * * @param args The arguments identifying the entity. */ refresh(...args: FetchArgs): Promise; /** * Gets the cache key of raw data. * * @param data The raw data. */ abstract keyOf(data: CacheEntityTypes[Name]): string; /** * Fetches the raw data of an entity from the API. * * @param args The arguments identifying the entity. */ protected abstract fetchRaw(...args: Args): Promise; /** * Gets this entity's raw store when it can enumerate its entries, for the `listCached` methods. * * @returns The store, or `undefined` when this entity is not cached. * @throws {TypeError} When the store cannot enumerate its entries. */ protected iterableCache(): IterableEntityCache | undefined; /** * Runs a raw store operation, reporting its failure through `cacheError`. With the client's `cacheErrors: "miss"`, * a failure resolves to `fallback`, otherwise it is rethrown. Synchronous when the operation is. */ protected guard(operation: CacheErrorContext["operation"], key: string | null, run: () => Awaitable, fallback: T): Awaitable; } /** * The fields of an auto moderation rule that can be edited. */ export interface AutoModerationRuleEditOptions { name?: string; eventType?: AutoModerationRuleEventType; /** * The trigger's settings, camel-cased or raw. Discord replaces them as a whole. */ triggerMetadata?: AutoModerationTriggerMetadataOptions | APIAutoModerationRuleTriggerMetadata; /** * The actions, camel-cased or raw. */ actions?: readonly (AutoModerationActionOptions | APIAutoModerationAction)[]; enabled?: boolean; exemptRoles?: readonly IdResolvable[]; exemptChannels?: readonly IdResolvable[]; reason?: string; } /** * The options to create an auto moderation rule with. */ export interface AutoModerationRuleCreateOptions extends AutoModerationRuleEditOptions { name: string; eventType: AutoModerationRuleEventType; triggerType: AutoModerationRuleTriggerType; actions: readonly (AutoModerationActionOptions | APIAutoModerationAction)[]; } /** * Manages the auto moderation rules of one guild. */ export declare class AutoModerationRuleManager extends CachedManager<"autoModerationRules", AutoModerationRule, [ruleId: string]> { readonly guildId: string; constructor(client: GatewayClient, guildId: string); protected createStructure(data: CacheEntityTypes["autoModerationRules"]): AutoModerationRule; keyOf(data: CacheEntityTypes["autoModerationRules"]): string; resolveKey(ruleId: string): string; _hydrate(data: CacheEntityTypes["autoModerationRules"]): Awaitable; /** * Fetches every rule of the guild, and caches them. */ fetchAll(): Promise; /** * Creates a rule. * * @param options The rule's name, trigger, actions, and exemptions. */ create(options: AutoModerationRuleCreateOptions): Promise; /** * Edits a rule. * * @param ruleId The ID of the rule. * @param options The fields to edit, and the reason for the audit log. */ edit(ruleId: string, options: AutoModerationRuleEditOptions): Promise; /** * Deletes a rule. * * @param ruleId The ID of the rule. * @param reason The reason for the audit log. */ delete(ruleId: string, reason?: string): Promise; protected fetchRaw(ruleId: string): Promise; } /** * Any class, abstract or not. */ export type MixinBase = abstract new (...args: any[]) => object; type UnionToIntersection = (Union extends unknown ? (value: Union) => void : never) extends ((value: infer Intersection) => void) ? Intersection : never; /** * The members `Mixins` add to a class extending `Base`, for the interface declaring them. * * @remarks * Following `@discordjs/structures`' `MixinTypes`, the members `Base` already declares are left out: `Base` keeps typing * them, even though the mixins' implementations win at runtime, which must therefore stay assignable to `Base`'s types. * {@link StructureMixin}'s members are left out too: the interface extends it directly, so they keep their `this` type. * * ```typescript * export interface TextChannel * extends * StructureMixin>, * MixinTypes]> {} * export class TextChannel extends BaseTextChannel {} * Mixin(TextChannel, [TextChannelMixin]); * ``` * * @typeParam Base The class the mixins are mixed into. * @typeParam Mixins The instance types of the mixins. */ export type MixinTypes = Omit, keyof Base | keyof StructureMixin>; /** * Copies the members of every mixin onto the prototype of `target`, the way `@discordjs/structures`' `Mixin` does. * * @remarks * Prototype members are copied. Static `DataTemplate`, `optimizeData`, and `enrichToJSON` hooks are * combined with the target's behavior, following `@discordjs/structures`. * Mixins must not rely on their constructor running. Declare an interface with the same name as `target`, extending * every mixin, so the members are visible to the type system as well: * * ```typescript * export interface TextChannel extends TextChannelMixin {} * export class TextChannel extends Channel {} * Mixin(TextChannel, [TextChannelMixin]); * ``` * * Members already defined on `target` itself win over the mixins', and earlier mixins win over later ones. * * @param target The class to mix into. * @param mixins The classes whose members are copied. */ export declare function Mixin(target: MixinBase, mixins: readonly MixinBase[]): void; export interface BaseChannelMixin extends Channel$1, StructureMixin, ChannelRelations> {} /** * Adds what every channel shares on top of `@discordjs/structures`' `Channel`: its relations, and the REST actions * every channel supports. */ export declare class BaseChannelMixin { /** * Forgets the parent when a patch moves the channel. * * @internal */ [kPatchRelations](data: object): void; /** * Whether the channel is partial, like discord.js's `BaseChannel#partial`: only direct messages can be, see * `Partials.Channel`. */ get partial(): boolean; /** * The flags of the channel. */ get flags(): Readonly; get createdTimestamp(): number; get createdAt(): Date; toString(): `<#${string}>`; /** * Deletes the channel, or closes it for a direct message, and drops it from the cache. * * @param reason The reason for the audit log. */ delete(reason?: string): Promise; /** * Fetches the channel from the API and patches this structure with the result. */ fetch(): Promise; } export interface ChannelOwnerMixin extends Channel {} /** * Adds the owner of threads and group direct messages. */ export declare class ChannelOwnerMixin { get ownerId(): string | null; } export interface ChannelParentMixin extends Channel {} /** * Adds the parent (a category, or a channel for threads) and the age restriction of guild channels. */ export declare class ChannelParentMixin { get parentId(): string | null; /** * The parent of the channel, from the cache, like discord.js's `parent`: the category of a guild channel, or the * channel a thread belongs to. `null` when it has none, when it is not cached, or when the cache is * asynchronous. */ get parent(): AnyChannel | null; get nsfw(): boolean; } export interface ChannelSlowmodeMixin extends Channel {} /** * Adds the slowmode of channels users can send messages in. */ export declare class ChannelSlowmodeMixin { /** * The slowmode, in seconds. `0` when disabled. */ get rateLimitPerUser(): number; /** * Sets the slowmode. * * @param rateLimitPerUser The slowmode, in seconds, `0` to disable it. * @param reason The reason for the audit log. */ setRateLimitPerUser(rateLimitPerUser: number, reason?: string): Promise; } export interface GuildChannelMixin extends Channel {} /** * Adds the fields every guild channel has, threads included. */ export declare class GuildChannelMixin { /** * The ID of the guild, when the payload included it. */ get guildId(): string | null; /** * The guild, from the cache. `null` when the guild is not cached, or when the cache is asynchronous: use * `fetchGuild()` to always get it. */ get guild(): Guild | null; /** * Fetches the guild, cache first. `null` when the payload did not include the guild's ID. */ fetchGuild(): Promise; get name(): string; /** * Whether this channel has the same data as another one, like discord.js's `GuildChannel#equals`: the same ID, type, * name, topic, position, and permission overwrites (in any order). The category is not compared, as in discord.js. * `false` for anything that is neither a channel nor a raw one. * * @param other The channel, or raw channel, to compare with. */ equals(other: unknown): boolean; /** * Edits the channel. * * @param options The fields to edit, and the reason for the audit log. */ edit(options: GuildChannelEditOptions): Promise; setName(name: string, reason?: string): Promise; /** * Creates a copy of the channel in its guild: same type, name, settings, and overwrites. * * @param options The fields to change on the copy. */ clone(options?: Partial): Promise; } /** * The raw fields any emoji carries: a custom emoji has an ID, a Unicode one only a name. */ export type EmojiData = Pick & Partial>; export interface Emoji extends StructureMixin {} /** * An emoji, a custom one (with an ID) or a Unicode one: `@discordjs/structures`' `Emoji`, with its identifier, image * URL, and mention. * * @typeParam Data The raw emoji data this structure wraps. * @typeParam Relations The related structures, resolved from the cache. */ export declare class Emoji extends Emoji$1 { /** * @param data The raw emoji. * @param relations The related structures, resolved from the cache. */ constructor(data: Data, relations?: Relations); get animated(): boolean; /** * The form reactions routes expect: `name:id` for custom emojis, the URL-encoded emoji for Unicode ones. */ get identifier(): string; get createdAt(): Date | null; /** * Gets the URL of the custom emoji's image, `null` for a Unicode emoji. Animated emojis default to a GIF. * @param options The image options. */ imageURL(options?: EmojiURLOptions): string | null; /** * The emoji as it is written in a message: `<:name:id>`, ``, or the Unicode emoji itself. */ toString(): string; } /** * Anything identifying an emoji: a Unicode emoji, a custom emoji mention (``), a `name:id` pair, a bare * emoji ID, or any object carrying `id`/`name`/`animated` (an {@link Emoji}, a raw `APIPartialEmoji`, ...). */ export type EmojiIdentifierResolvable = string | { id?: string | null; name?: string | null; animated?: boolean | null; }; /** * The emoji of a reaction or of a poll answer: a Unicode emoji, or a custom one known only by its ID and name. */ export declare class ReactionEmoji extends Emoji { /** * Resolves anything {@link EmojiIdentifierResolvable} to the identifier reaction routes expect. * * @param emoji The emoji to resolve. * @throws A `TypeError` when the value identifies no emoji. */ static resolveIdentifier(emoji: EmojiIdentifierResolvable): string; /** * Resolves anything {@link EmojiIdentifierResolvable} to the ID and name pair of welcome screens and onboarding. * * @param emoji The emoji to resolve. */ static resolvePartial(emoji: EmojiIdentifierResolvable): { id: string | null; name: string | null; animated: boolean; }; } export interface TextGuildChannelMixin extends Channel {} /** * Adds the actions of text-based channels of a guild only: discord.js's `TextBasedChannel` leaves them out of direct * messages, where Discord refuses them. */ export declare class TextGuildChannelMixin { /** * Deletes up to 100 messages at once, like discord.js's `TextBasedChannel#bulkDelete`. * * @param messages The messages, their IDs, or how many of the latest ones to delete. * @param filterOld Whether to drop the messages older than 14 days, which Discord refuses. * @returns The deleted messages by ID: the cached one, else a partial one with `Partials.Message`, else `undefined`. */ bulkDelete(messages: Collection | readonly MessageResolvable[] | number, filterOld?: boolean): Promise>; } /** * The options to move a channel or role among its siblings with. */ export interface SetPositionOptions { /** * Whether the position is an offset from the current one. */ relative?: boolean; /** * The reason for the audit log. */ reason?: string; } /** * A channel's new position, for {@link GuildChannelManager.setPositions}. */ export interface ChannelPosition { channel: IdResolvable; position?: number; /** * The new category, `null` to move the channel out of its category. */ parent?: IdResolvable | null; /** * Whether to copy the new category's overwrites, when `parent` is set. */ lockPermissions?: boolean; } /** * Manages the channels of one guild. Channels are cached by `client.channels`, which this manager writes to. */ export declare class GuildChannelManager extends BaseManager { readonly guildId: string; constructor(client: GatewayClient, guildId: string); /** * How many channels of the guild are cached, threads excluded: discord.js's `channelCountWithoutThreads`. A promise * with an asynchronous cache. * * @throws {TypeError} When the channel store cannot enumerate its entries. */ get channelCountWithoutThreads(): CacheRead; /** * Fetches every channel of the guild, threads excluded, and caches them. */ fetch(): Promise; /** * Creates a channel in the guild. * * @param options The channel's name, type, and settings. */ create(options: GuildChannelCreateOptions): Promise; /** * Edits a channel of the guild. * * @param channel The channel, or its ID. * @param options The fields to edit, and the reason for the audit log. */ edit(channel: IdResolvable, options: GuildChannelEditOptions): Promise; /** * Deletes a channel of the guild. * * @param channel The channel, or its ID. * @param reason The reason for the audit log. */ delete(channel: IdResolvable, reason?: string): Promise; /** * Moves several channels at once. * * @param positions The channels and their new positions or categories. * @param reason The reason for the audit log. */ setPositions(positions: readonly ChannelPosition[], reason?: string): Promise; /** * Moves a channel among the channels it is sorted with, like discord.js's `GuildChannelManager#setPosition`: the * channels of its category (the categories, for a category) and of its group, text-like or voice. * * @param channel The channel, or its ID. * @param position The index to move it to, in {@link GuildChannelManager.fetchSorted} order, or the offset to move it * by with `relative`. An index out of range leaves the channels where they are. * @param options Whether the position is relative, and the reason for the audit log. * @returns The moved channel. */ setPosition(channel: IdResolvable, position: number, options?: SetPositionOptions): Promise; /** * Fetches the channels a channel is sorted with, itself included, and caches them. * * @param channel The channel, or its ID. * @returns The channels, in the order Discord displays them. */ fetchSorted(channel: IdResolvable): Promise; } /** * The options to create or edit a role with. */ export interface RoleEditOptions { name?: string; /** * The primary color alone, see {@link RoleEditOptions.colors} for gradients. */ color?: number; colors?: Partial & { primaryColor: number; }; hoist?: boolean; permissions?: PermissionResolvable; mentionable?: boolean; /** * The icon: a data URI (`data:image/png;base64,...`), or anything `resolveImage` reads. `null` removes it. */ icon?: ImageResolvable | null; unicodeEmoji?: string | null; /** * The reason for the audit log. */ reason?: string; } /** * A role and the position to move it to. */ export interface RolePosition { role: string; position: number; } /** * Manages the {@link Role}s known to the client. * * `guild.roles` (or `client.guilds.roles(guildId)`) is this manager built for one guild, like discord.js's: * `cache` takes the role's ID alone, and the methods lose their `guildId` argument. * * @typeParam InGuild Whether the manager was built for one guild. */ export declare class RoleManager extends CachedManager<"roles", Role, [guildId: string, roleId: string], GuildArgs> { /** * The ID of the guild this manager was built for, `undefined` on `client.roles`. */ readonly guildId: InGuild extends true ? string : undefined; /** * @param client The client. * @param guildId The guild to build the manager for. */ constructor(client: GatewayClient, guildId?: string); protected createStructure(data: CacheEntityTypes["roles"]): Role; keyOf(data: CacheEntityTypes["roles"]): string; _hydrate(data: CacheEntityTypes["roles"]): Awaitable; resolveKey(guildId: string, roleId: string): string; /** * Fetches every role of a guild from the API, and caches them. * * @param guildId The ID of the guild. * @returns The roles, highest first. */ fetchAll(...args: GuildArgs): Promise; /** * Fetches how many members each role of a guild has, `@everyone` excluded. * * @param guildId The ID of the guild. * @returns The member count of every role, by role ID. */ fetchMemberCounts(...args: GuildArgs): Promise>; /** * Creates a role. * * @param guildId The ID of the guild. * @param options The role's fields. */ create(...args: GuildArgs): Promise; /** * Edits a role. * * @param guildId The ID of the guild. * @param roleId The ID of the role. * @param options The fields to edit. */ edit(...args: GuildArgs): Promise; /** * Deletes a role. * * @param guildId The ID of the guild. * @param roleId The ID of the role. * @param reason The reason for the audit log. */ delete(...args: GuildArgs): Promise; /** * Moves a role among the roles of its guild, like discord.js's `RoleManager#setPosition`. * * @param guildId The ID of the guild. * @param roleId The ID of the role. * @param position The index to move it to, lowest role first, or the offset to move it by with `relative`. An index * out of range leaves the roles where they are. * @param options Whether the position is relative and the reason for the audit log, or the reason alone. * @returns Every role of the guild, highest first. */ setPosition(...args: GuildArgs): Promise; /** * Moves several roles at once. * * @param guildId The ID of the guild. * @param positions The roles and their new positions. * @param reason The reason for the audit log. * @returns Every role of the guild, highest first. */ setPositions(...args: GuildArgs): Promise; /** * Compares the positions of two roles. * * @returns A negative number when `a` is lower, a positive one when it is higher, `0` when they are the same. */ comparePositions(a: Role, b: Role): number; /** * Fetches the `@everyone` role of a guild, whose ID is the guild's. * * @param guildId The ID of the guild. */ everyone(...args: GuildArgs): Promise; /** * Fetches the highest role of a guild. * * @param guildId The ID of the guild. */ highest(...args: GuildArgs): Promise; /** * Fetches the role Discord gives to the server boosters of a guild, if any. * * @param guildId The ID of the guild. */ premiumSubscriberRole(...args: GuildArgs): Promise; /** * Fetches the role Discord manages for a bot in a guild, if any. * * @param guildId The ID of the guild. * @param botId The ID of the bot user. */ botRoleFor(...args: GuildArgs): Promise; protected fetchRaw(guildId: string, roleId: string): Promise<{ id: import("discord-api-types/globals").Snowflake; name: string; color: number; colors: import("discord-api-types/v10").APIRoleColors; hoist: boolean; icon?: string | null; unicode_emoji?: string | null; position: number; permissions: import("discord-api-types/globals").Permissions; managed: boolean; mentionable: boolean; tags?: import("discord-api-types/v10").APIRoleTags; flags: import("discord-api-types/v10").RoleFlags; guild_id: string; }>; private store; } /** * The colors of a role: `primaryColor` alone for a solid color, with `secondaryColor` for a gradient, and with * `tertiaryColor` for the holographic style. */ export interface RoleColors { primaryColor: number; secondaryColor: number | null; tertiaryColor: number | null; } declare const kOptimizedPermissions: unique symbol; /** * A Discord guild role. */ export declare class Role extends Structure { [kRelations]: { guild?: Guild | null; }; protected [kOptimizedPermissions]: bigint; protected optimizeData(data: Partial): void; /** * The template used for removing data from the raw data stored for each role */ static readonly DataTemplate: Partial; /** * @param data - The raw data received from the API for the role * @param relations - The guild as resolved from the cache, by `client.roles` */ constructor(data: Partialize$1, relations?: { guild?: Guild | null; }); get id(): string; get guildId(): string; /** * The guild, from the cache. `null` when the guild is not cached, or when the cache is asynchronous: use * `fetchGuild()` to always get it. */ get guild(): Guild | null; /** * Fetches the guild, cache first. */ fetchGuild(): Promise; get name(): string; /** * The primary color of the role, `0` when it has none. */ get color(): number; /** * The primary color of the role as a `#rrggbb` string. */ get hexColor(): `#${string}`; get colors(): RoleColors; get position(): number; get permissions(): Readonly; /** * Fetches the role's permissions in a channel: its permissions and `@everyone`'s, with the channel's `@everyone` and * role overwrites applied. discord.js: `role.permissionsIn(channel)`. * * @param channel The channel, or its ID. Threads use their parent's overwrites. * * @deprecated Use {@link Role.permissionsIn}. When the guild or the channel may be missing from the cache, fetch * them first (`client.guilds.fetch(guildId)`, `client.channels.fetch(channelId)`), then call the method. */ fetchPermissionsIn(channel: AnyChannel | string): Promise>; /** * The role's permissions in a channel, like discord.js's `Role#permissionsIn`: its permissions and `@everyone`'s, * with the channel's `@everyone` and role overwrites applied, read from the cache. * * @param channel The channel, or the ID of a cached one. Threads use their parent's overwrites. * @throws A `GatewayError`: `ChannelUncached` when the channel is not cached. */ permissionsIn(channel: AnyChannel | string): CacheRead>; get hoist(): boolean; get managed(): boolean; get mentionable(): boolean; get icon(): string | null; get unicodeEmoji(): string | null; /** * What the role belongs to: a bot, an integration, the server boosters, or a subscription listing. Camel-cased * like discord.js's `Role#tags`. */ get tags(): RoleTagData | null; get flags(): Readonly; get createdTimestamp(): number; get createdAt(): Date; /** * Gets the URL of the role's icon, or `null` if it has none. * @param options The image options. */ iconURL(options?: ImageURLOptions): string | null; /** * Compares this role's position with another one's. * * @param role The role to compare with. * @returns A negative number when this role is lower, a positive one when it is higher, `0` when they are the same. */ comparePositionTo(role: Pick): number; /** * Whether the bot can edit this role, like discord.js's `Role#editable`: the role is not managed, and the bot has * `ManageRoles` and a higher role. * * @throws A `GatewayError`: `GuildUncachedMe` or `GuildUncached` on a cache miss. */ get editable(): CacheRead; /** * Whether the client's member can edit this role, i.e. it has `ManageRoles` and a higher role. * * @deprecated Use {@link Role.editable}. When the bot's member or its roles may be missing from the cache (a * filtered cache, a `plugin-broker` worker), fetch them first (`client.members.fetchMe(guildId)`, then * `me.roles.fetch()`), then read the getter. */ fetchEditable(): Promise; /** * Edits the role. * * @param options The fields to edit. * @returns This role, patched. */ edit(options: RoleEditOptions): Promise; setName(name: string, reason?: string): Promise; setColors(colors: Partial & { primaryColor: number; }, reason?: string): Promise; setHoist(hoist?: boolean, reason?: string): Promise; setPermissions(permissions: PermissionResolvable, reason?: string): Promise; setMentionable(mentionable?: boolean, reason?: string): Promise; /** * Sets the role's icon: a data URI (`data:image/png;base64,...`) or anything `resolveImage` reads. `null` removes it. */ setIcon(icon: ImageResolvable | null, reason?: string): Promise; setUnicodeEmoji(unicodeEmoji: string | null, reason?: string): Promise; /** * Moves the role among the roles of its guild, like discord.js's `Role#setPosition`. * * @param position The index to move it to, lowest role first, or the offset to move it by with `relative`. * @param options Whether the position is relative and the reason for the audit log, or the reason alone. */ setPosition(position: number, options?: SetPositionOptions | string): Promise; /** * Deletes the role. * * @param reason The reason for the audit log. */ delete(reason?: string): Promise; /** * Whether this role has the same data as another one, like discord.js's `Role#equals`: the same ID, name, colors, * `hoist`, position, permissions, `managed`, icon, and unicode emoji. * * @param role The role to compare with. */ equals(role: Role | null | undefined): boolean; toString(): `<@&${string}>` | "@everyone"; } /** * Several roles: an array of {@link RoleResolvable}s, or a `Collection` of roles, as discord.js takes them. */ type RoleResolvables = readonly RoleResolvable[] | ReadonlyCollection; /** * The options to edit a member with. */ export interface GuildMemberEditOptions { /** * The nickname, `null` to reset it. */ nick?: string | null; /** * The roles the member ends up with: an array of roles or IDs, or a `Collection` of roles. */ roles?: RoleResolvables; mute?: boolean; deaf?: boolean; /** * The voice channel to move the member to, `null` to disconnect them. */ channel?: string | null; /** * When the timeout ends, `null` to lift it. */ communicationDisabledUntil?: Date | number | null; flags?: GuildMemberFlagsResolvable; /** * The reason for the audit log. */ reason?: string; } /** * The options to edit the bot's own member with. Images are data URIs or anything `resolveImage` reads, `null` * removes them. */ export interface GuildMemberEditMeOptions { nick?: string | null; avatar?: ImageResolvable | null; banner?: ImageResolvable | null; bio?: string | null; reason?: string; } /** * The options to add a user to a guild with, through an OAuth2 access token with the `guilds.join` scope. */ export interface GuildMemberAddOptions { accessToken: string; nick?: string; /** * The roles the member starts with: an array of roles or IDs, or a `Collection` of roles. */ roles?: RoleResolvables; mute?: boolean; deaf?: boolean; } /** * The options to ban users with. */ export interface BanOptions { /** * How many seconds of the users' messages to delete, up to 7 days. */ deleteMessageSeconds?: number; reason?: string; } /** * The options to prune the inactive members of a guild with. */ export interface GuildPruneOptions { /** * How many days of inactivity make a member prunable. * * @default 7 */ days?: number; /** * The roles whose members are also prunable; members with roles are kept otherwise. */ roles?: readonly string[]; /** * Whether to only count the members that would be pruned. * * @default false */ dry?: boolean; /** * Whether to return the count; turning it off is recommended for large guilds. * * @default true */ count?: boolean; reason?: string; } /** * The options to request the members of a guild over the gateway with. Without `query` nor `userIds`, every member is * requested. */ export interface GuildMembersRequestOptions { /** * The prefix of the usernames and nicknames to match, `""` for every member. Exclusive with `userIds`. * * @default "" */ query?: string; /** * How many members to match with `query`, `0` for no limit (only with an empty `query`). * * @default 0 */ limit?: number; /** * The IDs of the users to request, up to 100. Exclusive with `query`. The ones that are not members are left out of * the result, and listed in the `not_found` of the `guildMembersChunk` data. An empty array is ignored, like omitting * it. */ userIds?: readonly string[]; /** * Whether to also receive (and cache) the members' presences. Needs the `GuildPresences` intent. * * @default false */ presences?: boolean; /** * The nonce identifying the request's chunks, up to 32 bytes. * * @default A random one. */ nonce?: string; /** * How long to wait for each chunk, in milliseconds, before rejecting with a `GuildMembersTimeoutError`. * * @default 120_000 */ time?: number; } /** * Manages the {@link GuildMember}s known to the client. * * `guild.members` (or `client.guilds.members(guildId)`) is this manager built for one guild, like discord.js's: * `cache` takes the user's ID alone, and the methods lose their `guildId` argument. * * @typeParam InGuild Whether the manager was built for one guild. */ export declare class GuildMemberManager extends CachedManager<"members", GuildMember, [guildId: string, userId: string], GuildArgs> { #private; /** * The ID of the guild this manager was built for, `undefined` on `client.members`. */ readonly guildId: InGuild extends true ? string : undefined; /** * @param client The client. * @param guildId The guild to build the manager for. */ constructor(client: GatewayClient, guildId?: string); protected createStructure(data: CacheEntityTypes["members"]): GuildMember; keyOf(data: CacheEntityTypes["members"]): string; /** * Adds a member to the cache, and its user to `client.users`. * * @internal */ _add(data: CacheEntityTypes["members"], cache?: boolean, options?: AddOptions): Promise; /** * Builds a member, resolving its user, guild, voice state, and presence from the cache. * * @remarks * The voice state and presence are built from their raw cache entries rather than by their managers, which resolve * their member in turn: their `member` is this very structure. * * @internal */ _hydrate(data: CacheEntityTypes["members"]): Awaitable; private readRelation; resolveKey(guildId: string, userId: string): string; /** * The bot's own member in a guild, from the cache: `null` when it is not cached. Use * {@link GuildMemberManager.fetchMe} to fall back to the API. * * @remarks * On the manager of a guild it is a getter, like discord.js's `guild.members.me`: the member itself, or a promise * of it with an asynchronous cache (see `GatewayCacheConfig`). On `client.members` it is a function taking the * guild's ID, synchronous when the member cache is. */ readonly me: InGuild extends true ? CacheRead : (guildId: string) => Awaitable; private cachedMe; /** * Fetches the bot's own member in a guild, cache first. * * @param guildId The ID of the guild. */ fetchMe(...args: GuildArgs): Promise; /** * Lists the members of a guild, in user ID order, and caches them. * * @param guildId The ID of the guild. * @param options How many members to list (up to 1000), and after which user ID. */ list(...args: GuildArgs): Promise; /** * Searches the members of a guild whose username or nickname starts with a query, and caches them. * * @param guildId The ID of the guild. * @param options The query, and how many members to return (up to 1000). */ search(...args: GuildArgs): Promise; /** * Requests the members of a guild over the gateway, every one of them by default, and caches them. discord.js: * `guild.members.fetch()` without a user. * * @remarks * Unlike {@link GuildMemberManager.list}, it gets the members of a large guild in one go, in chunks of up to 1000 * that are also emitted as `guildMembersChunk`. Requesting every member or a `query` needs the `GuildMembers` * intent. The request is sent on the guild's shard, which must be one this client runs. * * @param guildId The ID of the guild. * @param options Which members to request. * @returns The members, once the last chunk is cached. */ request(...args: GuildArgs): Promise; /** * Adds a cached chunk of members to the request with its nonce, resolving it with the last chunk. * * @internal */ handleChunk(members: GuildMember[], data: GatewayGuildMembersChunkDispatchData): void; /** * Rejects the request a `RATE_LIMITED` dispatch refers to, which gets no chunks at all. * * @internal */ handleRateLimited(data: GatewayRateLimitedDispatchData): void; /** * Adds a user to a guild, or fetches their member when they are in it already. * * @param guildId The ID of the guild. * @param userId The ID of the user. * @param options The access token and the member's initial state. */ add(...args: GuildArgs): Promise; /** * Edits a member. * * @param guildId The ID of the guild. * @param userId The ID of the member's user. * @param options The fields to edit. */ edit(...args: GuildArgs): Promise; /** * Edits the bot's own member. * * @param guildId The ID of the guild. * @param options The fields to edit. */ editMe(...args: GuildArgs): Promise; /** * Kicks a member. * * @param guildId The ID of the guild. * @param userId The ID of the member's user. * @param reason The reason for the audit log. */ kick(...args: GuildArgs): Promise; /** * Bans a user, member or not. * * @param guildId The ID of the guild. * @param userId The ID of the user. * @param options How many seconds of messages to delete, and the reason for the audit log. */ ban(...args: GuildArgs): Promise; /** * Lifts a user's ban. * * @param guildId The ID of the guild. * @param userId The ID of the user. * @param reason The reason for the audit log. */ unban(...args: GuildArgs): Promise; /** * Bans up to 200 users at once. * * @param guildId The ID of the guild. * @param userIds The IDs of the users. * @param options How many seconds of messages to delete, and the reason for the audit log. * @returns The users that were banned, and the ones that could not be. */ bulkBan(...args: GuildArgs): Promise<{ bannedUsers: string[]; failedUsers: string[]; }>; /** * Prunes the inactive members of a guild, or counts them with `dry`. * * @param guildId The ID of the guild. * @param options The inactivity threshold and the roles to include. * @returns How many members were (or would be) pruned, `null` when `count` is `false`. */ prune(...args: GuildArgs): Promise; /** * Adds a role to a member. * * @param guildId The ID of the guild. * @param userId The ID of the member's user. * @param roleId The ID of the role. * @param reason The reason for the audit log. */ addRole(...args: GuildArgs): Promise; /** * Removes a role from a member. * * @param guildId The ID of the guild. * @param userId The ID of the member's user. * @param roleId The ID of the role. * @param reason The reason for the audit log. */ removeRole(...args: GuildArgs): Promise; protected fetchRaw(guildId: string, userId: string): Promise<{ nick?: string | null; roles: import("discord-api-types/globals").Snowflake[]; premium_since?: string | null; pending?: boolean; communication_disabled_until?: string | null; avatar_decoration_data?: import("discord-api-types/v10").APIAvatarDecorationData | null; collectibles?: import("discord-api-types/v10").APICollectibles | null; flags: import("discord-api-types/v10").GuildMemberFlags; joined_at: string | null; avatar?: string | null; banner?: string | null; deaf: boolean; mute: boolean; user: import("discord-api-types/v10").APIUser; guild_id: string; }>; private store; private settle; private updateCachedRoles; } /** * Manages the roles of one {@link GuildMember}, like discord.js's `GuildMemberRoleManager`. * * @remarks * The one deliberate difference from discord.js: {@link GuildMemberRoleManager.cache} and the getters reading it * (`highest`, `hoist`, `color`, ...) are `Awaitable`, like `manager.cache.get`. They are synchronous with the default * in-memory cache and a promise with a remote store, so `await` works with both. * * They only know the roles the cache holds, and skip the ones it lacks without an error. With a filtered cache or a * `plugin-broker` worker that makes `highest` answer a lower role than the member's real one. Call * {@link GuildMemberRoleManager.fetch} first, or {@link GuildMemberRoleManager.fetchHighest}, where a hierarchy check * must not under-report. The other `fetch*` methods fall back to the API when a role is not cached. */ export declare class GuildMemberRoleManager extends BaseManager { /** * The member these roles belong to. */ readonly member: GuildMember; /** * @param member The member. */ constructor(member: GuildMember); /** * The member's guild, from the cache: `null` when it is not cached. */ get guild(): Guild | null; get guildId(): string; /** * Whether the member is partial, see {@link GuildMember.partial}. The roles of a partial member are not known. */ get partial(): boolean; /** * The ID of the member's user. * * @throws {GatewayError} `GuildMemberUserUnknown` when the member's payload did not include its user. */ get userId(): string; /** * The IDs of the member's roles, `@everyone` excluded. */ get ids(): readonly string[]; /** * The member's roles held in the cache, by ID, `@everyone` included. Roles that are not cached are skipped, without * an error: use {@link GuildMemberRoleManager.fetch} to get them all. */ get cache(): Awaitable>; /** * The member's highest cached role. `null` when none of their roles is cached, `@everyone` included. * * @remarks * Roles missing from the cache are skipped, not an error: the answer is the highest role the cache holds, so a * hierarchy check can compare a higher-ranked member as a lower one. Use {@link GuildMemberRoleManager.fetchHighest} * for an answer that is right on a cache miss, or `await member.roles.fetch()` before reading this. */ get highest(): Awaitable; /** * The cached role the member is displayed under in the member list, if any. */ get hoist(): Awaitable; /** * The highest cached role giving the member a color, if any. */ get color(): Awaitable; /** * The highest cached role giving the member an icon, if any. */ get icon(): Awaitable; /** * The server booster role, if the member has it and it is cached. */ get premiumSubscriberRole(): Awaitable; /** * The role Discord manages for the member, when the member is a bot and the role is cached. */ get botRole(): Awaitable; /** * Fetches the member's roles, `@everyone` included, highest first. */ fetch(): Promise; /** * Fetches the member's highest role, `@everyone` when they have no other. * * @remarks * The call for a role-hierarchy check that must be right on a cache miss: unlike * {@link GuildMemberRoleManager.highest}, it asks the API for the roles the cache lacks, so it never answers a lower * role than the member's real one. With a complete cache it makes no request. */ fetchHighest(): Promise; /** * Fetches the role the member is displayed under in the member list, if any. * * @deprecated Use {@link GuildMemberRoleManager.hoist}. See {@link GuildMemberRoleManager.fetchHighest} for the * cache-miss fallback. */ fetchHoist(): Promise; /** * Fetches the highest role giving the member a color, if any. * * @deprecated Use {@link GuildMemberRoleManager.color}. See {@link GuildMemberRoleManager.fetchHighest} for the * cache-miss fallback. */ fetchColor(): Promise; /** * Fetches the highest role giving the member an icon, if any. * * @deprecated Use {@link GuildMemberRoleManager.icon}. See {@link GuildMemberRoleManager.fetchHighest} for the * cache-miss fallback. */ fetchIcon(): Promise; /** * Fetches the server booster role, if the member has it. * * @deprecated Use {@link GuildMemberRoleManager.premiumSubscriberRole}. See * {@link GuildMemberRoleManager.fetchHighest} for the cache-miss fallback. */ fetchPremiumSubscriberRole(): Promise; /** * Fetches the role Discord manages for the member, when the member is a bot. * * @deprecated Use {@link GuildMemberRoleManager.botRole}. See {@link GuildMemberRoleManager.fetchHighest} for the * cache-miss fallback. */ fetchBotRole(): Promise; /** * Adds a role, or several, to the member. * * @remarks * A single role goes through its own endpoint and resolves to a copy of the member with the role added. Several * roles replace the member's roles, like {@link GuildMemberRoleManager.set}. * * @param roleOrRoles The role or its ID, or an array or `Collection` of them. * @param reason The reason for the audit log. * @returns The updated member. */ add(roleOrRoles: RoleResolvable | RoleResolvables, reason?: string): Promise; /** * Removes a role, or several, from the member. * * @remarks * A single role goes through its own endpoint and resolves to a copy of the member with the role removed. Several * roles replace the member's roles, like {@link GuildMemberRoleManager.set}. * * @param roleOrRoles The role or its ID, or an array or `Collection` of them. * @param reason The reason for the audit log. * @returns The updated member. */ remove(roleOrRoles: RoleResolvable | RoleResolvables, reason?: string): Promise; /** * Replaces the member's roles. * * @param roles The roles the member ends up with: an array of roles or IDs, or a `Collection` of roles. * @param reason The reason for the audit log. * @returns The member, patched. */ set(roles: RoleResolvables, reason?: string): Promise; /** * Creates another manager of the same member's roles. */ clone(): GuildMemberRoleManager; private fromCache; private resolveSingle; } /** * The raw assets of an activity, with the ID of the activity's application. */ export type RichPresenceAssetsData = GatewayActivityAssets & { application_id?: string | null; }; /** * The assets (images and their hover texts) of a rich presence activity. */ export declare class RichPresenceAssets extends Structure { /** * The ID of the application the assets belong to, needed to build the URLs of application assets. */ get applicationId(): string | null; /** * The hover text of the large image. */ get largeText(): string | null; /** * The hover text of the small image. */ get smallText(): string | null; /** * The ID of the large image asset, or an external asset in the `platform:id` form. */ get largeImage(): string | null; /** * The ID of the small image asset, or an external asset in the `platform:id` form. */ get smallImage(): string | null; /** * Gets the URL of the small image, or `null` if there is none or it comes from an unsupported platform. * * @param options The image options, ignored for external assets. */ smallImageURL(options?: ImageURLOptions): string | null; /** * Gets the URL of the large image, or `null` if there is none or it comes from an unsupported platform. * * @param options The image options, ignored for external assets. */ largeImageURL(options?: ImageURLOptions): string | null; } /** * The start and end of an activity. */ export interface ActivityTimestamps { /** * When the activity started, if known. */ start: Date | null; /** * When the activity ends, if known. */ end: Date | null; } /** * The party of an activity. */ export interface ActivityParty { /** * The ID of the party. */ id: string | null; /** * The size of the party, as `[current, max]`. */ size: readonly [current: number, max: number] | null; } /** * The emoji of a custom status activity. */ export interface ActivityEmoji { /** * The ID of the emoji, or `null` for a unicode emoji. */ id: string | null; /** * The name of the emoji, or the unicode character. */ name: string | null; /** * Whether the emoji is animated. */ animated: boolean; } export interface Activity extends StructureMixin {} /** * An activity of a user's presence: `@discordjs/structures`' `Activity`, with its timestamps, party, assets, emoji, * and buttons. */ export declare class Activity extends Activity$1 { /** * @param data The raw activity. * @param relations The related structures, resolved from the cache. */ constructor(data: GatewayActivity, relations?: object); /** * The URL of the stream, when the activity is being streamed. */ get url(): string | null; /** * What the user is currently doing. */ get details(): string | null; /** * The user's current party status, or the text of a custom status. */ get state(): string | null; /** * When the activity started and ends, if known. */ get timestamps(): ActivityTimestamps | null; /** * The party of the activity. */ get party(): ActivityParty | null; /** * The sync ID of the activity, which is the track ID for Spotify activities. * * @remarks This field is not documented by Discord. */ get syncId(): string | null; /** * The assets of the activity, when it is a rich presence. */ get assets(): RichPresenceAssets | null; /** * The flags describing the activity. */ get flags(): Readonly; /** * The emoji of a custom status activity. */ get emoji(): ActivityEmoji | null; /** * The labels of the buttons of a rich presence activity. */ get buttons(): string[]; /** * The time at which the activity was added to the user's session. */ get createdAt(): Date; /** * Whether this activity equals another: same name, type, URL, state, details and emoji. * * @param activity The activity to compare with. */ equals(activity: Activity | null | undefined): boolean; toString(): string; } /** * The status of a presence on each of the user's platforms; a missing platform means the user is offline there. */ export type ClientStatus = GatewayPresenceClientStatus; /** * The relations of a {@link Presence}, resolved from the cache by `client.presences`. */ export interface PresenceRelations { user?: User | null; member?: GuildMember | null; guild?: Guild | null; } export interface Presence extends StructureMixin {} /** * The presence of a user in a guild, their status and activities: `@discordjs/structures`' `Presence`, with its user, * member, and guild, and actions through the client. */ export declare class Presence extends Presence$1 { /** * @param data The raw presence. * @param relations The user, member, and guild as resolved from the cache, by `client.presences`. */ constructor(data: CacheEntityTypes["presences"], relations?: PresenceRelations); get userId(): string; get guildId(): string; /** * The status of the user, `offline` when the payload did not include it. */ get status(): PresenceUpdateReceiveStatus; get activities(): Activity[]; /** * The status of the user on each of their platforms, `null` when the payload did not include it. */ get clientStatus(): ClientStatus | null; /** * The user, from the cache. Presence payloads only carry the user's changed fields. */ get user(): User | null; get member(): GuildMember | null; get guild(): Guild | null; fetchMember(): Promise; fetchUser(): Promise; /** * Whether this presence has the same status, client status, and activities as another. * * @param presence The presence to compare with. */ equals(presence: Presence | null | undefined): boolean; } /** * The options to edit a voice state with, only applicable in stage channels. */ export interface VoiceStateEditOptions { /** * Whether the bot requests to become a speaker. Only available on the bot's own voice state. */ requestToSpeak?: boolean; /** * Whether the user is suppressed, i.e. moved to the audience. */ suppressed?: boolean; } /** * The relations of a {@link VoiceState}, resolved from the cache by `client.voiceStates`. */ export interface VoiceStateRelations { member?: GuildMember | null; guild?: Guild | null; channel?: AnyChannel | null; } export interface VoiceState extends StructureMixin {} /** * The voice state of a guild member: `@discordjs/structures`' `VoiceState`, with its member and guild, and actions * through the client. * * @remarks * Unlike `@discordjs/structures`', `deaf` and `mute` also account for the member's own deafen and mute; `serverDeaf` * and `serverMute` are the server-wide ones. */ export declare class VoiceState extends VoiceState$1 { protected optimizeData(data: Partial): void; /** * @param data The raw voice state. * @param relations The member and guild as resolved from the cache, by `client.voiceStates`. */ constructor(data: CacheEntityTypes["voiceStates"], relations?: VoiceStateRelations); [kPatch](data: Readonly>): this; /** * Whether the member is deafened server-wide. */ get serverDeaf(): boolean; /** * Whether the member is muted server-wide. */ get serverMute(): boolean; /** * Whether the member is streaming using "Screen Share", `false` when the payload did not include it. */ get streaming(): boolean; /** * The time at which the member requested to speak, or `null` if they did not. Only meaningful in stage channels. */ get requestToSpeakAt(): Date | null; /** * Whether the member is deafened, either by themselves or server-wide. */ get deaf(): boolean; /** * Whether the member is muted, either by themselves or server-wide. */ get mute(): boolean; /** * The member, from the payload or the cache. `null` when neither has it, or when the cache is asynchronous. */ get member(): GuildMember | null; /** * The guild, from the cache. */ get guild(): Guild | null; /** * The channel the member is connected to, from the cache, like discord.js's `VoiceState#channel`. `null` when they * are disconnected, when the channel is not cached, or when the cache is asynchronous. */ get channel(): AnyChannel | null; fetchMember(): Promise; fetchUser(): Promise; /** * Fetches the channel the member is connected to, `null` when they are disconnected. */ fetchChannel(): Promise; /** * Fetches the voice state from the API, and patches this structure with the result. */ fetch(): Promise; /** * Mutes or unmutes the member server-wide. */ setMute(mute?: boolean, reason?: string): Promise; /** * Deafens or undeafens the member server-wide. */ setDeaf(deaf?: boolean, reason?: string): Promise; /** * Moves the member to another voice channel, or disconnects them with `null`. */ setChannel(channel: string | null, reason?: string): Promise; disconnect(reason?: string): Promise; /** * Edits the voice state in a stage channel. * * @param options Whether to request to speak (the bot only), and whether the member is suppressed. */ edit(options: VoiceStateEditOptions): Promise; /** * Requests to speak in a stage channel, or withdraws the request. The bot's own voice state only. */ setRequestToSpeak(requestToSpeak?: boolean): Promise; /** * Moves the member to the audience of a stage channel, or invites them to speak. */ setSuppressed(suppressed?: boolean): Promise; private requireGuildId; private resolveTarget; } /** * The relations of a {@link GuildMember}, resolved from the cache by `client.members`. */ export interface GuildMemberRelations { user?: User; guild?: Guild | null; /** * The member's voice state, `null` when they are not connected. */ voice?: VoiceState | null; presence?: Presence | null; } /** * A {@link GuildMember} known to be partial, see {@link GuildMember.isPartial}. */ export type PartialGuildMember = GuildMember & { readonly partial: true; }; /** * A member of a Discord guild. * * @remarks * discord.js's `permissions`, `manageable`, `kickable`, ... are read from the cache like there: the plain value * with a synchronous cache, a promise of it with an asynchronous one, typed as a promise once `GatewayCacheConfig` * declares the cache asynchronous. They never call the API; their `fetch*` twins do, for what is not cached. * `member.roles` reads roles through the (possibly asynchronous) cache, so its getters are `Awaitable`. */ export declare class GuildMember extends Structure { [kRelations]: GuildMemberRelations; protected optimizeData(data: Partial): void; /** * @param data The raw member. * @param relations The member's user and guild as resolved from the cache, by `client.members`. */ constructor(data: CacheEntityTypes["members"], relations?: GuildMemberRelations); /** * The ID of the member's user, or `null` if the payload did not include it. */ get id(): string | null; get guildId(): string; /** * The guild, from the cache. `null` when the guild is not cached, or when the cache is asynchronous: use * `fetchGuild()` to always get it. */ get guild(): Guild | null; /** * Fetches the guild, cache first. */ fetchGuild(): Promise; [kPatch](data: Readonly>): this; /** * The member's user, or `null` if the payload did not include it. Resolved from `client.users` when the member * comes from a manager. */ get user(): User | null; get nickname(): string | null; /** * The name to show for this member: their nickname, falling back to their user's display name. */ get displayName(): string | null; /** * The IDs of the member's roles, excluding the implicit `@everyone` role. */ get roleIds(): readonly string[]; /** * The member's roles. Changing them needs the member's user ID, which every payload but some partial ones carries. */ get roles(): GuildMemberRoleManager; get joinedTimestamp(): number | null; get joinedAt(): Date | null; /** * When the member started boosting the guild, `null` if they are not boosting it. */ get premiumSinceTimestamp(): number | null; get premiumSince(): Date | null; get communicationDisabledUntilTimestamp(): number | null; get communicationDisabledUntil(): Date | null; get pending(): boolean; /** * Whether the member is deafened in voice channels, by a moderator. */ get deaf(): boolean; /** * Whether the member is muted in voice channels, by a moderator. */ get mute(): boolean; get flags(): Readonly; /** * The member's guild avatar hash, if any. */ get avatar(): string | null; /** * The member's guild banner hash, if any. */ get banner(): string | null; /** * The member's guild avatar decoration, if any. */ get avatarDecorationData(): AvatarDecorationData | null; /** * The member's guild collectibles, camel-cased like discord.js's `GuildMember#collectibles`. */ get collectibles(): Collectibles | null; /** * Whether the member is timed out right now. */ isCommunicationDisabled(): boolean; /** * Gets the URL of the member's guild avatar, or `null` if they have none. * @param options The image options. */ avatarURL(options?: ImageURLOptions): string | null; /** * Gets the URL of the member's guild avatar, falling back to their user's avatar. * @param options The image options. */ displayAvatarURL(options?: ImageURLOptions): string | null; /** * Gets the URL of the member's guild banner, or `null` if they have none. * @param options The image options. */ bannerURL(options?: ImageURLOptions): string | null; /** * Gets the URL of the member's guild banner, falling back to their user's banner when known. * @param options The image options. */ displayBannerURL(options?: ImageURLOptions): string | null; /** * Gets the URL of the member's guild avatar decoration, or `null` if they have none. */ avatarDecorationURL(): string | null; /** * Gets the URL of the member's guild avatar decoration, falling back to their user's. */ displayAvatarDecorationURL(): string | null; /** * The member's guild-wide permissions, before channel overwrites, like discord.js's `GuildMember#permissions`: * computed from the cached guild and roles, skipping the roles that are not cached. * * @remarks * A role missing from the cache is skipped, not an error, so the answer can hold fewer permissions than the member * has. Use {@link GuildMember.fetchPermissions} for an answer that is right on a cache miss, or * `await member.roles.fetch()` before reading this. * * @throws A `GatewayError`: `GuildUncached` when the guild is not cached. */ get permissions(): CacheRead>; /** * Fetches the member's guild-wide permissions, before channel overwrites: {@link GuildMember.permissions} with the * guild and the roles fetched from the API when they are not cached, whatever the cache. * * @remarks * The call for a permission check that must be right on a cache miss: the getter skips the roles the cache lacks * and can answer fewer permissions than the member has. */ fetchPermissions(): Promise>; /** * Fetches the member's permissions in a channel: their guild permissions with the channel's overwrites applied. * discord.js: `member.permissionsIn(channel)`. * * @remarks * Like {@link GuildMember.fetchPermissions}, the call for a check that must be right on a cache miss: it also * fetches the channel and the roles when they are not cached. * * @param channel The channel, or its ID. Threads use their parent's overwrites. */ fetchPermissionsIn(channel: AnyChannel | string): Promise>; /** * The member's permissions in a channel, like discord.js's `GuildMember#permissionsIn`: their guild permissions * with the channel's overwrites applied, read from the cache. * * @param channel The channel, or the ID of a cached one. Threads use their parent's overwrites. * @remarks * A role missing from the cache is skipped, as in {@link GuildMember.permissions}: use * {@link GuildMember.fetchPermissionsIn} for an answer that is right on a cache miss. * * @throws A `GatewayError`: `ChannelUncached` or `GuildUncached` when they are not cached. */ permissionsIn(channel: AnyChannel | string): CacheRead>; /** * The member's voice state, from the cache, like discord.js's `GuildMember#voice`: `null` when they are not * connected, when the voice state is not cached (it needs the `GuildVoiceStates` intent), or when the cache is * asynchronous. Use {@link GuildMember.fetchVoiceState} to ask the API. */ get voice(): VoiceState | null; /** * The member's presence, from the cache, like discord.js's `GuildMember#presence`: `null` when it is not cached * (it needs the `GuildPresences` intent), or when the cache is asynchronous. */ get presence(): Presence | null; /** * Fetches the member's voice state, cache first. discord.js: `member.voice`. * * @returns The voice state, or `null` when the member is not connected to voice. */ fetchVoiceState(): Promise; /** * Gets the member's presence from the cache. discord.js: `member.presence`. * * Not deprecated, unlike the other `fetch*` twins of getters: it is not a duplicate of {@link GuildMember.presence}, * which is `null` with an asynchronous cache, so this is how to read the presence there. * * @returns The presence, or `null` when it is not cached (the bot needs the `GuildPresences` intent). */ fetchPresence(): Promise; /** * The color the member's name is displayed in, like discord.js's `GuildMember#displayColor`: the one of their * highest cached role that has a color, `0` when none has. */ get displayColor(): CacheRead; /** * The color the member's name is displayed in, as a `#rrggbb` string, like discord.js's * `GuildMember#displayHexColor`. It throws like {@link GuildMember.displayColor}. */ get displayHexColor(): CacheRead<`#${string}`>; /** * Fetches the color the member's name is displayed in, `0` when none of their roles has one. * * @deprecated Use {@link GuildMember.displayColor}. When some roles may be missing from the cache, fetch them first * (`member.roles.fetch()`), then read the getter. */ fetchDisplayColor(): Promise; /** * Fetches the color the member's name is displayed in, as a `#rrggbb` string. * * @deprecated Use {@link GuildMember.displayHexColor}. See {@link GuildMember.fetchDisplayColor} for the cache-miss * fallback. */ fetchDisplayHexColor(): Promise<`#${string}`>; /** * Whether the bot ranks above the member, like discord.js's `GuildMember#manageable`: it is not the guild owner, not * the bot itself, and the bot's highest role is higher than theirs (or the bot owns the guild). * * @remarks * It reads {@link GuildMemberRoleManager.highest}, which skips the roles missing from the cache: a higher role that * is not cached makes the member look lower. Call `await member.roles.fetch()` and `await me.roles.fetch()` before * reading this, or compare {@link GuildMemberRoleManager.fetchHighest} of both. * * @throws A `GatewayError`: `GuildUncached` or `GuildUncachedMe` when the guild or the bot's member is * not cached. */ get manageable(): CacheRead; /** * Fetches whether the bot ranks above the member: {@link GuildMember.manageable} with the guild, the bot's member, * and the roles fetched from the API when they are not cached, whatever the cache. * * @deprecated Use {@link GuildMember.manageable}. When the guild, the bot's member or some roles may be missing from * the cache (a filtered cache, a `plugin-broker` worker), fetch them first (`client.guilds.fetch(guildId)`, * `client.members.fetchMe(guildId)`, `member.roles.fetch()`), then read the getter. */ fetchManageable(): Promise; /** * Whether the bot can kick the member, like discord.js's `GuildMember#kickable`: it outranks them and has * `KickMembers`. It throws, and skips uncached roles, like {@link GuildMember.manageable}. */ get kickable(): CacheRead; /** * Whether the bot can ban the member, like discord.js's `GuildMember#bannable`: it outranks them and has * `BanMembers`. It throws, and skips uncached roles, like {@link GuildMember.manageable}. */ get bannable(): CacheRead; /** * Whether the bot can time the member out, like discord.js's `GuildMember#moderatable`: it outranks them, has * `ModerateMembers`, and they are no administrator. It throws, and skips uncached roles, like * {@link GuildMember.manageable}. */ get moderatable(): CacheRead; /** * Whether the bot can kick the member: it outranks them and has `KickMembers`. * * @deprecated Use {@link GuildMember.kickable}. See {@link GuildMember.fetchManageable} for the cache-miss fallback. */ fetchKickable(): Promise; /** * Whether the bot can ban the member: it outranks them and has `BanMembers`. * * @deprecated Use {@link GuildMember.bannable}. See {@link GuildMember.fetchManageable} for the cache-miss fallback. */ fetchBannable(): Promise; /** * Whether the bot can time the member out: it outranks them, has `ModerateMembers`, and they are no administrator. * * @deprecated Use {@link GuildMember.moderatable}. See {@link GuildMember.fetchManageable} for the cache-miss * fallback. */ fetchModeratable(): Promise; /** * Edits the member. * * @param options The fields to edit. * @returns This member, patched. */ edit(options: GuildMemberEditOptions): Promise; setNickname(nick: string | null, reason?: string): Promise; setFlags(flags: GuildMemberFlagsResolvable, reason?: string): Promise; /** * Times the member out until a given time, or lifts the timeout with `null`. */ disableCommunicationUntil(communicationDisabledUntil: Date | number | null, reason?: string): Promise; /** * Times the member out for a duration in milliseconds, or lifts the timeout with `null`. */ timeout(duration: number | null, reason?: string): Promise; kick(reason?: string): Promise; ban(options?: BanOptions): Promise; /** * Opens a direct message channel with the member, reusing the cached one. * * @param force Whether to skip the cache lookup and always call the API. */ createDM(force?: boolean): Promise; deleteDM(): Promise; send(options: MessagePayloadResolvable): Promise; /** * Whether the member is partial: built from its IDs alone for an event about an uncached member, see * `Partials.GuildMember`. Only its IDs (and the user a removal carries) are reliable then, and * {@link GuildMember.fetch} completes it. */ get partial(): boolean; /** * Whether the member is partial, see {@link GuildMember.partial}, as a type guard: narrows to {@link PartialGuildMember}. * * @remarks * `joinedAt` stays `Date | null` on a member that is not partial: Discord types `joined_at` as nullable on the * gateway's member payloads, so `partial` alone can not tell that it is a date. */ isPartial(): this is PartialGuildMember; /** * Fetches the member from the API and patches this structure with the result. */ fetch(): Promise; /** * Fetches the member's user, cache first. */ fetchUser(): Promise; /** * Whether this member has the same data as another one, like discord.js's `GuildMember#equals`: the same user, * guild, `partial`, nickname, avatar, banner, `pending`, timestamps, flags, roles (in the same order), avatar * decoration, and nameplate. `false` for anything that is not a member. * * @param member The member to compare with. */ equals(member: unknown): boolean; toString(): string; private settledByOwnership; private managedWithCached; private managedWith; private requireId; } /** * The relations of a {@link ThreadMember}, resolved from the cache by `client.threadMembers`. */ export interface ThreadMemberRelations { /** * The member of the thread's guild, when the payload included it or the cache holds it. */ guildMember?: GuildMember | null; thread?: AnyThreadChannel | null; user?: User | null; } /** * A member of a thread: a user who joined it, or was added to it. */ export declare class ThreadMember extends Structure { [kRelations]: ThreadMemberRelations; protected optimizeData(data: Partial): void; /** * @param data The raw thread member. * @param relations The guild member, thread, and user as resolved from the cache, by `client.threadMembers`. */ constructor(data: CacheEntityTypes["threadMembers"], relations?: ThreadMemberRelations); [kPatch](data: Readonly>): this; /** * The ID of the user. Absent only from the thread member the gateway attaches to a thread payload for the bot. */ get id(): string | null; get threadId(): string | null; /** * Whether the thread member is partial: built from its IDs alone for an event about an uncached thread member, see * `Partials.ThreadMember`. Only `id`, `threadId`, and `guildId` are reliable then, and {@link ThreadMember.fetch} * completes it. */ get partial(): boolean; /** * Fetches the thread member from the API and patches this structure with the result. */ fetch(): Promise; get joinedTimestamp(): number; get joinedAt(): Date; /** * The thread member's notification flags. */ get flags(): number; /** * The member of the thread's guild, when known. */ get guildMember(): GuildMember | null; /** * The thread, from the cache, like discord.js's `ThreadMember#thread`. `null` when it is not cached, or when the * cache is asynchronous. */ get thread(): AnyThreadChannel | null; /** * The user, from the cache, like discord.js's `ThreadMember#user`, else the user of the guild member. */ get user(): User | null; /** * Removes the member from the thread. */ remove(): Promise; } /** * The options to list the members of a thread with. */ export interface ThreadMemberListOptions { /** * Whether to include each member's guild member. */ withMember?: boolean; /** * How many members to fetch, up to 100. Paginating requires `withMember`. */ limit?: number; after?: string; } /** * Manages the members of every thread known to the client. */ export declare class ThreadMemberManager extends CachedManager<"threadMembers", ThreadMember, [threadId: string, userId: string]> { constructor(client: GatewayClient); protected createStructure(data: CacheEntityTypes["threadMembers"]): ThreadMember; keyOf(data: CacheEntityTypes["threadMembers"]): string; resolveKey(threadId: string, userId: string): string; /** * Adds a thread member to the cache, and its guild member to `client.members`. * * @internal */ _add(data: CacheEntityTypes["threadMembers"], cache?: boolean, options?: AddOptions): Promise; _hydrate(data: CacheEntityTypes["threadMembers"]): Awaitable; /** * Fetches a member of a thread from the API, bypassing the cache, and caches it. * * @param threadId The ID of the thread. * @param userId The ID of the user. * @param options Whether to include the guild member. */ fetchWithMember(threadId: string, userId: string, options?: { withMember?: boolean; }): Promise; /** * Lists the members of a thread, and caches them. * * @param threadId The ID of the thread. * @param options Whether to include the guild members, and the page. */ list(threadId: string, options?: ThreadMemberListOptions): Promise; /** * Adds a user to a thread. * * @param threadId The ID of the thread. * @param userId The ID of the user, `"@me"` (the default) to join it. */ add(threadId: string, userId?: string): Promise; /** * Removes a user from a thread, and from the cache. * * @param threadId The ID of the thread. * @param userId The ID of the user, `"@me"` (the default) to leave it. */ remove(threadId: string, userId?: string): Promise; protected fetchRaw(threadId: string, userId: string): Promise; private withGuildId; private guildIdOf; } /** * Manages the members of one thread: `client.threadMembers`, with the thread's ID filled in. */ export declare class ThreadChannelMemberManager extends BaseManager { readonly threadId: string; /** * The cached members of the thread, by user ID. * * @example * ```typescript * const member = await thread.members.cache.get(userId); * ``` */ readonly cache: ScopedCache; constructor(client: GatewayClient, threadId: string); /** * Gets a member of the thread from the cache. Same as `cache.get`, always answering a promise. */ get(userId: string): Promise; /** * Gets a member of the thread from the cache, falling back to the API. * * @param userId The ID of the user. * @param options The cache options, and whether to include the guild member (which always calls the API). */ fetch(userId: string, options?: FetchOptions & { withMember?: boolean; }): Promise; /** * Lists the members of the thread. */ list(options?: ThreadMemberListOptions): Promise; /** * Adds a user to the thread, the bot by default. */ add(userId?: string): Promise; /** * Removes a user from the thread, the bot by default. */ remove(userId?: string): Promise; } declare const kArchiveTimestamp: unique symbol; export interface ThreadChannelMixin extends Channel {} /** * Adds the metadata of threads. */ export declare class ThreadChannelMixin { protected [kArchiveTimestamp]: number | null | undefined; static optimizeData(this: Channel, data: Partial): void; get archived(): boolean; get locked(): boolean; get archiveTimestamp(): number | null; /** * The minutes of inactivity after which the thread is archived. */ get autoArchiveDuration(): number | null; get messageCount(): number; get memberCount(): number; /** * Whether non-moderators can add members, for private threads. */ get invitable(): boolean | null; /** * Whether the bot is a member of the thread, like discord.js's `ThreadChannel#joined`: from the thread member cache * when the thread was built by a manager, else `true` when the payload carries the bot's thread member. * * @returns `null` when it cannot be told: no thread member cache, and no thread member in the payload. */ get joined(): boolean | null; /** * The members of the thread. */ get members(): ThreadChannelMemberManager; setArchived(archived?: boolean, reason?: string): Promise; setLocked(locked?: boolean, reason?: string): Promise; /** * Sets whether non-moderators can add members to the private thread. */ setInvitable(invitable?: boolean, reason?: string): Promise; setAutoArchiveDuration(autoArchiveDuration: ThreadAutoArchiveDuration, reason?: string): Promise; /** * Joins the thread. */ join(): Promise; /** * Leaves the thread. */ leave(): Promise; /** * Fetches the message the thread was started from, in its parent channel. Its ID is the thread's. */ fetchStarterMessage(): Promise; /** * Fetches the thread member of the thread's owner. */ fetchOwner(): Promise; } export interface PrivateThreadChannel extends StructureMixin, ChannelRelations>, MixinTypes, TextChannelMixin, TextGuildChannelMixin, GuildChannelMixin, ChannelOwnerMixin, ChannelParentMixin, ChannelSlowmodeMixin, ThreadChannelMixin]> {} /** * A private thread. */ export declare class PrivateThreadChannel extends PrivateThreadChannel$1 { /** * @param data The raw channel. * @param relations The guild as resolved from the cache, by `client.channels` or `client.threads`. */ constructor(data: ChannelDataType, relations?: ChannelRelations); } export interface AppliedTagsMixin extends Channel {} /** * Adds the tags applied to a thread of a forum or media channel. */ export declare class AppliedTagsMixin { get appliedTagIds(): readonly string[]; /** * Sets the tags of the thread. * * @param appliedTags The IDs of the tags. * @param reason The reason for the audit log. */ setAppliedTags(appliedTags: readonly string[], reason?: string): Promise; } export interface PublicThreadChannel extends StructureMixin, ChannelRelations>, MixinTypes, TextChannelMixin, TextGuildChannelMixin, GuildChannelMixin, ChannelOwnerMixin, ChannelParentMixin, ChannelSlowmodeMixin, ThreadChannelMixin, AppliedTagsMixin]> {} /** * A public thread. */ export declare class PublicThreadChannel extends PublicThreadChannel$1 { /** * @param data The raw channel. * @param relations The guild as resolved from the cache, by `client.channels` or `client.threads`. */ constructor(data: ChannelDataType, relations?: ChannelRelations); } /** * Any of the thread structures {@link ThreadManager} builds. */ export type AnyThreadChannel = AnnouncementThreadChannel | PrivateThreadChannel | PublicThreadChannel; /** * The options both kinds of threads are created with. */ export interface ThreadCreateBaseOptions { name: string; autoArchiveDuration?: ThreadAutoArchiveDuration; /** * The slowmode of the thread, in seconds. Both threads and forum or media posts take it. */ rateLimitPerUser?: number; reason?: string; } /** * The options to create a thread of a text or announcement channel with, like discord.js's * `GuildTextThreadCreateOptions`. To start a thread from a message, use `message.startThread()`. */ export interface TextThreadCreateOptions extends ThreadCreateBaseOptions { /** * The type of the thread: public (the default; an announcement thread in announcement channels) or private. */ type?: ChannelType.PublicThread | ChannelType.PrivateThread | ChannelType.AnnouncementThread; /** * Whether non-moderators can add members to a private thread. */ invitable?: boolean; /** * A thread has no first message: use {@link ForumThreadCreateOptions} to create a forum or media post. */ message?: undefined; /** * Only forum and media posts have tags. */ appliedTags?: undefined; } /** * The options to create a post of a forum or media channel with, like discord.js's `GuildForumThreadCreateOptions`. */ export interface ForumThreadCreateOptions extends ThreadCreateBaseOptions { /** * The first message of the post. */ message: MessagePayloadResolvable; /** * The tags of the post. */ appliedTags?: readonly string[]; /** * A post is always a public thread. */ type?: undefined; /** * A post is always a public thread. */ invitable?: undefined; } /** * The options to create a thread with: those of a thread in a text or announcement channel, or with `message`, those * of a post in a forum or media channel. Mixing the two is a compile error, and throws {@link GatewayTypeError} * `ThreadOptionsPostOnly` or `ThreadOptionsThreadOnly` at runtime. */ export type ThreadCreateOptions = TextThreadCreateOptions | ForumThreadCreateOptions; /** * The options to fetch archived threads with. */ export interface FetchArchivedThreadsOptions { /** * Public (the default) or private archived threads. */ type?: "public" | "private"; /** * Whether to fetch the private archived threads the bot joined, which needs no `ManageThreads`. */ joined?: boolean; /** * The archive time (or, with `joined`, the thread ID) to fetch threads before. */ before?: Date | number | string; limit?: number; } /** * Threads fetched in bulk, with the bot's membership of each. */ export interface FetchedThreads { threads: AnyThreadChannel[]; members: ThreadMember[]; /** * Whether more archived threads are left to fetch. */ hasMore: boolean; } /** * Manages the threads known to the client. */ export declare class ThreadManager extends CachedManager<"threads", AnyThreadChannel, [threadId: string]> { constructor(client: GatewayClient); protected createStructure(data: CacheEntityTypes["threads"]): AnyThreadChannel; keyOf(data: CacheEntityTypes["threads"]): string; _hydrate(data: CacheEntityTypes["threads"]): Awaitable; resolveKey(threadId: string): string; /** * Creates a thread in a channel. With `message`, creates a post of a forum or media channel. * * @param channelId The ID of the parent channel. * @param options The thread's name and settings, and the first message of a post. * @throws {@link GatewayTypeError} `ThreadOptionsPostOnly` when `appliedTags` is set without `message`, and * `ThreadOptionsThreadOnly` when `type` or `invitable` is set with it. */ create(channelId: string, options: ThreadCreateOptions): Promise; /** * Fetches the active threads of a guild, with the bot's membership of each, and caches them. * * @param guildId The ID of the guild. */ fetchActive(guildId: string): Promise; /** * Fetches the archived threads of a channel, most recently archived first, and caches them. * * @param channelId The ID of the parent channel. * @param options Public or private threads (only the joined ones with `joined`), and the page. */ fetchArchived(channelId: string, options?: FetchArchivedThreadsOptions): Promise; private defaultThreadType; private storeList; protected fetchRaw(threadId: string): Promise>; } /** * The options to list the messages of a channel with. `before`, `after`, and `around` are exclusive. */ export interface MessageListOptions { /** * How many messages to fetch, up to 100. * * @default 50 */ limit?: number; before?: string; after?: string; around?: string; } /** * The options to start a thread from a message with. */ export interface MessageThreadCreateOptions { name: string; autoArchiveDuration?: ThreadAutoArchiveDuration; rateLimitPerUser?: number; reason?: string; } /** * A pinned message, with the time it was pinned at. */ export interface PinnedMessage { message: Message; pinnedTimestamp: number; } /** * Manages the {@link Message}s known to the client. */ export declare class MessageManager extends CachedManager<"messages", Message, [channelId: string, messageId: string]> { constructor(client: GatewayClient); protected createStructure(data: CacheEntityTypes["messages"]): Message; keyOf(data: CacheEntityTypes["messages"]): string; /** * Adds a message to the cache, its author to `client.users` (unless a webhook sent it), and its member to * `client.members`. * * @internal */ _add(data: CacheEntityTypes["messages"], cache?: boolean, options?: AddOptions): Promise; _hydrate(data: CacheEntityTypes["messages"]): Awaitable; private resolveMentions; private resolveEmojis; resolveKey(channelId: string, messageId: string): string; /** * Lists the messages of a channel, newest first, and caches them. * * @param channelId The ID of the channel. * @param options How many messages, and around which one. */ list(channelId: string, options?: MessageListOptions): Promise; /** * Sends a message to a channel. * * @param channelId The ID of the channel. * @param options The message, or its content. */ send(channelId: string, options: MessagePayloadResolvable): Promise; /** * Forwards a message to another channel. * * @param channelId The ID of the channel of the message. * @param messageId The ID of the message. * @param targetChannelId The ID of the channel to forward it to. */ forward(channelId: string, messageId: string, targetChannelId: string): Promise; /** * Edits a message. * * @param channelId The ID of the channel. * @param messageId The ID of the message. * @param options The changes, or the new content. */ edit(channelId: string, messageId: string, options: MessagePayloadResolvable): Promise; /** * Deletes a message. * * @param channelId The ID of the channel. * @param messageId The ID of the message. * @param reason The reason for the audit log, when deleting someone else's message. */ delete(channelId: string, messageId: string, reason?: string): Promise; /** * Deletes up to 100 messages at once, like discord.js's `TextBasedChannel#bulkDelete`. * * @param channelId The ID of the channel. * @param messages The messages, their IDs, or how many of the latest ones to delete. * @param filterOld Whether to drop the messages older than 14 days instead of letting the request fail. * @returns The deleted messages by ID: the cached one, else a partial one with `Partials.Message`, else `undefined`. * @throws {@link GatewayTypeError} When `messages` is neither a `Collection`, an array, nor a number. */ bulkDelete(channelId: string, messages: Collection | readonly MessageResolvable[] | number, filterOld?: boolean): Promise>; /** * Builds the partial message of an ID alone, when `Partials.Message` is enabled. It is never cached. * * @internal */ _partial(channelId: string, messageId: string, guildId?: string): PartialMessage | null; private guildIdOf; /** * Fetches the pinned messages of a channel, most recently pinned first, and caches them. * * @param channelId The ID of the channel. * @param options How many pins to fetch (up to 50), and before which pin time. */ fetchPins(channelId: string, options?: { limit?: number; before?: Date | number; }): Promise<{ items: PinnedMessage[]; hasMore: boolean; }>; /** * Pins a message. * * @param channelId The ID of the channel. * @param messageId The ID of the message. * @param reason The reason for the audit log. */ pin(channelId: string, messageId: string, reason?: string): Promise; /** * Unpins a message. * * @param channelId The ID of the channel. * @param messageId The ID of the message. * @param reason The reason for the audit log. */ unpin(channelId: string, messageId: string, reason?: string): Promise; /** * Publishes a message of an announcement channel to the channels following it. * * @param channelId The ID of the channel. * @param messageId The ID of the message. */ crosspost(channelId: string, messageId: string): Promise; /** * Reacts to a message as the bot, and counts the reaction on the cached message. * * @param channelId The ID of the channel. * @param messageId The ID of the message. * @param emoji The emoji. */ react(channelId: string, messageId: string, emoji: EmojiIdentifierResolvable): Promise; /** * Removes every reaction with one emoji from a message. * * @param channelId The ID of the channel. * @param messageId The ID of the message. * @param emoji The emoji. */ removeReactionEmoji(channelId: string, messageId: string, emoji: EmojiIdentifierResolvable): Promise; /** * Removes every reaction from a message. * * @param channelId The ID of the channel. * @param messageId The ID of the message. */ removeAllReactions(channelId: string, messageId: string): Promise; /** * Starts a thread from a message. * * @param channelId The ID of the channel. * @param messageId The ID of the message. * @param options The thread's name and settings. */ startThread(channelId: string, messageId: string, options: MessageThreadCreateOptions): Promise; /** * Ends a poll now. Only the bot's own polls can be ended. * * @param channelId The ID of the channel. * @param messageId The ID of the message holding the poll. */ endPoll(channelId: string, messageId: string): Promise; /** * Fetches the users who voted for an answer of a poll, paginated by user ID. * * @param channelId The ID of the channel. * @param messageId The ID of the message holding the poll. * @param answerId The ID of the answer. * @param options How many voters to fetch (up to 100), and after which user ID. */ fetchPollAnswerVoters(channelId: string, messageId: string, answerId: number, options?: { limit?: number; after?: string; }): Promise; protected fetchRaw(channelId: string, messageId: string): Promise; private store; } /** * The options to create an emoji with. */ export interface GuildEmojiCreateOptions { /** * The image, up to 256 KiB: a data URI (`data:image/png;base64,...`), its contents, a path, a URL, a stream, or a * blob. */ attachment: ImageResolvable; name: string; /** * The roles allowed to use the emoji, everyone when omitted: an array of roles or IDs, or a `Collection` of roles. */ roles?: RoleResolvables; reason?: string; } /** * The options to edit an emoji with. */ export interface GuildEmojiEditOptions { name?: string; /** * The roles allowed to use the emoji, `null` or empty for everyone: an array of roles or IDs, or a `Collection` * of roles. */ roles?: RoleResolvables | null; reason?: string; } /** * Manages the custom emojis of one guild. */ export declare class GuildEmojiManager extends CachedManager<"emojis", GuildEmoji, [emojiId: string]> { /** * The ID of the guild. */ readonly guildId: string; constructor(client: GatewayClient, guildId: string); protected createStructure(data: CacheEntityTypes["emojis"]): GuildEmoji; keyOf(data: CacheEntityTypes["emojis"]): string; /** * Adds an emoji to the cache, and its uploader to `client.users`. * * @internal */ _add(data: CacheEntityTypes["emojis"], cache?: boolean, options?: AddOptions): Promise; _hydrate(data: CacheEntityTypes["emojis"]): Awaitable; resolveKey(emojiId: string): string; /** * Resolves an emoji of the guild, or anything identifying one, to the identifier reaction routes expect, like * discord.js's `resolveIdentifier`. * * @param emoji An emoji, its ID, or anything {@link EmojiIdentifierResolvable}. * @returns The identifier, `null` when an ID is not a cached emoji of this guild. */ resolveIdentifier(emoji: EmojiIdentifierResolvable): Awaitable; /** * Fetches every emoji of the guild, and caches them. */ fetchAll(): Promise; /** * Uploads an emoji. * * @param options The image, name, and allowed roles. */ create(options: GuildEmojiCreateOptions): Promise; /** * Edits an emoji. * * @param emojiId The ID of the emoji. * @param options The changes to apply. */ edit(emojiId: string, options: GuildEmojiEditOptions): Promise; /** * Deletes an emoji. * * @param emojiId The ID of the emoji. * @param reason The reason for the audit log. */ delete(emojiId: string, reason?: string): Promise; /** * Fetches the user who uploaded an emoji, which the API only returns with `ManageGuildExpressions`. * * @param emojiId The ID of the emoji. */ fetchAuthor(emojiId: string): Promise; /** * Lists the emojis of the guild held in the cache, without calling the API. * * @remarks * It enumerates the whole entity cache, which a Redis store answers from its index: prefer `fetchAll` when the * cache may be incomplete. * * @returns The cached entries, `[]` when this entity is not cached. * @throws {TypeError} When the store cannot enumerate its entries. */ listCached(): Promise; /** * Finds a custom emoji by its ID across every guild held in the cache, without calling the API. * * @remarks * Emojis are keyed by guild and ID, so it enumerates the whole entity cache like {@link GuildEmojiManager.listCached}. * The manager's own guild plays no part in the lookup. * * @param emojiId The ID of the emoji. * @returns The cached emoji, `null` when no guild has it or this entity is not cached. * @throws {TypeError} When the store cannot enumerate its entries. * @internal */ findCachedInAnyGuild(emojiId: string): Promise; private collectCached; protected fetchRaw(emojiId: string): Promise<{ id: import("discord-api-types/globals").Snowflake | null; name: string | null; animated?: boolean; roles?: import("discord-api-types/v10").APIRole['id'][]; user?: import("discord-api-types/v10").APIUser; require_colons?: boolean; managed?: boolean; available?: boolean; guild_id: string; }>; private store; } /** * Manages the roles allowed to use one custom emoji, like discord.js's `GuildEmojiRoleManager`. When it has none, * everyone can use it. * * @remarks * {@link GuildEmojiRoleManager.cache} is `Awaitable`, unlike discord.js's: synchronous with the default in-memory * cache, a promise with a remote store. */ export declare class GuildEmojiRoleManager extends BaseManager { /** * The emoji these roles belong to. */ readonly emoji: GuildEmoji; /** * @param emoji The emoji. */ constructor(emoji: GuildEmoji); /** * The emoji's guild, from the cache: `null` when it is not cached. */ get guild(): Guild | null; get guildId(): string; get emojiId(): string; /** * The IDs of the allowed roles. */ get ids(): readonly string[]; /** * The allowed roles held in the cache, by ID. Roles that are not cached are skipped: use * {@link GuildEmojiRoleManager.fetch} to get them all. */ get cache(): Awaitable>; /** * Fetches the allowed roles, cache first. */ fetch(): Promise; /** * Allows more roles to use the emoji. * * @param roleOrRoles The role or its ID, or an array or `Collection` of them. * @returns The emoji, patched. */ add(roleOrRoles: RoleResolvable | RoleResolvables): Promise; /** * Stops allowing roles to use the emoji. * * @param roleOrRoles The role or its ID, or an array or `Collection` of them. * @returns The emoji, patched. */ remove(roleOrRoles: RoleResolvable | RoleResolvables): Promise; /** * Replaces the allowed roles, everyone when empty. * * @param roles The roles: an array of roles or IDs, or a `Collection` of roles. * @returns The emoji, patched. */ set(roles: RoleResolvables): Promise; /** * Creates another manager of the same emoji's roles. */ clone(): GuildEmojiRoleManager; private resolve; } /** * The relations of a {@link GuildEmoji}, resolved from the cache by the guild's emoji manager. */ export interface GuildEmojiRelations { author?: User; guild?: Guild | null; } /** * A custom emoji of a guild. */ export declare class GuildEmoji extends Emoji { /** * @param data The raw emoji. * @param relations The uploader and guild as resolved from the cache, by the guild's emoji manager. */ constructor(data: CacheEntityTypes["emojis"], relations?: GuildEmojiRelations); [kPatch](data: Readonly>): this; get id(): string; get guildId(): string; /** * The guild, from the cache. `null` when the guild is not cached, or when the cache is asynchronous: use * `fetchGuild()` to always get it. */ get guild(): Guild | null; /** * Fetches the guild, cache first. */ fetchGuild(): Promise; /** * Whether the emoji is managed by an integration, e.g. Twitch. */ get managed(): boolean; get requiresColons(): boolean; /** * Whether the emoji can be used, `false` when the guild lost the boosts it needs. */ get available(): boolean; /** * The IDs of the roles allowed to use the emoji, everyone when empty. */ get roleIds(): readonly string[]; /** * The roles allowed to use the emoji. */ get roles(): GuildEmojiRoleManager; /** * The user who uploaded the emoji, when the payload includes it (it needs `ManageGuildExpressions`). */ get author(): User | null; /** * Whether the bot can delete the emoji, like discord.js's `GuildEmoji#deletable`: it is not managed, and the bot * has `ManageGuildExpressions`. * * @throws A `GatewayError`: `GuildUncachedMe` or `GuildUncached` on a cache miss. */ get deletable(): CacheRead; /** * Whether the bot can delete the emoji: it is not managed, and the bot has `ManageGuildExpressions`. * * @deprecated Use {@link GuildEmoji.deletable}. When the guild or the bot's member may be missing from the cache (a * filtered cache, a `plugin-broker` worker), fetch them first (`client.members.fetchMe(guildId)`), then read the * getter. */ fetchDeletable(): Promise; /** * Fetches the user who uploaded the emoji. */ fetchAuthor(): Promise; edit(options: GuildEmojiEditOptions): Promise; setName(name: string, reason?: string): Promise; delete(reason?: string): Promise; /** * Whether this emoji has the same data as another one, like discord.js's `GuildEmoji#equals`. Against an emoji, it * compares the ID, name, `managed`, `available`, `requiresColons`, and roles; against a raw emoji, only the ID, * name, and roles. `false` for anything else. * * @param other The emoji, or raw emoji, to compare with. */ equals(other: unknown): boolean; } /** * Manages the users who reacted to a message with one emoji. */ export declare class ReactionUserManager extends BaseManager { readonly channelId: string; readonly messageId: string; /** * The emoji, as the identifier reaction routes expect (`name:id` or the encoded Unicode emoji). */ readonly emoji: string; constructor(client: GatewayClient, channelId: string, messageId: string, emoji: string); /** * Fetches the users who reacted, paginated by user ID, and caches them. * * @param options How many users to fetch (up to 100), after which user ID, and which kind of reaction. */ fetch(options?: { limit?: number; after?: string; type?: ReactionType; }): Promise; /** * Removes a user's reaction, the bot's by default. * * @param userId The ID of the user, `"@me"` for the bot. */ remove(userId?: string): Promise; } /** * The raw data of a reaction, with the message it belongs to. The counts are absent when the reaction was built from * a gateway event on a message the cache did not hold. */ export type MessageReactionData = Omit & Partial> & { channel_id: string; message_id: string; }; /** * The relations of a {@link MessageReaction}: its message, and its cached custom emoji. */ export interface MessageReactionRelations { message?: Message | null; /** * The cached custom emoji, when it belongs to the message's guild. */ emoji?: GuildEmoji | null; } export interface MessageReaction extends StructureMixin {} /** * A reaction on a message, an emoji, how many users reacted with it, and whether the bot did: `@discordjs/structures`' * `Reaction`, with the message it belongs to, its users, and actions through the client. * * @remarks * The counts are omitted from `@discordjs/structures`' data type, since a reaction built from a gateway event on an * uncached message has none. */ export declare class MessageReaction extends Reaction<"count" | "count_details"> { /** * Keeps the raw `burst_colors`, which `@discordjs/structures` strips and re-serializes, so that * {@link MessageReaction.toJSON} returns the reaction as received. */ static DataTemplate: Partial; /** * @param data The raw reaction, with the message it belongs to. * @param relations The related structures, resolved from the cache. */ constructor(data: MessageReactionData, relations?: MessageReactionRelations); get channelId(): string; get messageId(): string; /** * The message the reaction is on, like discord.js's `MessageReaction#message`: the message it was read from, else * the cached one. `null` when the message is not cached. */ get message(): Message | null; /** * The emoji, like discord.js's `MessageReaction#emoji`: the cached custom emoji of the message's guild, else the * emoji of the payload. */ get emoji(): GuildEmoji | ReactionEmoji; /** * The emoji as the payload describes it, which the reaction routes are keyed by. */ private get reactionEmoji(); /** * How many users reacted, super reactions included; `null` when unknown. */ /** * Whether the reaction is partial: its message is not cached, so its counts are unknown. Only its emoji and IDs are * reliable then, and {@link MessageReaction.fetch} completes it. */ get partial(): boolean; get count(): number | null; /** * How many normal and super (burst) reactions there are; `null` when unknown. */ get countDetails(): { normal: number; burst: number; } | null; /** * The colors of the super reaction animation, as numbers. */ get burstColors(): number[]; /** * The users who reacted. */ get users(): ReactionUserManager; /** * Reacts with this emoji as the bot, and counts the bot in this reaction. */ react(): Promise; /** * Removes every reaction with this emoji. */ remove(): Promise; /** * Fetches the message and patches this reaction with its current counts. */ fetch(): Promise; valueOf(): string; /** * Transforms this reaction into its raw data, as received. * * @remarks * Typed as `@discordjs/structures`' `APIReaction`, but the counts are absent when they are unknown, and the data * carries the IDs of the channel and the message. */ toJSON(): APIReaction; } /** * Manages the reactions of one message, as they were in the message's payload. */ export declare class ReactionManager extends BaseManager { #private; readonly channelId: string; readonly messageId: string; /** * @param client The client. * @param channelId The ID of the channel of the message. * @param messageId The ID of the message. * @param reactions The raw reactions of the message. * @param message The message, which its reactions refer to. * @param emojis The cached custom emojis of the reactions, by ID. */ constructor(client: GatewayClient, channelId: string, messageId: string, reactions: readonly APIReaction[], message?: Message | null, emojis?: ReadonlyMap); /** * The reactions of the message, by emoji like discord.js's `ReactionManager#cache`: the ID of a custom emoji, the * name of a Unicode one. */ get cache(): Collection; /** * Finds the reaction with an emoji, if the message has it. * * @param emoji The emoji. */ resolve(emoji: EmojiIdentifierResolvable): MessageReaction | null; /** * Removes every reaction of the message. */ removeAll(): Promise; } /** * The raw data of any component, in a message or in a modal. */ export type APIAnyComponent = APIMessageComponent | APIModalComponent; /** * The members every component of this package shares, mixed into each of them. */ export declare class ComponentMixin { /** * Whether this component has the same data as another one, nested components included. * * @param other The component, or raw component data, to compare with. */ equals(other: Component | APIAnyComponent): boolean; } export interface Component extends StructureMixin, ComponentMixin {} /** * A component of a message or a modal: `@discordjs/structures`' `Component`, like discord.js' `Component`. * * @remarks * Each component type has its own class, like `ActionRow` or `ButtonComponent`s, which `createComponent` picks for a raw * component. This class is only instantiated for the types it has no class for. Their raw data is kept as received, * nested components included, so `toJSON` serializes them back to the API. * * @typeParam Data The raw data of the component. */ export declare class Component extends Component$1 { /** * Whether a value is a component of this package. Most components extend `@discordjs/structures`' own rather than * this class, so `instanceof Component` matches any `@discordjs/structures` component carrying * {@link StructureMixin}. Subclasses keep the default `instanceof` behavior. * * @param value The value to check. */ static [Symbol.hasInstance](value: unknown): boolean; /** * @param data The raw component. * @param relations The related structures, resolved from the cache. */ constructor(data: Data, relations?: object); } export interface ActionRow extends StructureMixin>, ComponentMixin {} /** * An action row, holding buttons, a select menu, or a text input: `@discordjs/structures`' `ActionRowComponent`, with * its components like discord.js' `ActionRow`. * * @typeParam Child The components of the row. */ export declare class ActionRow extends ActionRowComponent { /** * @param data The raw action row. * @param relations The related structures, resolved from the cache. */ constructor(data: APIActionRowComponent, relations?: object); /** * The components in this action row. */ get components(): Child[]; } export interface ChannelSelectMenuComponent extends StructureMixin, ComponentMixin {} /** * A select menu of channels: `@discordjs/structures`' `ChannelSelectMenuComponent`, like discord.js'. */ export declare class ChannelSelectMenuComponent extends ChannelSelectMenuComponent$1<""> { /** * @param data The raw select menu. * @param relations The related structures, resolved from the cache. */ constructor(data: APIChannelSelectComponent, relations?: object); /** * Whether the select menu is disabled. */ get disabled(): boolean; /** * The values selected by default. */ get defaultValues(): readonly APISelectMenuDefaultValue[]; } /** * A modal component for a binary choice. */ export declare class CheckboxComponent extends Component { /** * The custom ID of the checkbox. */ get customId(): string; /** * Whether the checkbox is checked by default. */ get default(): boolean; } /** * A modal component to pick any of its options. */ export declare class CheckboxGroupComponent extends Component { /** * The custom ID of the checkbox group. */ get customId(): string; /** * The options of the checkbox group. */ get options(): readonly APICheckboxGroupOption[]; /** * The minimum number of options to pick, `1` by default. */ get minValues(): number; /** * The maximum number of options to pick, the number of options by default. */ get maxValues(): number; /** * Whether picking options is required to submit the modal, `true` by default. */ get required(): boolean; } export interface ContainerComponent extends StructureMixin, ComponentMixin {} /** * A container visually grouping components, like an embed: `@discordjs/structures`' `ContainerComponent`, with its * components like discord.js'. */ export declare class ContainerComponent extends ContainerComponent$1<""> { /** * @param data The raw container. * @param relations The related structures, resolved from the cache. */ constructor(data: APIContainerComponent, relations?: object); /** * The components in this container. */ get components(): ComponentInContainer[]; /** * The accent color of the container, `null` when it has none. */ get accentColor(): number | null; /** * The accent color as a `#rrggbb` string, `null` when the container has none. */ get hexAccentColor(): `#${string}` | null; /** * Whether the container is marked as a spoiler. */ get spoiler(): boolean; } export interface UnfurledMediaItem extends StructureMixin {} /** * A media item of a thumbnail, file, or media gallery component: `@discordjs/structures`' `UnfurledMediaItem`, like * discord.js'. */ export declare class UnfurledMediaItem extends UnfurledMediaItem$1<""> { /** * @param data The raw media item. * @param relations The related structures, resolved from the cache. */ constructor(data: APIUnfurledMediaItem, relations?: object); } export interface FileComponent extends StructureMixin, ComponentMixin {} /** * An attached file: `@discordjs/structures`' `FileComponent`, with its media like discord.js'. */ export declare class FileComponent extends FileComponent$1<""> { /** * @param data The raw file component. * @param relations The related structures, resolved from the cache. */ constructor(data: APIFileComponent, relations?: object); /** * The file, an `attachment://` reference to an attachment of the message. */ get file(): UnfurledMediaItem; /** * Whether the file is marked as a spoiler. */ get spoiler(): boolean; } export interface FileUploadComponent extends StructureMixin, ComponentMixin {} /** * A file upload field of a modal: `@discordjs/structures`' `FileUploadComponent`, like discord.js'. */ export declare class FileUploadComponent extends FileUploadComponent$1<""> { /** * @param data The raw file upload. * @param relations The related structures, resolved from the cache. */ constructor(data: APIFileUploadComponent, relations?: object); /** * The types of files that can be uploaded, any when empty. */ get fileTypes(): readonly FileUploadType[]; } export interface InteractiveButtonComponent extends StructureMixin, ComponentMixin {} /** * A button sending an interaction when clicked, of the `Primary`, `Secondary`, `Success`, or `Danger` style: * `@discordjs/structures`' `InteractiveButtonComponent`, with discord.js' `ButtonComponent` helpers. */ export declare class InteractiveButtonComponent extends InteractiveButtonComponent$1 { /** * @param data The raw button. * @param relations The related structures, resolved from the cache. */ constructor(data: APIButtonComponentWithCustomId, relations?: object); /** * Whether the button is disabled. */ get disabled(): boolean; /** * The emoji on the button. */ get emoji(): APIMessageComponentEmoji | null; } /** * A modal component associating a label and a description with another component, like discord.js' `LabelComponent`. */ export declare class LabelComponent extends Component { /** * The label. */ get label(): string; /** * The description of the label. */ get description(): string | null; /** * The component the label is for. */ get component(): ComponentInLabel; } export interface LinkButtonComponent extends StructureMixin, ComponentMixin {} /** * A button of the `Link` style, opening a URL: `@discordjs/structures`' `LinkButtonComponent`, with discord.js' * `ButtonComponent` helpers. */ export declare class LinkButtonComponent extends LinkButtonComponent$1<""> { /** * @param data The raw button. * @param relations The related structures, resolved from the cache. */ constructor(data: APIButtonComponentWithURL, relations?: object); /** * Whether the button is disabled. */ get disabled(): boolean; /** * The emoji on the button. */ get emoji(): APIMessageComponentEmoji | null; } export interface MediaGalleryItem extends StructureMixin {} /** * An item of a media gallery component: `@discordjs/structures`' `MediaGalleryItem`, with its media like discord.js'. */ export declare class MediaGalleryItem extends MediaGalleryItem$1<""> { /** * @param data The raw media gallery item. * @param relations The related structures, resolved from the cache. */ constructor(data: APIMediaGalleryItem, relations?: object); /** * The media of the item. */ get media(): UnfurledMediaItem; /** * The description of the item. */ get description(): string | undefined; /** * Whether the item is marked as a spoiler. */ get spoiler(): boolean; } export interface MediaGalleryComponent extends StructureMixin, ComponentMixin {} /** * A gallery of images and videos: `@discordjs/structures`' `MediaGalleryComponent`, with its items like discord.js'. */ export declare class MediaGalleryComponent extends MediaGalleryComponent$1<""> { /** * @param data The raw media gallery. * @param relations The related structures, resolved from the cache. */ constructor(data: APIMediaGalleryComponent, relations?: object); /** * The items of the gallery. */ get items(): MediaGalleryItem[]; } export interface MentionableSelectMenuComponent extends StructureMixin, ComponentMixin {} /** * A select menu of users and roles: `@discordjs/structures`' `MentionableSelectMenuComponent`, like discord.js'. */ export declare class MentionableSelectMenuComponent extends MentionableSelectMenuComponent$1<""> { /** * @param data The raw select menu. * @param relations The related structures, resolved from the cache. */ constructor(data: APIMentionableSelectComponent, relations?: object); /** * Whether the select menu is disabled. */ get disabled(): boolean; /** * The values selected by default. */ get defaultValues(): readonly APISelectMenuDefaultValue[]; } export interface PremiumButtonComponent extends StructureMixin, ComponentMixin {} /** * A button of the `Premium` style, purchasing a SKU: `@discordjs/structures`' `PremiumButtonComponent`. */ export declare class PremiumButtonComponent extends PremiumButtonComponent$1<""> { /** * @param data The raw button. * @param relations The related structures, resolved from the cache. */ constructor(data: APIButtonComponentWithSKUId, relations?: object); /** * Whether the button is disabled. */ get disabled(): boolean; } /** * A modal component to pick one of its options. */ export declare class RadioGroupComponent extends Component { /** * The custom ID of the radio group. */ get customId(): string; /** * The options of the radio group. */ get options(): readonly APIRadioGroupOption[]; /** * Whether picking an option is required to submit the modal, `true` by default. */ get required(): boolean; } export interface RoleSelectMenuComponent extends StructureMixin, ComponentMixin {} /** * A select menu of roles: `@discordjs/structures`' `RoleSelectMenuComponent`, like discord.js'. */ export declare class RoleSelectMenuComponent extends RoleSelectMenuComponent$1<""> { /** * @param data The raw select menu. * @param relations The related structures, resolved from the cache. */ constructor(data: APIRoleSelectComponent, relations?: object); /** * Whether the select menu is disabled. */ get disabled(): boolean; /** * The values selected by default. */ get defaultValues(): readonly APISelectMenuDefaultValue[]; } export interface ThumbnailComponent extends StructureMixin, ComponentMixin {} /** * A small image, used as the accessory of a section: `@discordjs/structures`' `ThumbnailComponent`, with its media like * discord.js'. */ export declare class ThumbnailComponent extends ThumbnailComponent$1<""> { /** * @param data The raw thumbnail. * @param relations The related structures, resolved from the cache. */ constructor(data: APIThumbnailComponent, relations?: object); /** * The media of the thumbnail. */ get media(): UnfurledMediaItem; /** * The description of the thumbnail. */ get description(): string | undefined; /** * Whether the thumbnail is marked as a spoiler. */ get spoiler(): boolean; } export interface SectionComponent extends StructureMixin, ComponentMixin {} /** * Text displayed alongside an accessory: `@discordjs/structures`' `SectionComponent`, with its components and accessory * like discord.js'. */ export declare class SectionComponent extends SectionComponent$1<""> { /** * @param data The raw section. * @param relations The related structures, resolved from the cache. */ constructor(data: APISectionComponent, relations?: object); /** * The text components in this section. */ get components(): ComponentInSection[]; /** * The button or thumbnail shown next to the section. */ get accessory(): ButtonComponent | ThumbnailComponent; } export interface SeparatorComponent extends StructureMixin, ComponentMixin {} /** * Vertical padding between components: `@discordjs/structures`' `SeparatorComponent`, with Discord's defaults like * discord.js'. */ export declare class SeparatorComponent extends SeparatorComponent$1<""> { /** * @param data The raw separator. * @param relations The related structures, resolved from the cache. */ constructor(data: APISeparatorComponent, relations?: object); /** * The size of the padding, `Small` by default. */ get spacing(): SeparatorSpacingSize; /** * Whether a divider line is shown, `true` by default. */ get divider(): boolean; } export interface StringSelectMenuComponent extends StructureMixin, ComponentMixin {} /** * A select menu of predefined text options: `@discordjs/structures`' `StringSelectMenuComponent`, like discord.js'. */ export declare class StringSelectMenuComponent extends StringSelectMenuComponent$1<""> { /** * @param data The raw select menu. * @param relations The related structures, resolved from the cache. */ constructor(data: APIStringSelectComponent, relations?: object); /** * Whether the select menu is disabled. */ get disabled(): boolean; /** * The options of the select menu. */ get options(): readonly APISelectMenuOption[]; } export interface TextDisplayComponent extends StructureMixin, ComponentMixin {} /** * Markdown text: `@discordjs/structures`' `TextDisplayComponent`, like discord.js'. */ export declare class TextDisplayComponent extends TextDisplayComponent$1<""> { /** * @param data The raw text display. * @param relations The related structures, resolved from the cache. */ constructor(data: APITextDisplayComponent, relations?: object); } export interface TextInputComponent extends StructureMixin, ComponentMixin {} /** * A text field of a modal: `@discordjs/structures`' `TextInputComponent`, like discord.js'. */ export declare class TextInputComponent extends TextInputComponent$1<""> { /** * @param data The raw text input. * @param relations The related structures, resolved from the cache. */ constructor(data: APITextInputComponent, relations?: object); } export interface UserSelectMenuComponent extends StructureMixin, ComponentMixin {} /** * A select menu of users: `@discordjs/structures`' `UserSelectMenuComponent`, like discord.js'. */ export declare class UserSelectMenuComponent extends UserSelectMenuComponent$1<""> { /** * @param data The raw select menu. * @param relations The related structures, resolved from the cache. */ constructor(data: APIUserSelectComponent, relations?: object); /** * Whether the select menu is disabled. */ get disabled(): boolean; /** * The values selected by default. */ get defaultValues(): readonly APISelectMenuDefaultValue[]; } /** * A button, of any style. */ export type ButtonComponent = InteractiveButtonComponent | LinkButtonComponent | PremiumButtonComponent; /** * A select menu, of any type. */ export type SelectMenuComponent = ChannelSelectMenuComponent | MentionableSelectMenuComponent | RoleSelectMenuComponent | StringSelectMenuComponent | UserSelectMenuComponent; /** * A component of a message's action row. */ export type MessageActionRowComponent = ButtonComponent | SelectMenuComponent; /** * A component of a modal's action row. */ export type ModalActionRowComponent = TextInputComponent; /** * A component of a section. */ export type ComponentInSection = TextDisplayComponent; /** * A component of a container. */ export type ComponentInContainer = ActionRow | FileComponent | MediaGalleryComponent | SectionComponent | SeparatorComponent | TextDisplayComponent; /** * A top-level component of a message. */ export type MessageTopLevelComponent = ComponentInContainer | ContainerComponent; /** * A component of a label. */ export type ComponentInLabel = CheckboxComponent | CheckboxGroupComponent | FileUploadComponent | RadioGroupComponent | SelectMenuComponent | TextInputComponent; /** * The component {@link createComponent} builds for some raw component data, {@link Component} for the types this * package has no class for. * * @typeParam Data The raw component data. */ export type ComponentOf = Data extends APIActionRowComponent ? ActionRow, MessageActionRowComponent | ModalActionRowComponent>> : Data extends APIButtonComponentWithCustomId ? InteractiveButtonComponent : Data extends APIButtonComponentWithURL ? LinkButtonComponent : Data extends APIButtonComponentWithSKUId ? PremiumButtonComponent : Data extends APIStringSelectComponent ? StringSelectMenuComponent : Data extends APIUserSelectComponent ? UserSelectMenuComponent : Data extends APIRoleSelectComponent ? RoleSelectMenuComponent : Data extends APIMentionableSelectComponent ? MentionableSelectMenuComponent : Data extends APIChannelSelectComponent ? ChannelSelectMenuComponent : Data extends APITextInputComponent ? TextInputComponent : Data extends APISectionComponent ? SectionComponent : Data extends APITextDisplayComponent ? TextDisplayComponent : Data extends APIThumbnailComponent ? ThumbnailComponent : Data extends APIMediaGalleryComponent ? MediaGalleryComponent : Data extends APIFileComponent ? FileComponent : Data extends APISeparatorComponent ? SeparatorComponent : Data extends APIContainerComponent ? ContainerComponent : Data extends APILabelComponent ? LabelComponent : Data extends APIFileUploadComponent ? FileUploadComponent : Data extends APIRadioGroupComponent ? RadioGroupComponent : Data extends APICheckboxGroupComponent ? CheckboxGroupComponent : Data extends APICheckboxComponent ? CheckboxComponent : Component; /** * Any component of this package. */ export type AnyComponent = ComponentOf; /** * Builds the component class matching some raw component data, like discord.js' `createComponent`: an `ActionRow` for * an action row, a `LinkButtonComponent` for a link button, and so on. Nested components are built too, when accessed. * * @param data The raw component data, or a component, which is returned as is. * @returns The component. */ export declare function createComponent(data: Data | ComponentOf): ComponentOf; /** * Finds a component by its custom ID in a component tree, like discord.js' `findComponentByCustomId`. * * @param components The components, or raw component data, to search in, like a message's top-level components. * @param customId The custom ID. * @returns The component, as given, `null` when none has the custom ID. */ export declare function findComponentByCustomId(components: readonly (AnyComponent | APIAnyComponent)[], customId: string): AnyComponent | APIAnyComponent | null; /** * The options to create a webhook with. */ export interface WebhookCreateOptions { name: string; /** * The avatar: a data URI, or anything `resolveImage` reads. */ avatar?: ImageResolvable | null; reason?: string; } /** * The options to edit a webhook with. */ export interface WebhookEditOptions { name?: string; /** * The avatar: a data URI, or anything `resolveImage` reads. `null` removes it. */ avatar?: ImageResolvable | null; /** * The channel to move the webhook to. Needs the bot's authorization, not the webhook's token. */ channel?: IdResolvable; reason?: string; } /** * Manages webhooks. Discord does not send them over the gateway, so they are never cached. * * @remarks * Methods taking a webhook's token call the API with it rather than with the bot's authorization, so they work for * webhooks of other applications too. */ export declare class WebhookManager extends BaseManager { constructor(client: GatewayClient); /** * Fetches a webhook. * * @param webhookId The ID of the webhook. * @param token The webhook's token, to fetch it without the bot's authorization. */ fetch(webhookId: string, token?: string): Promise; /** * Fetches the webhooks of a channel. * * @param channelId The ID of the channel. */ fetchChannel(channelId: string): Promise; /** * Fetches the webhooks of a guild. * * @param guildId The ID of the guild. */ fetchGuild(guildId: string): Promise; /** * Creates a webhook in a channel. * * @param channelId The ID of the channel. * @param options The webhook's name and avatar, and the reason for the audit log. */ create(channelId: string, options: WebhookCreateOptions): Promise; /** * Edits a webhook. * * @param webhookId The ID of the webhook. * @param options The fields to edit, and the reason for the audit log. * @param token The webhook's token, to edit it without the bot's authorization (which cannot move it). */ edit(webhookId: string, options: WebhookEditOptions, token?: string): Promise; /** * Deletes a webhook. * * @param webhookId The ID of the webhook. * @param options The webhook's token, to delete it without the bot's authorization, and the reason for the audit log. */ delete(webhookId: string, options?: { token?: string; reason?: string; }): Promise; /** * Sends a message through a webhook, and caches it. * * @param webhookId The ID of the webhook. * @param token The webhook's token. * @param options The message, or its content, and the thread to send it in. */ send(webhookId: string, token: string, options: MessagePayloadResolvable): Promise; /** * Fetches a message sent by a webhook. * * @param webhookId The ID of the webhook. * @param token The webhook's token. * @param messageId The ID of the message. * @param options The thread the message is in. */ fetchMessage(webhookId: string, token: string, messageId: string, options?: WebhookThreadOptions): Promise; /** * Edits a message sent by a webhook. * * @param webhookId The ID of the webhook. * @param token The webhook's token. * @param messageId The ID of the message. * @param options The changes, or the new content, and the thread the message is in. */ editMessage(webhookId: string, token: string, messageId: string, options: MessagePayloadResolvable): Promise; /** * Deletes a message sent by a webhook. * * @param webhookId The ID of the webhook. * @param token The webhook's token. * @param messageId The ID of the message. * @param options The thread the message is in. */ deleteMessage(webhookId: string, token: string, messageId: string, options?: WebhookThreadOptions): Promise; /** * Builds the structure of a raw webhook, resolving its guild, channel, source guild, source channel, and owner from * the cache. * * @param data The raw webhook. */ hydrate(data: APIWebhook): Promise; } /** * What {@link WebhookMixin} needs from the class it is mixed into. */ export interface WebhookMixin { readonly id: string; readonly token: string | null | undefined; readonly client: GatewayClient; } /** * The members shared by everything posting through a webhook's token, like discord.js's `Webhook.applyToClass`. * * @remarks * Every method calls the API with the webhook's token rather than with the bot's authorization, so they work for * webhooks of other applications too. */ export declare class WebhookMixin { /** * The URL to post to, built from the webhook's ID and token. */ get url(): string | undefined; get createdTimestamp(): number; get createdAt(): Date; /** * Sends a message through the webhook. * * @param options The message, its content, or a {@link MessagePayload}, and the thread to send it in. */ send(options: MessagePayloadResolvable): Promise; /** * Sends a Slack-compatible message through the webhook. * * @param body The Slack message. * @param options The thread to send it in. */ sendSlackMessage(body: unknown, options?: WebhookThreadOptions): Promise; /** * Fetches a message sent by the webhook. * * @param messageId The ID of the message. * @param options The thread the message is in. */ fetchMessage(messageId: string, options?: WebhookThreadOptions): Promise; /** * Edits a message sent by the webhook. * * @param messageId The ID of the message. * @param options The changes, the new content, or a {@link MessagePayload}, and the thread the message is in. */ editMessage(messageId: string, options: MessagePayloadResolvable): Promise; /** * Deletes a message sent by the webhook. * * @param messageId The ID of the message. * @param options The thread the message is in. */ deleteMessage(messageId: string, options?: WebhookThreadOptions): Promise; /** * Gets the webhook's token, throwing when it has none. * * @internal */ requireToken(): string; } /** * The relations of a {@link Webhook}, resolved from the cache by `client.webhooks`. */ export interface WebhookRelations { guild?: Guild | null; channel?: AnyChannel | null; sourceGuild?: Guild | null; sourceChannel?: AnyChannel | null; owner?: User; } export interface Webhook extends StructureMixin, MixinTypes {} /** * A webhook, an incoming one posting to a channel, a channel follower, or an application's: `@discordjs/structures`' * `Webhook`, with its owner, source, and URLs, and actions through the client. * * @remarks * `token` is only set for incoming webhooks, and only their creator (or the guild's managers) see it. */ export declare class Webhook extends Webhook$1 { /** * @param data The raw webhook. * @param relations The related structures, resolved from the cache. */ constructor(data: APIWebhook, relations?: object); [kRelations]: WebhookRelations; get guildId(): string | null; /** * The guild of the webhook, from the cache, like discord.js's `Webhook#guild`: `null` when it is not cached. */ get guild(): Guild | null; /** * The channel the webhook posts to, from the cache: `null` when it is not cached. */ get channel(): AnyChannel | null; /** * The user who created the webhook, from the cache, else from the payload. */ get owner(): User | null; /** * The guild a channel follower webhook posts from: the cached guild, else the partial one of the payload. */ get sourceGuild(): Guild | NonNullable | null; /** * The channel a channel follower webhook posts from: the cached channel, else the partial one of the payload. */ get sourceChannel(): AnyChannel | NonNullable | null; /** * The URL to post to, for webhooks with a token: the one Discord sent, or one built from the token. */ get url(): string | undefined; get createdTimestamp(): number; get createdAt(): Date; avatarURL(options?: Readonly): string | null; isIncoming(): boolean; isChannelFollower(): boolean; isApplicationCreated(): boolean; /** * Edits the webhook, with its token when it has one (then it cannot be moved to another channel). * * @param options The fields to edit, and the reason for the audit log. */ edit(options: WebhookEditOptions): Promise; /** * Deletes the webhook. * * @param reason The reason for the audit log. */ delete(reason?: string): Promise; } export interface Attachment extends StructureMixin {} /** * A file attached to a message: `@discordjs/structures`' `Attachment`, with discord.js' aliases and helpers. */ export declare class Attachment extends Attachment$1 { /** * @param data The raw attachment. * @param relations The related structures, resolved from the cache. */ constructor(data: APIAttachment, relations?: object); /** * The URL of the file, like discord.js's `Attachment#attachment`, so that an attachment can be resent with * `AttachmentBuilder.from`. */ get attachment(): string; /** * The name of the file. */ get name(): string; /** * Whether the attachment is ephemeral: it is deleted shortly after the message is, unless referenced elsewhere. */ get ephemeral(): boolean; /** * The duration of a voice message, in seconds. */ get duration(): number | null; get flags(): Readonly; /** * Whether the attachment is marked as a spoiler. */ get spoiler(): boolean; get createdTimestamp(): number; get createdAt(): Date; } export interface Embed extends StructureMixin {} /** * An embed of a received message: `@discordjs/structures`' `Embed`, with its nested parts and discord.js' helpers. * Use `@discordjs/builders`' `EmbedBuilder` to create embeds. */ export declare class Embed extends Embed$1<""> { /** * Keeps the raw `timestamp`, which `@discordjs/structures` strips and re-serializes in its own format, so that * {@link Embed.toJSON} returns the embed as received. */ static readonly DataTemplate: Partial; /** * @param data The raw embed. * @param relations The related structures, resolved from the cache. */ constructor(data: APIEmbed, relations?: object); /** * The color as a `#rrggbb` string, `undefined` when the embed has none. */ get hexColor(): `#${string}` | undefined; get fields(): readonly APIEmbedField[]; /** * The thumbnail, camel-cased like discord.js's `Embed#thumbnail`. */ get thumbnail(): EmbedAssetData | null; /** * The image, camel-cased like discord.js's `Embed#image`. */ get image(): EmbedAssetData | null; /** * The video, camel-cased like discord.js's `Embed#video`. */ get video(): EmbedAssetData | null; /** * The author, camel-cased like discord.js's `Embed#author`. */ get author(): EmbedAuthorData | null; get provider(): APIEmbedProvider | null; /** * The footer, camel-cased like discord.js's `Embed#footer`. */ get footer(): EmbedFooterData | null; /** * The number of characters counting towards Discord's 6000 characters limit. */ get length(): number; /** * Whether this embed has the same data as another one, like discord.js's `Embed#equals`. Against an embed, the raw * data is compared in depth; against a raw embed, the author, color, description, footer, image, thumbnail, * timestamp, title, URL, video, fields (a missing `inline` is `false`), and provider. * * @param other The embed, or raw embed data, to compare with. */ equals(other: Embed | APIEmbed | null | undefined): boolean; toJSON(): APIEmbed; } /** * The mentioned entities, resolved from the cache by `client.messages`, each by ID. */ export interface MessageMentionsRelations { /** * The mentioned users and the ones parsed from the content, and the author of the replied message. The users the * payload mentions are there even when they are not cached. */ users?: ReadonlyMap; members?: ReadonlyMap; roles?: ReadonlyMap; /** * The channels mentioned in the content. */ channels?: ReadonlyMap; guild?: Guild | null; } /** * The raw fields of a message the mentions are read from. */ export type MessageMentionsData = Pick & Partial> & { guild_id?: string; /** * The mentioned users. In guilds, the gateway attaches each one's partial member. */ mentions: (APIUser & { member?: Omit; })[]; }; /** * The options of {@link MessageMentions.has}. */ export interface MentionsHasOptions { /** * Whether to ignore direct mentions of the user, role, or channel. */ ignoreDirect?: boolean; /** * Whether to ignore mentions of the member's roles. */ ignoreRoles?: boolean; /** * Whether to ignore the author of the replied message. */ ignoreRepliedUser?: boolean; /** * Whether to ignore `@everyone` and `@here`. */ ignoreEveryone?: boolean; } /** * The users, roles, and channels a message mentions. * * @remarks * Users and members come with the message payload, and are replaced by their cached copies when the message was built * by `client.messages`, which also resolves the mentioned roles and channels from the cache, like discord.js. */ export declare class MessageMentions { #private; /** * Matches `@everyone` and `@here`. */ static readonly EveryonePattern: RegExp; /** * Matches user mentions, `<@id>` and the legacy `<@!id>`. */ static readonly UsersPattern: RegExp; /** * Matches role mentions, `<@&id>`. */ static readonly RolesPattern: RegExp; /** * Matches channel mentions, `<#id>`. */ static readonly ChannelsPattern: RegExp; /** * @param data The raw fields of the message. * @param relations The mentioned entities, as resolved from the cache. */ constructor(data: MessageMentionsData, relations?: MessageMentionsRelations); /** * The guild of the message, from the cache, like discord.js's `MessageMentions#guild`. */ get guild(): If; /** * The cached roles the message mentions, by ID, like discord.js's `MessageMentions#roles`. */ get roles(): Map; /** * The cached channels the content mentions, by ID, like discord.js's `MessageMentions#channels`. */ get channels(): Map; /** * The users the content mentions, by ID, like discord.js's `MessageMentions#parsedUsers`, which also counts the * users the message does not ping. * * @remarks * Like discord.js, it reads the cache: a user the content mentions without the payload listing it is skipped when * it is not cached. The users the payload does list are included even when uncached, as discord.js adds them to its * cache first; here nothing is written to it. */ get parsedUsers(): Map; /** * Whether the message mentions `@everyone` or `@here`. */ get everyone(): boolean; /** * The mentioned users: their cached copies, else the payload's. */ get users(): User[]; /** * The mentioned users as members, for messages sent in a guild. */ get members(): GuildMember[]; get roleIds(): readonly string[]; /** * The IDs of the channels mentioned in the content, and of the crossposted channels. */ get channelIds(): string[]; /** * The IDs of the channels mentioned in the content. */ get parsedChannelIds(): string[]; /** * The channels a crossposted message mentions, from other guilds, camel-cased like discord.js's * `MessageMentions#crosspostedChannels`. */ get crosspostedChannels(): CrosspostedChannel[]; /** * The author of the message this one replies to, if any. */ get repliedUser(): User | null; /** * The IDs of the users mentioned in the content, including the ones Discord did not resolve. */ get parsedUserIds(): string[]; /** * Lists the unique IDs a mention pattern matches in a content. * * @param content The content. * @param pattern One of the global mention patterns, e.g. {@link MessageMentions.ChannelsPattern}. */ static parseIds(content: string, pattern: RegExp): string[]; /** * Whether the message mentions a user, member, role, or channel. * * @param target The ID, or a structure with an `id` (and `roleIds` for members). * @param options What kinds of mentions to ignore. */ has(target: string | { id: string | null; roleIds?: readonly string[]; }, options?: MentionsHasOptions): boolean; } /** * Manages the voters of one {@link PollAnswer}, like discord.js's `PollAnswerVoterManager`. * * @remarks * Unlike discord.js's, it has no `cache`: the voters of an answer are not tracked, so {@link PollAnswerVoterManager.fetch} * reads them from the API each time (and caches the users). */ export declare class PollAnswerVoterManager extends BaseManager { /** * The answer these voters voted for. */ readonly answer: PollAnswer; /** * @param answer The answer. */ constructor(answer: PollAnswer); /** * Fetches the users that voted for the answer. * * @param options How many voters to fetch (up to 100), and after which user ID. */ fetch(options?: { limit?: number; after?: string; }): Promise; } /** * The raw data of a poll answer, with its vote count from the poll's results and the message it belongs to. */ export type PollAnswerData = APIPollAnswer & { channel_id: string; message_id: string; /** * The vote count from the poll's results, absent when Discord did not send them. */ count?: number; me_voted?: boolean; }; /** * The relations of a {@link PollAnswer}: its poll, and its cached custom emoji. */ export interface PollAnswerRelations { poll?: Poll | null; emoji?: GuildEmoji | null; } export interface PollAnswer extends StructureMixin {} /** * An answer of a {@link Poll}: `@discordjs/structures`' `PollAnswer`, with its vote count and the message it belongs to. */ export declare class PollAnswer extends PollAnswer$1 { /** * @param data The raw answer, with its vote count and the message it belongs to. * @param relations The related structures, resolved from the cache. */ constructor(data: PollAnswerData, relations?: PollAnswerRelations); /** * The ID of the answer, an alias of `answerId`. */ get id(): number; get channelId(): string; get messageId(): string; get text(): string | null; /** * Whether the answer is partial: its message is not cached, so only its ID is known, see `Partials.PollAnswer`. * Fetch its poll to complete it. */ get partial(): boolean; /** * The poll the answer belongs to, like discord.js's `PollAnswer#poll`: `null` when the answer was not read from a * poll. */ get poll(): Poll | null; /** * The emoji of the answer, like discord.js's `PollAnswer#emoji`: the cached custom emoji of the message's guild, * else the payload's. */ get emoji(): GuildEmoji | ReactionEmoji | null; /** * How many users voted for the answer, `0` when the results are unknown. */ get voteCount(): number; /** * Whether the bot voted for the answer. */ get meVoted(): boolean; /** * Fetches the users who voted for the answer, paginated by user ID. * * @param options How many voters to fetch (up to 100), and after which user ID. */ fetchVoters(options?: { limit?: number; after?: string; }): Promise; /** * The voters of the answer, like discord.js's `PollAnswer#voters`. */ get voters(): PollAnswerVoterManager; } /** * The raw data of a poll, with the message it belongs to. */ export type PollData = APIPoll & { channel_id: string; message_id: string; }; /** * The relations of a {@link Poll}: the message it belongs to, and that message's channel and cached custom emojis. */ export interface PollRelations { message?: Message | null; channel?: AnyChannel | null; /** * The cached custom emojis of the answers, by ID, when they belong to the message's guild. */ emojis?: ReadonlyMap; } export interface Poll extends StructureMixin {} /** * The poll of a message: `@discordjs/structures`' `Poll`, with its answers, results, and the message it belongs to. */ export declare class Poll extends Poll$1<""> { /** * Keeps the raw `expiry`, which `@discordjs/structures` strips and re-serializes in its own format, so that * {@link Poll.toJSON} returns the poll as received. */ static DataTemplate: Partial; /** * @param data The raw poll, with the message it belongs to. * @param relations The related structures, resolved from the cache. */ constructor(data: PollData, relations?: PollRelations); get channelId(): string; get messageId(): string; /** * The message the poll belongs to, like discord.js's `Poll#message`: `null` when the message is not cached, * or when the cache is asynchronous. */ get message(): Message | null; /** * The channel of the poll's message, from the cache, like discord.js's `Poll#channel`. */ get channel(): AnyChannel | null; /** * Whether the poll is partial: built from its message's IDs alone for a vote on an uncached message, see * `Partials.Poll`. Only `channelId` and `messageId` are reliable then, and {@link Poll.fetch} completes it. */ get partial(): boolean; /** * Fetches the poll's message from the API and patches this structure with its poll. */ fetch(): Promise; get question(): { text: string | null; emoji: ReactionEmoji | null; }; /** * The answers, with their vote counts when Discord sent the results. */ get answers(): PollAnswer[]; /** * Whether the votes are final, i.e. the poll ended and Discord counted them. */ get resultsFinalized(): boolean; /** * When the poll ends, `null` for polls that never do. */ get expiresAt(): Date | null; /** * Ends the poll now. Only the bot's own polls can be ended. * * @returns The message holding the ended poll. */ end(): Promise; toJSON(): PollData; } /** * The options to upload a sticker with. */ export interface GuildStickerCreateOptions { /** * The PNG, APNG, GIF, or Lottie JSON file, up to 512 KiB. */ file: RawFile; name: string; /** * The name of the Unicode emoji the sticker relates to, used for suggestions. */ tags: string; description?: string; reason?: string; } /** * The options to edit a sticker with. */ export interface GuildStickerEditOptions { name?: string; description?: string | null; tags?: string; reason?: string; } /** * Manages the custom stickers of one guild. */ export declare class GuildStickerManager extends CachedManager<"stickers", Sticker, [stickerId: string]> { /** * The ID of the guild. */ readonly guildId: string; constructor(client: GatewayClient, guildId: string); protected createStructure(data: CacheEntityTypes["stickers"]): Sticker; keyOf(data: CacheEntityTypes["stickers"]): string; /** * Adds a sticker to the cache, and its uploader to `client.users`. * * @internal */ _add(data: CacheEntityTypes["stickers"], cache?: boolean, options?: AddOptions): Promise; _hydrate(data: CacheEntityTypes["stickers"]): Awaitable; resolveKey(stickerId: string): string; /** * Fetches every sticker of the guild, and caches them. */ fetchAll(): Promise; /** * Uploads a sticker. * * @param options The file, name, and tags. */ create(options: GuildStickerCreateOptions): Promise; /** * Edits a sticker. * * @param stickerId The ID of the sticker. * @param options The changes to apply. */ edit(stickerId: string, options: GuildStickerEditOptions): Promise; /** * Deletes a sticker. * * @param stickerId The ID of the sticker. * @param reason The reason for the audit log. */ delete(stickerId: string, reason?: string): Promise; /** * Fetches the user who uploaded a sticker, which the API only returns with `ManageGuildExpressions`. * * @param stickerId The ID of the sticker. */ fetchUser(stickerId: string): Promise; /** * Lists the stickers of the guild held in the cache, without calling the API. * * @remarks * It enumerates the whole entity cache, which a Redis store answers from its index: prefer `fetchAll` when the * cache may be incomplete. * * @returns The cached entries, `[]` when this entity is not cached. * @throws {TypeError} When the store cannot enumerate its entries. */ listCached(): Promise; protected fetchRaw(stickerId: string): Promise<{ id: import("discord-api-types/globals").Snowflake; pack_id?: import("discord-api-types/globals").Snowflake; name: string; description: string | null; tags: string; asset?: ''; type: import("discord-api-types/v10").StickerType; format_type: import("discord-api-types/v10").StickerFormatType; available?: boolean; user?: import("discord-api-types/v10").APIUser; sort_value?: number; guild_id: string; }>; private store; } export interface StickerPack extends StructureMixin {} /** * A pack of standard stickers: `@discordjs/structures`' `StickerPack`, with its stickers and banner URL. */ export declare class StickerPack extends StickerPack$1 { /** * @param data The raw sticker pack. * @param relations The related structures, resolved from the cache. */ constructor(data: APIStickerPack, relations?: object); /** * The ID of the pack's banner asset, `null` if it has none. */ get bannerId(): string | null; get stickers(): Sticker[]; /** * The sticker shown as the pack's cover, if any. */ get coverSticker(): Sticker | null; get createdTimestamp(): number; get createdAt(): Date; /** * Gets the URL of the pack's banner, or `null` if it has none. * @param options The image options. */ bannerURL(options?: BaseImageURLOptions): string | null; } /** * The relations of a {@link Sticker}, resolved from the cache by the guild's sticker manager. */ export interface StickerRelations { user?: User; guild?: Guild | null; } export interface Sticker extends StructureMixin {} /** * A sticker, a standard one from a sticker pack or a custom one of a guild: `@discordjs/structures`' `Sticker`, with * its guild, uploader, and URL, and actions through the client. */ export declare class Sticker extends Sticker$1 { /** * @param data The raw sticker. * @param relations The uploader and guild as resolved from the cache, by the guild's sticker manager. */ constructor(data: APISticker, relations?: StickerRelations); [kPatch](data: Readonly>): this; /** * The format of the sticker's image, an alias of `formatType`. */ get format(): StickerFormatType; /** * Whether the sticker can be used, `false` when its guild lost the boosts it needs. */ get available(): boolean; get guildId(): string | null; /** * The guild, from the cache. `null` outside of guilds, when the guild is not cached, or when the cache is * asynchronous: use `fetchGuild()` to always get it. */ get guild(): Guild | null; /** * Fetches the guild, cache first. `null` outside of guilds. */ fetchGuild(): Promise; /** * The ID of the pack of a standard sticker. */ get packId(): string | null; /** * The position of a standard sticker in its pack. */ get sortValue(): number | null; /** * The user who uploaded a guild sticker, when the payload includes it (it needs `ManageGuildExpressions`). */ get user(): User | null; get createdTimestamp(): number; get createdAt(): Date; /** * The URL of the sticker's image: a GIF for GIF stickers, a JSON file for Lottie ones, a PNG otherwise. */ get url(): string; /** * Fetches the sticker from the API and patches this structure with the result. */ fetch(): Promise; /** * Fetches the pack of a standard sticker, `null` for a guild sticker. */ fetchPack(): Promise; /** * Fetches the user who uploaded a guild sticker, `null` for a standard one or without `ManageGuildExpressions`. */ fetchUser(): Promise; /** * Edits a guild sticker. * * @param options The changes to apply. */ edit(options: GuildStickerEditOptions): Promise; /** * Deletes a guild sticker. * * @param reason The reason for the audit log. */ delete(reason?: string): Promise; /** * Whether this sticker has the same data as another one, like discord.js's `Sticker#equals`. Against a sticker, it * compares the ID, description, type, format, name, pack, tags, availability, guild, and sort value; against a raw * sticker, only the ID, description, name, and tags. `false` for anything else. * * @param other The sticker, or raw sticker, to compare with. */ equals(other: unknown): boolean; private requireGuildId; } export interface DMChannelMixin extends Channel {} /** * Adds the recipients of direct messages. */ export declare class DMChannelMixin { get recipients(): User[]; } export interface GroupDMMixin extends Channel {} /** * Adds the fields of group direct messages. */ export declare class GroupDMMixin { get name(): string | null; get icon(): string | null; /** * The ID of the application that created the group, if any. */ get applicationId(): string | null; /** * Gets the URL of the group's icon, or `null` if it has none. * @param options The image options. */ iconURL(options?: ImageURLOptions): string | null; } export interface GroupDMChannel extends StructureMixin, ChannelRelations>, MixinTypes, DMChannelMixin, TextChannelMixin, ChannelOwnerMixin, GroupDMMixin]> {} /** * A group direct message channel. */ export declare class GroupDMChannel extends GroupDMChannel$1 { /** * @param data The raw channel. * @param relations The guild as resolved from the cache, by `client.channels` or `client.threads`. */ constructor(data: ChannelDataType, relations?: ChannelRelations); } /** * The relations of a {@link Message}, resolved from the cache by `client.messages`. */ export interface MessageRelations { author?: User; /** * The author as a member, `null` outside of guilds. */ member?: GuildMember | null; guild?: Guild | null; channel?: AnyChannel | null; /** * The thread started from the message, from the thread cache. */ thread?: AnyThreadChannel | null; /** * The mentioned users, members, roles, and channels, from the cache. */ mentions?: MessageMentionsRelations; /** * The cached custom emojis of the message's reactions and poll answers, by ID, when they belong to its guild. */ emojis?: ReadonlyMap; } export interface Message extends StructureMixin {} /** * A message built from its IDs alone, like discord.js's `PartialMessage`: `partial` is `true`, and `content`, `author` * and `cleanContent` may be missing. Narrow a `Message | PartialMessage` with `partial`; {@link Message.fetch} * completes it. */ export interface PartialMessage extends Partialize, "pinned" | "system" | "tts" | "type", "author" | "cleanContent" | "content"> {} /** * A structure whose `channel` can not be a group direct message, like discord.js's `OmitPartialGroupDMChannel`: what * the message actions resolve to. */ export type OmitPartialGroupDMChannel = Structure & { channel: Exclude; }; /** * A snapshot of a forwarded message, like discord.js's `MessageSnapshot`: only the data Discord keeps, the rest may be * `null`. */ export type MessageSnapshot = Partialize>; /** * A Discord message: `@discordjs/structures`' `Message`, with its relations, substructures, and actions through the * client. * * @remarks * What discord.js reads synchronously from its cache is read the same way here with a synchronous cache: `guild`, * `channel`, and the `editable`, `deletable`, ... permission checks, which apply the channel's overwrites. With an * asynchronous cache the relation getters are `null` (use `fetchChannel()`, `fetchGuild()`, `fetchReference()`), and * the checks answer a promise read from the cache, typed as one once `GatewayCacheConfig` declares the cache * asynchronous. The `fetch*able()` twins also ask the API for what is not cached. */ type NullableMessageKeys = "webhook_id" | "application_id" | "nonce" | "position"; export declare class Message extends Message$1 { /** * Keeps the raw `timestamp` and `edited_timestamp`, which `@discordjs/structures` strips and re-serializes in its own * format, so that {@link Message.toJSON} returns the message as received. */ static DataTemplate: Partial; protected optimizeData(data: Partial): void; /** * @param data The raw message. * @param relations The author, member, guild, and channel as resolved from the cache, by `client.messages`. */ constructor(data: CacheEntityTypes["messages"], relations?: MessageRelations); [kPatch](data: Readonly>): this; get guildId(): If; /** * Whether the message was sent by Discord, e.g. a member join or a pin notice. */ get system(): boolean; /** * The author. Resolved from `client.users` when the message comes from a manager, so it has the latest known data of * the user, not only the copy embedded in the message. */ get author(): User; /** * The author as a guild member, or `null` for messages sent outside of a guild or by a webhook. */ get member(): GuildMember | null; /** * The guild the message was sent in, from the cache. `null` outside of guilds, when the guild is not cached, or when * the cache is asynchronous: use {@link Message.fetchGuild} to always get it. */ get guild(): If; /** * The channel the message was sent in, from the cache. `null` when the channel is not cached, or when the cache is * asynchronous: use {@link Message.fetchChannel} to always get it. */ get channel(): If | null; get flags(): Readonly; /** * The attachments of the message, by ID, like discord.js's `Message#attachments`. */ get attachments(): Collection; get embeds(): Embed[]; /** * The top-level components of the message, like discord.js'. Their `toJSON` returns the raw components; build new * ones with `@discordjs/builders`. */ get components(): MessageTopLevelComponent[]; /** * The stickers of the message, by ID, like discord.js's `Message#stickers`: partial stickers carrying the ID, name, * and format of the payload's sticker items. Fetch a full one with `client.fetchSticker(id)`. */ get stickers(): Collection; /** * The users, members, roles, and channels the message mentions: their cached copies when the message was built by * `client.messages`, like discord.js. */ get mentions(): MessageMentions; /** * The reactions of the message, whose `message` is this one, and whose custom emojis are the cached ones. */ get reactions(): ReactionManager; /** * The poll of the message, whose `message` is this one. */ get poll(): Poll | null; /** * The reference of a reply, crosspost, forward, or pin notice, if any, camel-cased like discord.js's * `Message#reference`. */ get reference(): MessageReference | null; /** * The snapshots of the messages this one forwards, as a collection of messages carrying the IDs of the forwarded * message, by that ID, like discord.js's `Message#messageSnapshots`. */ get messageSnapshots(): Collection; /** * The rich presence activity the message was sent with, e.g. a game invite, camel-cased like discord.js's * `Message#activity`. */ get activity(): MessageActivity | null; /** * The metadata of the interaction the message answers, if any, camel-cased like discord.js's * `Message#interactionMetadata`. */ get interactionMetadata(): MessageInteractionMetadata | null; /** * The call a call message is about, camel-cased like discord.js's `Message#call`. */ get call(): MessageCall | null; /** * The subscription a role subscription purchase message is about, camel-cased like discord.js's * `Message#roleSubscriptionData`. */ get roleSubscriptionData(): RoleSubscriptionData | null; /** * The custom client theme the message was shared with, camel-cased like discord.js's `Message#sharedClientTheme`. */ get sharedClientTheme(): SharedClientTheme | null; /** * Whether a thread was started from the message. */ get hasThread(): boolean; /** * The thread started from the message, like discord.js's `Message#thread`: the cached thread (its ID is the * message's), else the one of the payload. */ get thread(): AnyThreadChannel | null; /** * The content with user, role, and channel mentions replaced by names, and `@everyone`/`@here` defused, like * discord.js's `Message#cleanContent`. Mentions of entities that are not cached are kept. */ get cleanContent(): string; get createdTimestamp(): number; get createdAt(): Date; /** * When the message was last edited, `null` if it never was. */ get editedTimestamp(): number | null; /** * The ID of the webhook that sent the message, `null` when no webhook did, like discord.js's `Message#webhookId`. */ get webhookId(): string | null; /** * The ID of the application of an interaction or of a Rich Presence-related chat embed, `null` without one. */ get applicationId(): string | null; /** * The nonce the message was sent with, to check that it was sent, `null` without one. */ get nonce(): string | number | null; /** * The approximate position of the message in a thread, `null` outside of one. */ get position(): number | null; get editedAt(): Date | null; /** * The URL to jump to this message. */ get url(): string; /** * Whether the message was sent in a guild. */ inGuild(): this is Message; /** * Fetches the channel the message was sent in. */ fetchChannel(): Promise; /** * Fetches the guild the message was sent in, `null` outside of guilds. */ fetchGuild(): Promise; /** * Fetches the message this one replies to, crossposts, or forwards. */ fetchReference(): Promise>>; /** * Whether the bot can edit the message, like discord.js's `Message#editable`: it is the author. */ get editable(): boolean; /** * Whether the bot can delete the message, like discord.js's `Message#deletable`: it is the author, or it has * `ManageMessages` in the channel. * * @throws A `GatewayError` when the permissions are needed: `GuildUncachedMe`, `GuildUncached` or `ChannelUncached` on a cache miss. */ get deletable(): CacheRead; /** * Whether the bot can bulk delete the message, like discord.js's `Message#bulkDeletable`: it is newer than 14 days, * and the bot has `ManageMessages`. It throws like {@link Message.deletable}. */ get bulkDeletable(): CacheRead; /** * Whether the bot can pin the message, like discord.js's `Message#pinnable`: it is not a system message, and the * bot has `PinMessages`. It throws like {@link Message.deletable}. */ get pinnable(): CacheRead; /** * Whether the bot can publish the message, like discord.js's `Message#crosspostable`: it is in an announcement * channel, not crossposted yet, and the bot authored it or has `ManageMessages`. It throws like * {@link Message.deletable}. */ get crosspostable(): CacheRead; /** * Whether the bot can start a thread from the message, like discord.js's `Message#threadable`: it is in a text or * announcement channel, has no thread yet, and the bot has `ViewChannel` and `CreatePublicThreads` there. It throws * like {@link Message.deletable}. * * Unlike discord.js, which ignores the `Administrator` permission (`checkAdmin = false`), an administrator can * start a thread, as the API allows it. This only checks the permissions and the channel type: a locked or archived * parent, the limit of active threads, and an announcement message that has to be published first are not checked. */ get threadable(): CacheRead; /** * Whether the bot can delete the message: it is the author, or it has `ManageMessages` in the guild. * * @deprecated Use {@link Message.deletable}. When the guild, the channel or the bot's member may be missing from the * cache (a filtered cache, a `plugin-broker` worker), fetch them first (`client.members.fetchMe(guildId)`), then read * the getter. */ fetchDeletable(): Promise; /** * Whether the bot can bulk delete the message: it can delete it, and it is newer than 14 days. * * @deprecated Use {@link Message.bulkDeletable}. See {@link Message.fetchDeletable} for the cache-miss fallback. */ fetchBulkDeletable(): Promise; /** * Whether the bot can pin the message: it is not a system message, and the bot has `PinMessages`. * * @deprecated Use {@link Message.pinnable}. See {@link Message.fetchDeletable} for the cache-miss fallback. */ fetchPinnable(): Promise; /** * Whether the bot can publish the message: it is in an announcement channel, not crossposted yet, and the bot * authored it or has `ManageMessages`. * * @deprecated Use {@link Message.crosspostable}. See {@link Message.fetchDeletable} for the cache-miss fallback. */ fetchCrosspostable(): Promise; /** * Whether the message is partial, like discord.js's `Message#partial`: it lacks its content or its author. That is * a message built from its IDs alone for an event about an uncached message (see `Partials.Message`), or from an * update that carried neither. Only `id`, `channelId`, and `guildId` are reliable then, and {@link Message.fetch} * completes it. * * Typed `false`, like discord.js: a partial message is a {@link PartialMessage}, whose `partial` is `true`. */ get partial(): false; /** * Finds a component of the message by its custom ID, like discord.js's `Message#resolveComponent`. * * @param customId The custom ID. */ resolveComponent(customId: string): AnyComponent | APIAnyComponent | null; /** * Fetches the webhook that sent the message, like discord.js's `Message#fetchWebhook`. * * @throws A `GatewayError`: `WebhookMessage` when a webhook did not send the message, `WebhookApplication` when the * webhook belongs to an application. */ fetchWebhook(): Promise; /** * Fetches the message and patches this structure with the result. * * @param force Whether to ask the API even when the message is cached. Defaults to `true`, like discord.js. */ fetch(force?: boolean): Promise>; /** * Edits the message. * * @param options The changes, or the new content. */ edit(options: MessagePayloadResolvable): Promise>; /** * Replies to the message. * * @param options The reply, or its content. */ reply(options: MessagePayloadResolvable): Promise>>; /** * Forwards the message to another channel. * * @param channel The channel to forward it to, or its ID. */ forward(channel: Exclude): Promise>>; delete(reason?: string): Promise>; pin(reason?: string): Promise>; unpin(reason?: string): Promise>; /** * Reacts to the message as the bot. * * @param emoji The emoji. * @returns The reaction, counting the bot, like discord.js's `Message#react`. */ react(emoji: EmojiIdentifierResolvable): Promise; /** * Publishes the message of an announcement channel to the channels following it. */ crosspost(): Promise>; /** * Starts a thread from the message. * * @param options The thread's name and settings. */ startThread(options: MessageThreadCreateOptions): Promise; /** * Hides or shows the embeds of the message. * * @param suppress Whether to hide them. */ suppressEmbeds(suppress?: boolean): Promise>; /** * Removes every attachment of the message. */ removeAttachments(): Promise>; /** * Whether this message has the same data as another one, like discord.js's `Message#equals`: the same ID, author, * content, `nonce`, `tts`, attachments (by ID), and embeds (through `Embed#equals`, in order). A change of `pinned`, * flags, or reactions does not make messages differ; compare `toJSON()` for that. * * @param message The message, or raw message, to compare with. A raw embed update, which carries neither an author nor * attachments, only compares the ID and the number of embeds. * @param rawData The raw message `message` comes from. When given, `mention_everyone` and the timestamps are compared * too. */ equals(message: Message | APIMessage | null | undefined, rawData?: Partial): boolean; toJSON(): CacheEntityTypes["messages"]; toString(): string; private hasCachedPermission; private hasPermission; } /** * Manages the messages of one channel: `client.messages`, with the channel's ID filled in. * * @remarks * One class serves every channel, where discord.js has a `MessageManager` subclass per kind (`GuildMessageManager`, * `DMMessageManager`, `PartialGroupDMMessageManager`). The methods only a guild has (`crosspost`, `bulkDelete`, * `startThread`) throw `ChannelMessagesGuildOnly` before any request when the manager belongs to a direct message or a * group direct message, which the channel's own `messages` tells. A manager built by hand without the channel's type * sends the request, and Discord refuses it. */ export declare class ChannelMessageManager extends BaseManager { readonly channelId: string; /** * The type of the channel, when known. */ readonly channelType: ChannelType | null; /** * The cached messages of the channel, by message ID. * * @example * ```typescript * const message = await channel.messages.cache.get(messageId); * ``` */ readonly cache: ScopedCache; constructor(client: GatewayClient, channelId: string, channelType?: ChannelType | null); /** * Gets a message of the channel from the cache. Same as `cache.get`, always answering a promise. */ get(messageId: string): Promise; /** * Gets a message of the channel from the cache, falling back to the API. */ fetch(messageId: string, options?: FetchOptions): Promise; /** * Lists the messages of the channel, newest first. */ list(options?: MessageListOptions): Promise; send(options: MessagePayloadResolvable): Promise; edit(messageId: string, options: MessagePayloadResolvable): Promise; delete(messageId: string, reason?: string): Promise; fetchPins(options?: { limit?: number; before?: Date | number; }): Promise<{ items: PinnedMessage[]; hasMore: boolean; }>; pin(messageId: string, reason?: string): Promise; unpin(messageId: string, reason?: string): Promise; /** * Publishes a message of an announcement channel to the channels following it, like discord.js's * `GuildMessageManager#crosspost`. * * @param message The message, or its ID. * @throws {@link GatewayError} `ChannelMessagesGuildOnly` in a direct message. * @throws {@link GatewayTypeError} `IdUnresolvable` when `message` holds no ID. */ crosspost(message: MessageResolvable): Promise; /** * Deletes up to 100 messages at once. * * @throws {@link GatewayError} `ChannelMessagesGuildOnly` in a direct message, as the channel has no `bulkDelete`. */ bulkDelete(messages: Collection | readonly MessageResolvable[] | number, filterOld?: boolean): Promise>; forward(messageId: string, targetChannelId: string): Promise; react(messageId: string, emoji: EmojiIdentifierResolvable): Promise; removeReactionEmoji(messageId: string, emoji: EmojiIdentifierResolvable): Promise; removeAllReactions(messageId: string): Promise; /** * Starts a thread from a message. * * @throws {@link GatewayError} `ChannelMessagesGuildOnly` in a direct message. */ startThread(messageId: string, options: MessageThreadCreateOptions): Promise; endPoll(messageId: string): Promise; fetchPollAnswerVoters(messageId: string, answerId: number, options?: { limit?: number; after?: string; }): Promise; private assertGuild; } declare const kLastPinTimestamp: unique symbol; declare const kLastPinRaw: unique symbol; export interface TextChannelMixin extends Channel {} /** * Adds the fields and message actions of channels holding messages. */ export declare class TextChannelMixin { static DataTemplate: { last_pin_timestamp: string | null | undefined; }; protected [kLastPinTimestamp]: number | null | undefined; protected [kLastPinRaw]: string | null | undefined; static optimizeData(this: Channel, data: Partial): void; static enrichToJSON(this: Channel, data: object): void; get lastMessageId(): string | null; get lastPinTimestamp(): number | null; get lastPinAt(): Date | null; /** * The messages of the channel. */ get messages(): ChannelMessageManager; /** * Sends a message to the channel. * * @param options The message, or its content. */ send(options: MessagePayloadResolvable): Promise; /** * Shows the bot as typing in the channel, for about 10 seconds or until it sends a message. */ sendTyping(): Promise; /** * Fetches the last message of the channel, cache first. */ fetchLastMessage(): Promise; } export interface AnnouncementThreadChannel extends StructureMixin, ChannelRelations>, MixinTypes, TextChannelMixin, TextGuildChannelMixin, GuildChannelMixin, ChannelOwnerMixin, ChannelParentMixin, ChannelSlowmodeMixin, ThreadChannelMixin]> {} /** * A thread of an announcement channel. */ export declare class AnnouncementThreadChannel extends AnnouncementThreadChannel$1 { /** * @param data The raw channel. * @param relations The guild as resolved from the cache, by `client.channels` or `client.threads`. */ constructor(data: ChannelDataType, relations?: ChannelRelations); } /** * The options to create a channel inside a category with: the guild channel's, minus its category and with no * category type, as Discord does not nest categories. */ export interface CategoryCreateChannelOptions extends Omit { type?: Exclude; } /** * Manages the channels of one {@link CategoryChannel}, like discord.js's `CategoryChannelChildManager`. * * @remarks * It holds no cache of its own: {@link CategoryChannelChildManager.cache} is read from the channel cache each time, so * it always agrees with `client.channels`. With a remote cache the store must be able to enumerate its entries, or * reading it throws `CacheNotIterable`, like `listCached`. */ export declare class CategoryChannelChildManager extends BaseManager { /** * The category these channels belong to. */ readonly channel: CategoryChannel; /** * @param channel The category. */ constructor(channel: CategoryChannel); /** * The category's guild, from the cache: `null` when it is not cached. */ get guild(): Guild | null; /** * The channels of the category held in the cache, by ID, threads excluded. Channels that are not cached are not * listed. A promise with an asynchronous cache, see {@link CacheRead}. */ get cache(): CacheRead>; /** * Creates a channel in the category. * * @param options The channel's name, type, and settings. * @throws {GatewayTypeError} `CategoryChildCategory` when the type is a category. */ create(options: CategoryCreateChannelOptions): Promise; /** * Gets a cached channel of the category. * * @param child The channel, or its ID. * @returns The channel, `null` when it is not cached or belongs to another category. */ resolve(child: IdResolvable): CacheRead; /** * Gets the ID of a channel, or of an ID. * * @param child The channel, or its ID. */ resolveId(child: IdResolvable): string; /** * The category's cache, like discord.js. */ valueOf(): CacheRead>; } /** * The relations of a {@link PermissionOverwrites}: the channel it belongs to. */ export interface PermissionOverwritesRelations { channel?: AnyChannel | null; } /** * The raw data of a permission overwrite, with the channel it belongs to. */ export type PermissionOverwritesData = APIOverwrite & { channel_id: string; }; declare const kOptimizedAllow: unique symbol; declare const kOptimizedDeny: unique symbol; /** * A permission overwrite of a channel: what it allows and denies to a role or a member. */ export declare class PermissionOverwrites extends Structure { [kRelations]: PermissionOverwritesRelations; protected [kOptimizedAllow]: bigint; protected [kOptimizedDeny]: bigint; protected optimizeData(data: Partial): void; /** * The ID of the role or member the overwrite targets. */ get id(): string; get channelId(): string; /** * The channel the overwrite belongs to, like discord.js's `PermissionOverwrites#channel`: `null` when the channel is * not cached, or when the cache is asynchronous. */ get channel(): AnyChannel | null; /** * Whether the overwrite targets a role or a member. */ get type(): import("discord-api-types/v10").OverwriteType; get allow(): Readonly; get deny(): Readonly; /** * Changes some permissions of the overwrite, keeping the others. * * @param options The permissions to change. * @param reason The reason for the audit log. */ edit(options: PermissionOverwriteOptions, reason?: string): Promise; /** * Deletes the overwrite. * * @param reason The reason for the audit log. */ delete(reason?: string): Promise; } /** * The options of {@link PermissionOverwriteManager.create} and {@link PermissionOverwriteManager.edit}. */ export interface PermissionOverwriteEditOptions { /** * Whether the target is a role or a member. Guessed from the cache when absent: a cached role of the guild with * that ID makes it a role, anything else a member. */ type?: OverwriteType; reason?: string; } /** * Manages the permission overwrites of one channel, as they were in the channel's payload. */ export declare class PermissionOverwriteManager extends BaseManager { #private; readonly channelId: string; readonly guildId: string | null; /** * @param client The client. * @param channelId The ID of the channel. * @param guildId The ID of the channel's guild, if known. * @param overwrites The raw overwrites of the channel. * @param channel The channel, which the overwrites refer to. */ constructor(client: GatewayClient, channelId: string, guildId: string | null, overwrites: readonly APIOverwrite[], channel?: AnyChannel | null); /** * The overwrites of the channel. */ get cache(): PermissionOverwrites[]; /** * Finds the overwrite of a role or member, if the channel has one. * * @param target The role or member, or its ID. */ resolve(target: IdResolvable): PermissionOverwrites | null; /** * Replaces every overwrite of the channel. * * @param overwrites The new overwrites. * @param reason The reason for the audit log. */ set(overwrites: readonly OverwriteData[], reason?: string): Promise; /** * Creates the overwrite of a role or member, replacing any existing one. * * @param target The role or member, or its ID. * @param options The permissions to allow (`true`) or deny (`false`). * @param editOptions The target's type and the reason for the audit log. */ create(target: IdResolvable, options: PermissionOverwriteOptions, editOptions?: PermissionOverwriteEditOptions): Promise; /** * Changes some permissions of the overwrite of a role or member, creating it if needed. * * @param target The role or member, or its ID. * @param options The permissions to allow (`true`), deny (`false`), or reset (`null`). * @param editOptions The target's type and the reason for the audit log. */ edit(target: IdResolvable, options: PermissionOverwriteOptions, editOptions?: PermissionOverwriteEditOptions): Promise; /** * Deletes the overwrite of a role or member. * * @param target The role or member, or its ID. * @param reason The reason for the audit log. */ delete(target: IdResolvable, reason?: string): Promise; private upsert; private guessType; private patchCached; } type Data = { guild_id?: string; parent_id?: string | null; position?: number; permission_overwrites?: APIOverwrite[]; }; export declare function sameOverwrites(channel: Data, parent: Data): boolean; export interface ChannelPermissionMixin extends Channel {} /** * Adds the position and permission overwrites of guild channels other than threads. */ export declare class ChannelPermissionMixin { get position(): number; /** * The permission overwrites of the channel. */ get permissionOverwrites(): PermissionOverwriteManager; /** * Whether the channel's overwrites are the same as its category's, like discord.js's * `GuildChannel#permissionsLocked`: `null` when it has no category, or when the category is not in a synchronous cache (see * {@link ChannelPermissionMixin.fetchPermissionsLocked}). */ get permissionsLocked(): boolean | null; /** * Moves the channel among the channels it is sorted with, like discord.js's `GuildChannel#setPosition`. * * @param position The index to move it to among them, or the offset to move it by with `relative`. * @param options Whether the position is relative, and the reason for the audit log. */ setPosition(position: number, options?: SetPositionOptions): Promise; /** * Moves the channel into a category, or out of its category. * * @param parent The category, `null` to move the channel out. * @param options Whether to copy the category's overwrites (the default), and the reason for the audit log. */ setParent(parent: IdResolvable | null, options?: { lockPermissions?: boolean; reason?: string; }): Promise; setNSFW(nsfw?: boolean, reason?: string): Promise; /** * Replaces the channel's overwrites with its category's. * * @param reason The reason for the audit log. */ lockPermissions(reason?: string): Promise; /** * Fetches whether the channel's overwrites are the same as its category's. `null` without a category. * * @deprecated Use {@link ChannelPermissionMixin.permissionsLocked}. When the category may be missing from the cache, * fetch it first (`client.channels.fetch(channel.parentId)`), then read the getter. */ fetchPermissionsLocked(): Promise; /** * The permissions of a member or role in the channel, like discord.js's `GuildChannel#permissionsFor`: their guild * permissions with the channel's overwrites applied, read from the cache. * * @param target A member, a role, or the ID of a cached member. * @throws A `GatewayError`: `GuildMemberUncached` or `GuildUncached` on a miss. */ permissionsFor(target: GuildMember | Role | string): CacheRead>; /** * Fetches the permissions of a member or role in the channel: their guild permissions with the channel's overwrites * applied. discord.js: `channel.permissionsFor(memberOrRole)`. * * @param target A member, a role, or the ID of a member. * * @deprecated Use {@link ChannelPermissionMixin.permissionsFor}. When the guild or the member may be missing from the * cache, fetch them first (`client.guilds.fetch(guildId)`, `client.members.fetch(guildId, userId)`), then call the * method. */ fetchPermissionsFor(target: GuildMember | Role | string): Promise>; } export interface CategoryChannel extends StructureMixin, ChannelRelations>, MixinTypes, GuildChannelMixin, ChannelPermissionMixin]> {} /** * A guild category. */ export declare class CategoryChannel extends CategoryChannel$1 { /** * @param data The raw channel. * @param relations The guild as resolved from the cache, by `client.channels` or `client.threads`. */ constructor(data: ChannelDataType, relations?: ChannelRelations); /** * The channels of the category, like discord.js's `CategoryChannel#children`. */ get children(): CategoryChannelChildManager; } /** * Manages the threads of one channel: `client.threads`, with the channel's ID filled in. */ export declare class ChannelThreadManager extends BaseManager { readonly channelId: string; readonly guildId: string | null; /** * The type of the channel, when known: it tells a forum or media channel, whose threads are posts created with a * `message`, from a text or announcement channel. */ readonly channelType: ChannelType | null; constructor(client: GatewayClient, channelId: string, guildId: string | null, channelType?: ChannelType | null); /** * Creates a thread in the channel, or a post in a forum or media channel (with `message`). discord.js splits this in * `GuildTextThreadManager` and `GuildForumThreadManager`; here the manager is shared and the options are checked * against the type of the channel. * * @param options The thread's name and settings. * @throws {@link GatewayTypeError} `ThreadPostMessageRequired` in a forum or media channel without `message`, * `ThreadOptionsThreadOnly` there with `type` or `invitable`, and `ThreadOptionsPostOnly` with `message` or * `appliedTags` in any other channel. */ create(options: ThreadCreateOptions): Promise; /** * Fetches the active threads of the channel, and caches them. */ fetchActive(): Promise; /** * Fetches the archived threads of the channel, and caches them. * * @param options Public or private threads, and the page. */ fetchArchived(options?: FetchArchivedThreadsOptions): Promise; } export interface ChannelThreadsMixin extends Channel {} /** * Adds the threads of the channels that can have threads. */ export declare class ChannelThreadsMixin { /** * The threads of the channel. */ get threads(): ChannelThreadManager; } export interface ChannelWebhooksMixin extends Channel {} /** * Adds the webhook actions of the channels that can have webhooks. */ export declare class ChannelWebhooksMixin { /** * Fetches the webhooks of the channel. */ fetchWebhooks(): Promise; /** * Creates a webhook in the channel. * * @param options The webhook's name and avatar, and the reason for the audit log. */ createWebhook(options: WebhookCreateOptions): Promise; } export interface ChannelTopicMixin extends Channel {} /** * Adds the topic of text, announcement, forum, and media channels. */ export declare class ChannelTopicMixin { get topic(): string | null; setTopic(topic: string | null, reason?: string): Promise; } export interface ThreadOnlyChannelMixin extends Channel {} /** * Adds the fields of forum and media channels, which only hold threads. */ export declare class ThreadOnlyChannelMixin { /** * The tags threads can have, camel-cased like discord.js's `ForumChannel#availableTags`. */ get availableTags(): GuildForumTag[]; /** * The emoji reacted to new threads with, camel-cased like discord.js's `ForumChannel#defaultReactionEmoji`. */ get defaultReactionEmoji(): DefaultReactionEmoji | null; get defaultThreadRateLimitPerUser(): number; setAvailableTags(availableTags: readonly GuildForumTagData[], reason?: string): Promise; setDefaultReactionEmoji(defaultReactionEmoji: DefaultReactionEmoji | APIGuildForumDefaultReactionEmoji | null, reason?: string): Promise; setDefaultThreadRateLimitPerUser(defaultThreadRateLimitPerUser: number, reason?: string): Promise; setDefaultSortOrder(defaultSortOrder: SortOrderType | null, reason?: string): Promise; setDefaultForumLayout(defaultForumLayout: ForumLayoutType, reason?: string): Promise; } export interface ForumChannel extends StructureMixin, ChannelRelations>, MixinTypes, GuildChannelMixin, ChannelParentMixin, ChannelPermissionMixin, ChannelSlowmodeMixin, ChannelTopicMixin, ThreadOnlyChannelMixin, ChannelWebhooksMixin, ChannelThreadsMixin]> {} /** * A guild forum channel. */ export declare class ForumChannel extends ForumChannel$1 { /** * @param data The raw channel. * @param relations The guild as resolved from the cache, by `client.channels` or `client.threads`. */ constructor(data: ChannelDataType, relations?: ChannelRelations); } export interface MediaChannel extends StructureMixin, ChannelRelations>, MixinTypes, GuildChannelMixin, ChannelParentMixin, ChannelPermissionMixin, ChannelSlowmodeMixin, ChannelTopicMixin, ThreadOnlyChannelMixin, ChannelWebhooksMixin, ChannelThreadsMixin]> {} /** * A guild media channel. */ export declare class MediaChannel extends MediaChannel$1 { /** * @param data The raw channel. * @param relations The guild as resolved from the cache, by `client.channels` or `client.threads`. */ constructor(data: ChannelDataType, relations?: ChannelRelations); } /** * The fields of a scheduled event that can be edited. */ export interface GuildScheduledEventEditOptions { name?: string; description?: string | null; /** * The stage or voice channel, `null` for an external event. */ channel?: IdResolvable | null; scheduledStartTime?: Date | number; scheduledEndTime?: Date | number | null; privacyLevel?: GuildScheduledEventPrivacyLevel; entityType?: GuildScheduledEventEntityType; /** * Where an external event takes place. */ entityMetadata?: APIGuildScheduledEventEntityMetadata | null; /** * Starts, ends, or cancels the event. */ status?: GuildScheduledEventStatus; /** * The cover image: a data URI, or anything `resolveImage` reads. `null` removes it. */ image?: ImageResolvable | null; /** * How the event repeats, camel-cased like discord.js's `GuildScheduledEventRecurrenceRuleOptions` or raw. */ recurrenceRule?: GuildScheduledEventRecurrenceRuleOptions | Partial | null; reason?: string; } /** * The options to create a scheduled event with. */ export interface GuildScheduledEventCreateOptions extends Omit { name: string; scheduledStartTime: Date | number; privacyLevel: GuildScheduledEventPrivacyLevel; entityType: GuildScheduledEventEntityType; } /** * The options to fetch the subscribers of an event with. `before` and `after` are user IDs. */ export interface GuildScheduledEventSubscribersOptions { /** * How many users to fetch, up to 100. */ limit?: number; before?: string; after?: string; /** * Whether to include each user's guild member. */ withMember?: boolean; } /** * A user subscribed to a scheduled event. */ export interface GuildScheduledEventSubscriber { user: User; member: GuildMember | null; } /** * Manages the scheduled events of one guild. */ export declare class GuildScheduledEventManager extends CachedManager<"scheduledEvents", GuildScheduledEvent, [eventId: string]> { readonly guildId: string; constructor(client: GatewayClient, guildId: string); protected createStructure(data: CacheEntityTypes["scheduledEvents"]): GuildScheduledEvent; keyOf(data: CacheEntityTypes["scheduledEvents"]): string; resolveKey(eventId: string): string; /** * Adds an event to the cache, and its creator to `client.users`. * * @internal */ _add(data: CacheEntityTypes["scheduledEvents"], cache?: boolean, options?: AddOptions): Promise; _hydrate(data: CacheEntityTypes["scheduledEvents"]): Awaitable; /** * Fetches every scheduled event of the guild, and caches them. * * @param options Whether to include how many users subscribed to each. */ fetchAll(options?: { withUserCount?: boolean; }): Promise; /** * Creates a scheduled event. * * @param options The event's name, time, place, and privacy. */ create(options: GuildScheduledEventCreateOptions): Promise; /** * Edits a scheduled event. * * @param eventId The ID of the event. * @param options The fields to edit, and the reason for the audit log. */ edit(eventId: string, options: GuildScheduledEventEditOptions): Promise; /** * Deletes a scheduled event. * * @param eventId The ID of the event. * @param reason The reason for the audit log. */ delete(eventId: string, reason?: string): Promise; /** * Fetches the users who subscribed to an event, and caches them. * * @param eventId The ID of the event. * @param options How many users, around which user ID, and whether to include their members. */ fetchSubscribers(eventId: string, options?: GuildScheduledEventSubscribersOptions): Promise; protected fetchRaw(eventId: string): Promise; } /** * The relations of a {@link GuildScheduledEvent}, resolved from the cache by the guild's event manager. */ export interface GuildScheduledEventRelations { creator?: User | null; guild?: Guild | null; channel?: AnyChannel | null; } /** * An event scheduled in a guild: in a stage or voice channel, or somewhere else. */ export declare class GuildScheduledEvent extends Structure { [kRelations]: GuildScheduledEventRelations; protected optimizeData(data: Partial): void; /** * @param data The raw event. * @param relations The creator, guild, and channel as resolved from the cache, by the guild's event manager. */ constructor(data: APIGuildScheduledEvent, relations?: GuildScheduledEventRelations); [kPatch](data: Readonly>): this; get id(): string; get guildId(): string; get channelId(): string | null; get creatorId(): string | null; get name(): string; /** * Whether the event is partial: built from its IDs alone for an event about an uncached scheduled event, see * `Partials.GuildScheduledEvent`. Only `id` and `guildId` are reliable then, and {@link GuildScheduledEvent.fetch} * completes it. */ get partial(): boolean; /** * Fetches the event from the API and patches this structure with the result. */ fetch(): Promise; get description(): string | null; get scheduledStartTimestamp(): number; get scheduledStartAt(): Date; get scheduledEndTimestamp(): number | null; get scheduledEndAt(): Date | null; get privacyLevel(): import("discord-api-types/v10").GuildScheduledEventPrivacyLevel; get status(): GuildScheduledEventStatus; get entityType(): import("discord-api-types/v10").GuildScheduledEventEntityType; get entityId(): string | null; /** * Where an external event takes place. */ get location(): string | null; /** * The metadata of the event, camel-cased like discord.js's `GuildScheduledEvent#entityMetadata`. */ get entityMetadata(): GuildScheduledEventEntityMetadata | null; /** * How many users subscribed, when the payload includes it. */ get userCount(): number | null; get image(): string | null; /** * How the event repeats, camel-cased like discord.js's `GuildScheduledEvent#recurrenceRule`. */ get recurrenceRule(): GuildScheduledEventRecurrenceRule | null; /** * The creator, from the payload or the cache. */ get creator(): User | null; get guild(): Guild | null; get channel(): AnyChannel | null; /** * The URL of the event. */ get url(): string; get createdTimestamp(): number; get createdAt(): Date; coverImageURL(options?: Readonly): string | null; isScheduled(): boolean; isActive(): boolean; isCompleted(): boolean; isCanceled(): boolean; /** * Edits the event. * * @param options The fields to edit, and the reason for the audit log. */ edit(options: GuildScheduledEventEditOptions): Promise; setName(name: string, reason?: string): Promise; setDescription(description: string | null, reason?: string): Promise; setScheduledStartTime(scheduledStartTime: Date | number, reason?: string): Promise; setScheduledEndTime(scheduledEndTime: Date | number | null, reason?: string): Promise; setStatus(status: GuildScheduledEventStatus, reason?: string): Promise; /** * Sets where an external event takes place. */ setLocation(location: string, reason?: string): Promise; /** * Fetches the users who subscribed to the event, paginated by user ID. * * @param options How many users, around which user ID, and whether to include their members. */ fetchSubscribers(options?: GuildScheduledEventSubscribersOptions): Promise; delete(reason?: string): Promise; } /** * The relations of a {@link StageInstance}, resolved from the cache by the guild's stage instance manager. */ export interface StageInstanceRelations { guild?: Guild | null; channel?: AnyChannel | null; guildScheduledEvent?: GuildScheduledEvent | null; } export interface StageInstance extends StructureMixin {} /** * A live stage, the topic of a stage channel while it is open: `@discordjs/structures`' `StageInstance`, with its * guild and channel, and actions through the client. */ export declare class StageInstance extends StageInstance$1 { /** * @param data The raw stage instance. * @param relations The guild and channel as resolved from the cache, by the guild's stage instance manager. */ constructor(data: APIStageInstance, relations?: StageInstanceRelations); get guild(): Guild | null; get channel(): AnyChannel | null; /** * The scheduled event the stage belongs to, from the cache, like discord.js's * `StageInstance#guildScheduledEvent`: `null` when it has none, when it is not cached, or when the stage was not * built by its guild's stage instance manager. */ get guildScheduledEvent(): GuildScheduledEvent | null; [kPatchRelations](data: object): void; get createdTimestamp(): number; get createdAt(): Date; /** * Fetches the scheduled event the stage belongs to, if any. */ fetchGuildScheduledEvent(): Promise; /** * Edits the stage. * * @param options The topic and privacy level, and the reason for the audit log. */ edit(options: StageInstanceEditOptions): Promise; setTopic(topic: string, reason?: string): Promise; setPrivacyLevel(privacyLevel: StageInstancePrivacyLevel, reason?: string): Promise; /** * Ends the stage. * * @param reason The reason for the audit log. */ delete(reason?: string): Promise; } /** * The fields of a stage instance that can be edited. */ export interface StageInstanceEditOptions { topic?: string; privacyLevel?: StageInstancePrivacyLevel; reason?: string; } /** * The options to start a stage with. */ export interface StageInstanceCreateOptions extends StageInstanceEditOptions { topic: string; /** * Whether to notify the members of the guild that the stage started. */ sendStartNotification?: boolean; /** * The scheduled event the stage belongs to. */ guildScheduledEvent?: IdResolvable; } /** * Manages the stage instances of one guild, keyed by the ID of their stage channel. */ export declare class StageInstanceManager extends CachedManager<"stageInstances", StageInstance, [channelId: string]> { readonly guildId: string; constructor(client: GatewayClient, guildId: string); protected createStructure(data: CacheEntityTypes["stageInstances"]): StageInstance; keyOf(data: CacheEntityTypes["stageInstances"]): string; resolveKey(channelId: string): string; _hydrate(data: CacheEntityTypes["stageInstances"]): Awaitable; /** * Starts a stage in a stage channel. * * @param channel The stage channel, or its ID. * @param options The topic and privacy level, and whether to notify the guild. */ create(channel: IdResolvable, options: StageInstanceCreateOptions): Promise; /** * Edits the stage of a channel. * * @param channelId The ID of the stage channel. * @param options The topic and privacy level, and the reason for the audit log. */ edit(channelId: string, options: StageInstanceEditOptions): Promise; /** * Ends the stage of a channel. * * @param channelId The ID of the stage channel. * @param reason The reason for the audit log. */ delete(channelId: string, reason?: string): Promise; protected fetchRaw(channelId: string): Promise; } export interface VoiceChannelMixin extends Channel {} /** * Adds the fields of voice and stage channels. */ export declare class VoiceChannelMixin { get bitrate(): number; /** * The user limit, `0` when unlimited. */ get userLimit(): number; /** * The voice region, `null` for automatic. */ get rtcRegion(): string | null; get videoQualityMode(): number | null; setBitrate(bitrate: number, reason?: string): Promise; /** * Sets the user limit. * * @param userLimit The user limit, `0` for none. * @param reason The reason for the audit log. */ setUserLimit(userLimit: number, reason?: string): Promise; /** * Sets the voice region. * * @param rtcRegion The region, `null` for automatic. * @param reason The reason for the audit log. */ setRTCRegion(rtcRegion: string | null, reason?: string): Promise; setVideoQualityMode(videoQualityMode: VideoQualityMode, reason?: string): Promise; } export interface StageChannel extends StructureMixin, ChannelRelations>, MixinTypes, TextChannelMixin, TextGuildChannelMixin, GuildChannelMixin, ChannelParentMixin, ChannelPermissionMixin, ChannelSlowmodeMixin, VoiceChannelMixin, ChannelWebhooksMixin]> {} /** * A guild stage channel. */ export declare class StageChannel extends StageChannel$1 { /** * @param data The raw channel. * @param relations The guild as resolved from the cache, by `client.channels` or `client.threads`. */ constructor(data: ChannelDataType, relations?: ChannelRelations); /** * The live stage of the channel, from the cache, like discord.js's `StageChannel#stageInstance`: `null` when the * stage is not live, when it is not cached, or when the channel was not built by a manager. * * @remarks * Its own `channel` is this channel, and its scheduled event is not resolved: use * {@link StageChannel.fetchStageInstance} for the stage with every relation. */ get stageInstance(): StageInstance | null; /** * Fetches the live stage of the channel, `null` when the stage is not live. */ fetchStageInstance(): Promise; /** * Starts a stage in the channel. * * @param options The topic and privacy level, and whether to notify the guild. */ createStageInstance(options: StageInstanceCreateOptions): Promise; } export interface TextChannel extends StructureMixin, ChannelRelations>, MixinTypes, TextChannelMixin, TextGuildChannelMixin, GuildChannelMixin, ChannelParentMixin, ChannelPermissionMixin, ChannelSlowmodeMixin, ChannelTopicMixin, ChannelWebhooksMixin, ChannelThreadsMixin]> {} /** * A guild text channel. */ export declare class TextChannel extends TextChannel$1 { /** * @param data The raw channel. * @param relations The guild as resolved from the cache, by `client.channels` or `client.threads`. */ constructor(data: ChannelDataType, relations?: ChannelRelations); } /** * The raw data of a ban: the banned user, the guild, and the reason when it came from the API. */ export type GuildBanData = CacheEntityTypes["bans"] & { reason?: string | null; }; /** * The relations of a {@link GuildBan}, resolved from the cache by the guild's ban manager. */ export interface GuildBanRelations { user?: User; guild?: Guild | null; } /** * A ban of a user from a guild. */ export declare class GuildBan extends Structure { [kRelations]: GuildBanRelations; /** * @param data The raw ban. * @param relations The user and guild as resolved from the cache, by the guild's ban manager. */ constructor(data: GuildBanData, relations?: GuildBanRelations); get guildId(): string; get user(): User; /** * The reason of the ban. Only bans fetched from the API have it: the gateway does not send it. */ get reason(): string | null; get guild(): Guild | null; /** * Fetches the ban from the API, which knows its reason. */ fetch(): Promise; /** * Lifts the ban. * * @param reason The reason for the audit log. */ remove(reason?: string): Promise; } /** * The raw data of an invite, from the REST API (`APIExtendedInvite`, with a nested `channel` and `guild`) or from an * `INVITE_CREATE` dispatch (with `channel_id` and `guild_id`). */ export type InviteData = { code: string; } & Partial> & Partial> & { uses?: number; }; /** * The relations of an invite, resolved from the cache by `client.guilds.invites()`. */ export interface InviteRelations { inviter?: User; targetUser?: User; guild?: Guild | null; channel?: AnyChannel | null; } export interface BaseInvite extends StructureMixin {} /** * The base of every invite, to a guild, to a group direct message, or a friend invite: `@discordjs/structures`' * `Invite`, with its channel, inviter, target user, and discord.js' helpers. * * @typeParam Data The raw invite data this structure wraps. */ export declare class BaseInvite extends Invite<""> { /** * Keeps the raw `created_at` and `expires_at`, which `@discordjs/structures` strips and re-serializes in its own * format, so that {@link BaseInvite.toJSON} returns the invite as received. */ static readonly DataTemplate: Partial; /** * Matches the invite URLs Discord hands out, capturing their `code`, like discord.js's `BaseInvite.InvitesPattern`. */ static readonly InvitesPattern: RegExp; protected optimizeData(data: Partial): void; /** * @param data The raw invite. * @param relations The inviter, target user, and guild as resolved from the cache, by `client.guilds.invites()`. */ constructor(data: Data, relations?: InviteRelations); [kPatch](data: Readonly>): this; /** * The URL of the invite. */ get url(): string; get type(): InviteType; get channelId(): string | null; /** * The channel the invite leads to, like discord.js's `BaseInvite#channel`: the cached channel, else the partial * channel the API returns with the invite, if any. */ get channel(): AnyChannel | APIInviteChannel | null; /** * The user who created the invite, if known. */ get inviter(): User | null; get inviterId(): string | null; get targetUser(): User | null; get targetApplication(): Partial | null; get createdTimestamp(): number | null; get createdAt(): Date | null; /** * When the invite expires, `null` when it never does or it is unknown. */ get expiresTimestamp(): number | null; get expiresAt(): Date | null; /** * Transforms this invite into its raw data, as received. * * @remarks * Typed as `@discordjs/structures`' `APIActualInvite`, but an invite built from an `INVITE_CREATE` dispatch has the * dispatch's fields instead. */ toJSON(): APIActualInvite; valueOf(): string; } /** * The raw fields every guild-like payload carries, from the partial guilds of invites to full guilds. */ export type AnonymousGuildData = Pick & Partial>; /** * The public attributes shared by {@link Guild} and {@link InviteGuild}, i.e. what an anonymous user can see of a * guild. * * @remarks * Merges discord.js's `BaseGuild` and `AnonymousGuild`, there being no `OAuth2Guild` here to justify the split. * * @typeParam Data The raw guild data this structure wraps. */ export declare class AnonymousGuild extends Structure { get id(): Data["id"]; get name(): Data["name"]; get icon(): Data["icon"]; get features(): Data["features"]; get splash(): string | null; get banner(): string | null; get description(): string | null; get verificationLevel(): NonNullable | null; /** * The vanity invite code of the guild, if any. */ get vanityURLCode(): string | null; get nsfwLevel(): NonNullable | null; /** * The total number of boosts of the guild, or `null` if unknown. */ get premiumSubscriptionCount(): number | null; get createdTimestamp(): number; get createdAt(): Date; /** * The acronym shown in place of the guild's icon when it has none. */ get nameAcronym(): string; /** * Whether the guild is partnered. */ get partnered(): boolean; /** * Whether the guild is verified. */ get verified(): boolean; /** * Gets the URL of the guild's icon, or `null` if it has none. * @param options The image options. */ iconURL(options?: ImageURLOptions): string | null; /** * Gets the URL of the guild's banner, or `null` if it has none. * @param options The image options. */ bannerURL(options?: ImageURLOptions): string | null; /** * Gets the URL of the guild's invite splash image, or `null` if it has none. * @param options The image options. */ splashURL(options?: BaseImageURLOptions): string | null; toString(): string; } /** * The partial guild carried by a {@link GuildInvite}. * * @remarks * The welcome screen discord.js attaches here comes with the admin phase (see #54). */ export declare class InviteGuild extends AnonymousGuild {} /** * An invite to a guild. */ export declare class GuildInvite extends BaseInvite { get guildId(): string | null; /** * The guild the invite leads to: the cached guild when the invite comes from a manager, like discord.js, else the * partial guild the API returns with the invite, if any. */ get guild(): Guild | InviteGuild | null; /** * Whether the bot can delete the invite, like discord.js's `GuildInvite#deletable`: it created it, or it has * `ManageGuild` (or `ManageChannels`). * * @throws A `GatewayError` when the permissions are needed: `GuildUncachedMe` or `GuildUncached` on a cache miss. */ get deletable(): CacheRead; /** * Whether the bot can delete the invite: it created it, or it has `ManageGuild` (or `ManageChannels`). * * @deprecated Use {@link GuildInvite.deletable}. When the guild or the bot's member may be missing from the cache (a * filtered cache, a `plugin-broker` worker), fetch them first (`client.members.fetchMe(guildId)`), then read the * getter. */ fetchDeletable(): Promise; /** * Deletes the invite. * * @param reason The reason for the audit log. */ delete(reason?: string): Promise; } /** * The relations of an {@link Entitlement}, resolved from the cache. */ export interface EntitlementRelations { guild?: Guild | null; user?: User | null; } export interface Entitlement extends StructureMixin {} /** * A user's or a guild's access to a premium offer (a SKU) of the application: `@discordjs/structures`' * `Entitlement`, with its guild and user, and actions through the client. */ export declare class Entitlement extends Entitlement$1 { /** * @param data The raw entitlement. * @param relations The guild and user as resolved from the cache. */ constructor(data: APIEntitlement, relations?: EntitlementRelations); /** * The guild that is granted access to the SKU, from the cache: `null` for an entitlement of a user, or when the * guild is not cached. */ get guild(): Guild | null; /** * The user that is granted access to the SKU, from the cache: `null` for an entitlement of a guild, or when the * user is not cached. */ get user(): User | null; /** * The date at which the entitlement is valid from, `null` for a test entitlement. Like discord.js's * `Entitlement#startsAt`. */ get startsAt(): Date | null; /** * The date at which the entitlement stops being valid, `null` if it never does. Like discord.js's * `Entitlement#endsAt`. */ get endsAt(): Date | null; get createdAt(): Date | null; /** * Whether the entitlement is active: not deleted, and not ended. */ isActive(): boolean; /** * Whether the entitlement is a test one, created through `entitlements.createTest`. */ isTest(): boolean; /** * Whether the entitlement is a subscription of a user. */ isUserSubscription(): boolean; /** * Whether the entitlement is a subscription of a guild. */ isGuildSubscription(): boolean; /** * Fetches the user that is granted access to the SKU. * * @throws {GatewayTypeError} `IdUnresolvable` when the entitlement belongs to a guild, without a user. */ fetchUser(): Promise; /** * Marks the entitlement as consumed. Only available for one-time purchase consumable SKUs. */ consume(): Promise; /** * Whether this entitlement has the same data as another one. `false` for anything that is neither an entitlement nor * a raw one. * * @param other The entitlement, or raw entitlement, to compare with. */ equals(other: unknown): boolean; } export interface Subscription extends StructureMixin {} /** * A user's recurring purchase of a SKU: `@discordjs/structures`' `Subscription`. */ export declare class Subscription extends Subscription$1 { /** * @param data The raw subscription. */ constructor(data: APISubscription); /** * The time the subscription was created at, from its ID. */ get createdAt(): Date | null; /** * The time the current period of the subscription starts at. */ get currentPeriodStartAt(): Date | null; /** * The time the current period of the subscription ends at. */ get currentPeriodEndAt(): Date | null; /** * The time the subscription was canceled at, `null` if it was not. */ get canceledAt(): Date | null; /** * Whether this subscription has the same data as another one. `false` for anything that is neither a subscription * nor a raw one. * * @param other The subscription, or raw subscription, to compare with. */ equals(other: unknown): boolean; } /** * The options to list the subscriptions to a SKU with. * * @remarks * With both `before` and `after`, Discord only respects `before`. */ export interface SubscriptionFetchOptions { /** * How many subscriptions to fetch, up to 100. */ limit?: number; /** * Only the subscriptions of this user. */ user?: UserResolvable; /** * Only the subscriptions before this subscription ID. */ before?: string; /** * Only the subscriptions after this subscription ID. */ after?: string; } /** * Manages the subscriptions to one SKU, reached through `sku.subscriptions` and `client.application.subscriptions`. * * @remarks * Subscriptions are fetched from the API and never cached: nothing keeps a cached subscription up to date for the * bot, unlike entitlements. */ export declare class SubscriptionManager extends BaseManager { /** * The ID of the SKU the subscriptions are to. */ readonly skuId: string; constructor(client: GatewayClient, skuId: string); /** * Resolves a {@link SubscriptionResolvable} to a subscription ID. * * @param subscription The subscription, or its ID. * @returns The ID, or `null` if the value holds none. */ resolveId(subscription: SubscriptionResolvable): string | null; /** * Fetches a subscription to the SKU. * * @param subscription The subscription, or its ID. */ fetch(subscription: SubscriptionResolvable): Promise; /** * Lists the subscriptions to the SKU. * * @param options What to list. */ fetch(options?: SubscriptionFetchOptions): Promise>; private build; } export interface SKU extends StructureMixin {} /** * A premium offer of the application, to subscribe to or to buy: `@discordjs/structures`' `SKU`, with its * subscriptions. */ export declare class SKU extends SKU$1 { /** * @param data The raw SKU. */ constructor(data: APISKU); /** * The flags of the SKU. */ get flags(): Readonly; get createdTimestamp(): number; get createdAt(): Date; /** * The subscriptions to the SKU, fetched from the API and never cached. A manager is built on every access. */ get subscriptions(): SubscriptionManager; /** * The name of the SKU. */ toString(): string; /** * Whether this SKU has the same data as another one. `false` for anything that is neither a SKU nor a raw one. * * @param other The SKU, or raw SKU, to compare with. */ equals(other: unknown): boolean; } /** * A permission of an application command: whether a role, user, or channel may use it. */ export type ApplicationCommandPermissions = APIApplicationCommandPermission; /** * The ID standing for the `@everyone` role in the permissions of a command: the ID of the guild. */ export type RolePermissionConstant = Snowflake; /** * The ID standing for every channel in the permissions of a command: the ID of the guild minus one. */ export type ChannelPermissionConstant = Snowflake; /** * Where an {@link ApplicationCommandPermissionsManager} acts: a guild and a command it is bound to, none of them for * the manager of the application, whose options then have to carry them. */ export interface ApplicationCommandPermissionsScope { guildId?: string | null; commandId?: string | null; } /** * The options every method of the permissions manager takes to say where to act. */ export interface BaseApplicationCommandPermissionsOptions { /** * The guild to modify or check permissions in. Ignored by a manager bound to a guild. */ guild?: GuildResolvable; /** * The command to modify or check permissions of. Ignored by a manager bound to a command. */ command?: ApplicationCommandResolvable; } /** * The options to fetch permissions with. */ export interface FetchApplicationCommandPermissionsOptions extends BaseApplicationCommandPermissionsOptions { /** * Whether to skip the cache and always ask the API, for the permissions of one command. * * @default false */ force?: boolean; } /** * The options to set or add permissions with. * * @remarks * Omitting `command` edits the permissions of the guild, as a whole, when the manager is not bound to a command: they * apply to the commands without permissions of their own. */ export interface ApplicationCommandPermissionsEditOptions extends BaseApplicationCommandPermissionsOptions { /** * The permissions to set, or to add to the existing ones. */ permissions: ApplicationCommandPermissions[]; /** * The OAuth2 bearer token of a user able to manage the guild, with the `applications.commands.permissions.update` * scope: Discord refuses the bot's own token here. */ token: string; } /** * The options to remove permissions with. At least one of `users`, `roles`, and `channels` is required. */ export interface RemoveApplicationCommandPermissionsOptions extends BaseApplicationCommandPermissionsOptions { /** * The OAuth2 bearer token of a user able to manage the guild, with the `applications.commands.permissions.update` * scope. */ token: string; users?: readonly UserResolvable[]; /** * The roles to remove: roles, or IDs, or the ID of the guild for `@everyone`. */ roles?: readonly (RolePermissionConstant | RoleResolvable)[]; /** * The channels to remove: channels, or IDs, or the ID of the guild minus one for every channel. */ channels?: readonly (ChannelPermissionConstant | GuildChannelResolvable)[]; } /** * The options to check for a permission with. */ export interface HasApplicationCommandPermissionsOptions extends BaseApplicationCommandPermissionsOptions { /** * The user, role, channel, or constant to look for. */ permissionId: ApplicationCommandPermissionIdResolvable; /** * Only look for a permission of this type, which tells apart a channel from the `@everyone` role when their IDs * are equal. */ permissionType?: ApplicationCommandPermissionType; } /** * Manages the permissions of application commands, like discord.js's `ApplicationCommandPermissionsManager`. * * @remarks * Reachable from `client.application.commands.permissions` (any guild and command), `guild.commands.permissions` (one * guild) and `command.permissions` (one command): the scope it is bound to decides which of the options' `guild` and * `command` are needed, and are ignored. * * Reads use the bot's authorization, and the `applicationCommandPermissions` cache (kept up to date by * `APPLICATION_COMMAND_PERMISSIONS_UPDATE`) when the client has one. Writes (`set`, `add`, `remove`) cannot use it: * Discord only accepts an OAuth2 bearer token of a user there, passed as the `token` option. Obtaining one is up to * the caller, there is no OAuth2 flow here. */ export declare class ApplicationCommandPermissionsManager extends BaseManager { #private; /** * The ID of the guild this manager acts on, `null` for any. */ readonly guildId: string | null; /** * The ID of the command this manager acts on, `null` for any. */ readonly commandId: string | null; constructor(client: GatewayClient, scope?: ApplicationCommandPermissionsScope); /** * The path of the permissions of a guild's commands, or of one command. * * @param guildId The ID of the guild. * @param commandId The ID of the command. */ permissionsPath(guildId: string, commandId?: string): string; /** * Fetches the permissions of one command, or of every command of a guild. The ID of the application as the command * stands for the permissions of the guild as a whole. * * @remarks * The permissions of one command come from the cache when it has them, unless `force` is set. The API's answer is * written to the cache. * * @param options The guild and command, as far as this manager is not bound to them. * @returns The permissions of the command, or of each command of the guild, by command ID. * @throws {GatewayError} `GlobalCommandPermissions` when no guild is known. */ fetch(options: FetchApplicationCommandPermissionsOptions & { command: ApplicationCommandResolvable; }): Promise; fetch(options?: FetchApplicationCommandPermissionsOptions): Promise>; /** * Sets the permissions of the guild, or of a command, replacing the existing ones. * * @param options The permissions, the bearer token, and the guild and command as far as this manager is not bound to * them. * @returns The permissions as stored. * @throws {GatewayError} `ApplicationCommandPermissionsTokenMissing` without a token, and `GlobalCommandPermissions` * when no guild is known. */ set(options: ApplicationCommandPermissionsEditOptions): Promise; /** * Adds permissions to the existing ones of the guild or a command. A permission for an ID that has one already * replaces it. * * @param options The permissions to add, the bearer token, and the guild and command as far as this manager is not * bound to them. * @returns The permissions as stored. * @throws {GatewayError} `ApplicationCommandPermissionsTokenMissing` without a token, and `GlobalCommandPermissions` * when no guild is known. */ add(options: ApplicationCommandPermissionsEditOptions): Promise; /** * Removes users, roles, and channels from the permissions of the guild or a command. * * @param options Who to remove, the bearer token, and the guild and command as far as this manager is not bound to * them. * @returns The permissions as stored. * @throws {GatewayError} `ApplicationCommandPermissionsTokenMissing` without a token, and `GlobalCommandPermissions` * when no guild is known. */ remove(options: RemoveApplicationCommandPermissionsOptions): Promise; /** * Checks whether a command has a permission for a user, role, channel, or constant. * * @remarks * It reads the permissions like {@link ApplicationCommandPermissionsManager.fetch} does, from the cache when it has * them. Pass `force: true` to {@link ApplicationCommandPermissionsManager.fetch} first for fresher ones. * * @param options The ID to look for, and the guild and command as far as this manager is not bound to them. * @throws {GatewayError} `GlobalCommandPermissions` when no guild is known. */ has(options: HasApplicationCommandPermissionsOptions): Promise; } /** * The options to fetch application commands with. */ export interface FetchApplicationCommandOptions { /** * The ID of the command to fetch. Every command is fetched when omitted. */ id?: string; /** * The ID of the guild to fetch commands of, global commands when omitted. Ignored by the manager of a guild. */ guildId?: string; /** * The locale to localize the names and descriptions of every command for, sent as `X-Discord-Locale`. Not used * when fetching one command. */ locale?: Locale | `${Locale}`; /** * Whether to include the full localization dictionaries, instead of the localized name and description. */ withLocalizations?: boolean; } /** * Manages the application commands of the application, global or of a guild, through the API. * * @remarks * Commands are never cached: Discord sends no event when they change, so a copy could not be kept in sync. Every * method calls the API, and returns new {@link ApplicationCommand} structures. * * `@wolfstar/http-framework` registers the commands of its pieces on its own, with the same bulk overwrite * {@link ApplicationCommandManager.set} sends. Calling `set()` replaces whatever the framework registered, and * nothing here runs by itself: use it to manage commands the framework does not, or instead of it. */ export declare class ApplicationCommandManager extends BaseManager { #private; /** * The ID of the guild this manager acts on, `null` for global commands (and for the guilds of its methods' `guildId` * option). */ readonly guildId: string | null; /** * The manager of the permissions of any command, in any guild (the one of this manager's guild). */ readonly permissions: ApplicationCommandPermissionsManager; /** * @param client The client. * @param guildId The ID of the guild to bind the manager to, see `client.guilds.commands(guildId)` and * `guild.commands`. Global when omitted. */ constructor(client: GatewayClient, guildId?: string | null); /** * The path of the commands, or of one command. * * @param options The ID of the command, and the ID of the guild (ignored by the manager of a guild). */ commandPath({ id, guildId }?: { id?: string; guildId?: string; }): `/${string}`; /** * Resolves a command, or its ID, to its ID. * * @param command The command, a raw one, or its ID. * @returns The ID, `null` if the value holds none. */ resolveId(command: ApplicationCommandResolvable): string | null; /** * Fetches one command, from the API. * * @param id The ID of the command, or the options with it. */ fetch(id: string | (FetchApplicationCommandOptions & { id: string; })): Promise; /** * Fetches every command, from the API. * * @param options The guild (ignored by the manager of a guild), the locale to localize for, and whether to include * the localizations. */ fetch(options?: FetchApplicationCommandOptions & { id?: undefined; }): Promise>; /** * Creates an application command. * * @param command The command: camel-cased data, a raw command, or a builder. * @param guildId The ID of the guild to create it in, global when omitted. Ignored by the manager of a guild. */ create(command: ApplicationCommandDataResolvable, guildId?: string): Promise; /** * Replaces every command of the application, or of a guild, with the given ones: the bulk overwrite. * * @remarks * It deletes the commands that are not among the given ones, including the ones `@wolfstar/http-framework` * registered for its pieces. Use it to manage the commands yourself, not alongside the framework. * * @param commands The commands: camel-cased data, raw commands, or builders. * @param guildId The ID of the guild to set them in, global when omitted. Ignored by the manager of a guild. * @returns The commands as stored, by ID. */ set(commands: readonly ApplicationCommandDataResolvable[], guildId?: string): Promise>; /** * Edits an application command. * * @param command The command, or its ID. * @param data The fields to edit. * @param guildId The ID of the guild it is registered in, global when omitted. Ignored by the manager of a guild. * @throws {GatewayTypeError} `InvalidType` when `command` holds no ID. */ edit(command: ApplicationCommandResolvable, data: Partial, guildId?: string): Promise; /** * Deletes an application command. * * @param command The command, or its ID. * @param guildId The ID of the guild it is registered in, global when omitted. Ignored by the manager of a guild. * @throws {GatewayTypeError} `InvalidType` when `command` holds no ID. */ delete(command: ApplicationCommandResolvable, guildId?: string): Promise; /** * Transforms command data into the payload to send to the API, like discord.js's * `ApplicationCommandManager.transformCommand`. * * @param command The command: camel-cased data, a raw command, or a builder (anything with a `toJSON()`). */ static transformCommand(command: ApplicationCommandDataResolvable): RESTPostAPIApplicationCommandsJSONBody; } /** * A choice of an application command option, as the API returns it. */ export interface ApplicationCommandOptionChoice { name: string; /** * The name in the locale the command was fetched with. */ nameLocalized?: string | null; nameLocalizations?: LocalizationMap | null; value: number | string; } /** * A choice to give an application command option. */ export interface ApplicationCommandOptionChoiceData { name: string; nameLocalizations?: LocalizationMap | null; value: number | string; } interface ApplicationCommandOptionBase { type: ApplicationCommandOptionType; name: string; nameLocalizations?: LocalizationMap | null; description: string; descriptionLocalizations?: LocalizationMap | null; /** * Whether the option is required, `false` unless it is given, and not defined for subcommands (groups). */ required?: boolean; /** * Whether the option is autocompleted, for string, integer, and number options. */ autocomplete?: boolean; choices?: Choice[]; /** * The types of channels that can be picked, for channel options. */ channelTypes?: ChannelType[]; /** * The types of files that can be uploaded, for attachment options. */ fileTypes?: FileUploadType[]; minValue?: number; maxValue?: number; minLength?: number; maxLength?: number; } /** * An option of an application command or subcommand, as the API returns it with camel-cased keys, like discord.js's * `ApplicationCommandOption`. */ export interface ApplicationCommandOption extends ApplicationCommandOptionBase { /** * The name in the locale the command was fetched with. */ nameLocalized?: string; /** * The description in the locale the command was fetched with. */ descriptionLocalized?: string; options?: ApplicationCommandOption[]; } /** * An option to give an application command or subcommand, like discord.js's `ApplicationCommandOptionData`. */ export interface ApplicationCommandOptionData extends ApplicationCommandOptionBase { options?: readonly ApplicationCommandOptionResolvable[]; } /** * An option to give an application command: camel-cased data, or the raw API option a builder produces. */ export type ApplicationCommandOptionResolvable = APIApplicationCommandOption | ApplicationCommandOptionData; /** * The data to create or edit an application command with, like discord.js's `ApplicationCommandData`. */ export interface ApplicationCommandData { /** * The name of the command, in lowercase for chat input commands. */ name: string; nameLocalizations?: LocalizationMap | null; /** * The description of the command, for chat input and primary entry point commands. */ description?: string; descriptionLocalizations?: LocalizationMap | null; /** * Whether the command is age-restricted. */ nsfw?: boolean; /** * The type of the command. * * @default ApplicationCommandType.ChatInput */ type?: ApplicationCommandType; options?: readonly ApplicationCommandOptionResolvable[]; /** * The permissions a member needs by default to run the command, `null` for everyone. */ defaultMemberPermissions?: PermissionResolvable | null; /** * The installation contexts where the command is available, for global commands. */ integrationTypes?: ApplicationIntegrationType[]; /** * The interaction contexts where the command can be used, for global commands. */ contexts?: InteractionContextType[]; /** * Whether the app or Discord handles the interaction, for primary entry point commands. */ handler?: EntryPointCommandHandlerType; } /** * A command of the application, registered globally or in one guild, like discord.js's `ApplicationCommand`. * * @remarks * Application commands are only fetched and edited through the API, never cached: nothing keeps a copy in sync, as * Discord sends no event when they change. `edit()` patches this very structure with the API's answer. */ export declare class ApplicationCommand extends Structure { #private; get id(): string; /** * The ID of the application owning the command. */ get applicationId(): string; /** * The ID of the guild the command is registered in, `null` for a global command. */ get guildId(): string | null; /** * The guild the command is registered in, from the cache. `null` for a global command, or when the guild is not * cached: use {@link ApplicationCommand.fetchGuild} to always get it. */ get guild(): Guild | null; /** * Fetches the guild the command is registered in, cache first. * * @returns The guild, `null` for a global command. */ fetchGuild(): Promise; /** * The manager of this command's permissions: on its guild, or on any guild when the command is global. */ get permissions(): ApplicationCommandPermissionsManager; /** * The manager this command belongs to: the one of its guild, else the application's. */ get manager(): ApplicationCommandManager; get type(): ApplicationCommandType; get name(): string; get nameLocalizations(): LocalizationMap | null; /** * The name in the locale the command was fetched with, `null` if it was not fetched with one. */ get nameLocalized(): string | null; get description(): string; get descriptionLocalizations(): LocalizationMap | null; /** * The description in the locale the command was fetched with, `null` if it was not fetched with one. */ get descriptionLocalized(): string | null; /** * Whether the command is age-restricted. */ get nsfw(): boolean; /** * The options of the command, `null` if it has none. */ get options(): ApplicationCommandOption[] | null; /** * The permissions a member needs by default to run the command, `null` for everyone. */ get defaultMemberPermissions(): Readonly | null; /** * The installation contexts where the command is available, only for global commands. */ get integrationTypes(): ApplicationIntegrationType[] | null; /** * The interaction contexts where the command can be used, only for global commands. */ get contexts(): InteractionContextType[] | null; /** * Whether the app or Discord handles the interaction, only for primary entry point commands. */ get handler(): EntryPointCommandHandlerType | null; /** * The autoincrementing version of the command, updated on substantial changes. */ get version(): string; get createdTimestamp(): number; get createdAt(): Date; /** * Edits the command, and patches this structure with the result. * * @param data The fields to edit. * @returns This command. */ edit(data: Partial): Promise; /** * Edits the name of the command. * * @param name The new name. */ setName(name: string): Promise; /** * Edits the localized names of the command. * * @param nameLocalizations The new localized names, `null` removes them. */ setNameLocalizations(nameLocalizations: LocalizationMap | null): Promise; /** * Edits the description of the command. * * @param description The new description. */ setDescription(description: string): Promise; /** * Edits the localized descriptions of the command. * * @param descriptionLocalizations The new localized descriptions, `null` removes them. */ setDescriptionLocalizations(descriptionLocalizations: LocalizationMap | null): Promise; /** * Edits the permissions a member needs by default to run the command. * * @param defaultMemberPermissions The new permissions, `null` for everyone. */ setDefaultMemberPermissions(defaultMemberPermissions: PermissionResolvable | null): Promise; /** * Edits the options of the command. * * @param options The new options. */ setOptions(options: readonly ApplicationCommandOptionResolvable[]): Promise; /** * Deletes the command. * * @returns This command. */ delete(): Promise; /** * Whether this command equals another one, like discord.js's `ApplicationCommand#equals`. It compares every field * the other command has, so for most uses comparing IDs is faster and enough. `false` for anything that is not a * command, data, or raw command. * * @param command The command, its data, or its raw form, to compare with. * @param enforceOptionOrder Whether options and choices must come in the same order. Discord may not keep the * order they were sent in. */ equals(command: unknown, enforceOptionOrder?: boolean): boolean; /** * Recursively checks that the options of an application command equal the given ones, like discord.js's * `ApplicationCommand.optionsEqual`. For most uses, {@link ApplicationCommand.equals} is better. `false` for * anything that is not a list of options. * * @param existing The options of the existing command, {@link ApplicationCommand.options}. * @param options The options to compare with: camel-cased data or raw options. * @param enforceOptionOrder Whether options and choices must come in the same order. */ static optionsEqual(existing: readonly ApplicationCommandOption[], options: readonly ApplicationCommandOptionResolvable[], enforceOptionOrder?: boolean): boolean; /** * Transforms an option into the camel-cased form {@link ApplicationCommand.options} has, or into the API's, like * discord.js's `ApplicationCommand.transformOption`. * * @param option The option, camel-cased or raw. * @param received Whether to build the camel-cased form of an option received from Discord, rather than the raw one * to send. */ static transformOption(option: ApplicationCommandOption | ApplicationCommandOptionResolvable, received: true): ApplicationCommandOption; static transformOption(option: ApplicationCommandOption | ApplicationCommandOptionResolvable, received?: false): APIApplicationCommandOption; } /** * Named colors accepted by {@link resolveColor}. */ export declare const Colors: { readonly Aqua: 1752220; readonly Blue: 3447003; readonly Blurple: 5793266; readonly DarkAqua: 1146986; readonly DarkBlue: 2123412; readonly DarkButNotBlack: 2895667; readonly DarkerGrey: 8359053; readonly DarkGold: 12745742; readonly DarkGreen: 2067276; readonly DarkGrey: 9936031; readonly DarkNavy: 2899536; readonly DarkOrange: 11027200; readonly DarkPurple: 7419530; readonly DarkRed: 10038562; readonly DarkVividPink: 11342935; readonly Default: 0; readonly Fuchsia: 15418782; readonly Gold: 15844367; readonly Green: 5763719; readonly Grey: 9807270; readonly Greyple: 10070709; readonly LightGrey: 12370112; readonly LuminousVividPink: 15277667; readonly Navy: 3426654; readonly NotQuiteBlack: 2303786; readonly Orange: 15105570; readonly Purple: 10181046; readonly Red: 15548997; readonly White: 16777215; readonly Yellow: 16705372; }; /** * Any thread channel. */ type ThreadChannel = AnnouncementThreadChannel | PrivateThreadChannel | PublicThreadChannel; /** * Any channel that belongs to a guild, threads excluded. Listed rather than derived from {@link AnyChannel}: its * `BaseChannel` fallback would structurally accept DM channels and threads too. */ type NonThreadGuildBasedChannel = AnnouncementChannel | CategoryChannel | ForumChannel | MediaChannel | StageChannel | TextChannel | VoiceChannel; /** * Any channel that belongs to a guild, threads included. */ type GuildBasedChannel = NonThreadGuildBasedChannel | ThreadChannel; /** * Any channel messages can be sent in. */ type TextBasedChannel = AnnouncementChannel | DMChannel | GroupDMChannel | StageChannel | TextChannel | ThreadChannel | VoiceChannel; /** * Any channel of a guild messages can be sent in: {@link TextBasedChannel} without the direct message channels. */ type GuildTextBasedChannel = Exclude; /** * `True` when `Value` is `true`, `False` when it is `false`, and both when it is `boolean`, like discord.js's `If`. */ type If = Value extends true ? TrueResult : Value extends false ? FalseResult : FalseResult | TrueResult; /** * The structures that can be partial, see {@link Partialize}. */ type AllowedPartial = Message; /** * A structure known to be partial, like discord.js's `Partialize`: `partial` is `true`, the nulled keys are `null`, the * nullable ones may be, and the overridable ones may be missing. */ type Partialize = { [K in keyof Omit]: K extends "partial" ? true : K extends NulledKeys ? null : K extends NullableKeys ? Structure[K] | null : Structure[K]; } & { [K in OverridableKeys]: K extends keyof Structure ? Structure[K] : never; }; /** * Any channel members can connect to. */ type VoiceBasedChannel = StageChannel | VoiceChannel; /** * Any guild channel an invite can be created for. */ type GuildInvitableChannel = AnnouncementChannel | ForumChannel | MediaChannel | StageChannel | TextChannel | VoiceChannel; /** * A channel, or its ID. */ type ChannelResolvable = AnyChannel | Snowflake; /** * A guild channel (threads included), or its ID. */ type GuildChannelResolvable = GuildBasedChannel | Snowflake; /** * An announcement channel, or its ID. */ type AnnouncementChannelResolvable = AnnouncementChannel | Snowflake; /** * A category channel, or its ID. */ type CategoryChannelResolvable = CategoryChannel | Snowflake; /** * A stage channel, or its ID. */ type StageChannelResolvable = Snowflake | StageChannel; /** * A text channel, or its ID. */ type TextChannelResolvable = Snowflake | TextChannel; /** * A text or announcement channel, or its ID. */ type GuildTextChannelResolvable = AnnouncementChannel | Snowflake | TextChannel; /** * A channel messages can be sent in, or its ID. */ type TextBasedChannelResolvable = Snowflake | TextBasedChannel; /** * A thread channel, or its ID. */ type ThreadChannelResolvable = Snowflake | ThreadChannel; /** * A voice channel, or its ID. */ type VoiceChannelResolvable = Snowflake | VoiceChannel; /** * A voice or stage channel, or its ID. */ type GuildVoiceChannelResolvable = Snowflake | VoiceBasedChannel; /** * A guild channel an invite can be created for, or its ID. */ type GuildInvitableChannelResolvable = GuildInvitableChannel | Snowflake; /** * A guild, something that belongs to a guild, or the guild's ID. */ type GuildResolvable = Guild | GuildEmoji | GuildInvite | GuildMember | NonThreadGuildBasedChannel | Role | Snowflake; /** * A role, or its ID. */ type RoleResolvable = Role | Snowflake; /** * A ban, or the banned user. */ type GuildBanResolvable = GuildBan | UserResolvable; /** * An audit log event to filter by, or `null` for every event. */ type GuildAuditLogsResolvable = AuditLogEvent | null; /** * A scheduled event, or its ID. */ type GuildScheduledEventResolvable = GuildScheduledEvent | Snowflake; /** * A guild template code or URL. */ type GuildTemplateResolvable = string; /** * An auto moderation rule, or its ID. */ type AutoModerationRuleResolvable = AutoModerationRule | Snowflake; /** * A stage instance, or its ID. */ type StageInstanceResolvable = Snowflake | StageInstance; /** * A sticker, or its ID. */ type StickerResolvable = Snowflake | Sticker; /** * A soundboard sound, or its ID. */ type SoundboardSoundResolvable = Snowflake | SoundboardSound | string; /** * An invite code or URL. */ type InviteResolvable = string; /** * A guild invite code or URL. */ type GuildInviteResolvable = string; /** * A user, something identifying one (a member, a thread member, a message by its author), or the user's ID. */ type UserResolvable = GuildMember | Message | Snowflake | ThreadMember | User; /** * A thread member, or the user it is. */ type ThreadMemberResolvable = ThreadMember | UserResolvable; /** * A presence, or the user it belongs to. */ type PresenceResolvable = Presence | Snowflake | UserResolvable; /** * A permission overwrite, or the data to create one. */ type OverwriteResolvable = OverwriteData | PermissionOverwrites; /** * A permission overwrite, or the role or user it targets. */ type PermissionOverwriteResolvable = PermissionOverwrites | RoleResolvable | UserResolvable; /** * A message, or its ID. */ type MessageResolvable = Message | Snowflake; /** * A reaction, or the ID or identifier of its emoji. */ type MessageReactionResolvable = MessageReaction | Snowflake | string; /** * An emoji structure, or a custom emoji's ID. */ type EmojiResolvable = GuildEmoji | ReactionEmoji | Snowflake; /** * The emoji of a component: a raw one, or a Unicode emoji / custom emoji mention to parse. */ type ComponentEmojiResolvable = APIMessageComponentEmoji | string; /** * A component of a message's action row, raw or serializable (a builder). */ type MessageActionRowComponentResolvable = APIComponentInMessageActionRow | JSONEncodable; /** * An application, an activity of one, or the application's ID. */ type ApplicationResolvable = Activity | APIApplication | Snowflake; /** * An application command, a raw one, or its ID. */ type ApplicationCommandResolvable = APIApplicationCommand | ApplicationCommand | Snowflake; /** * The data to create an application command with: camel-cased data, or raw or serializable (a builder). */ type ApplicationCommandDataResolvable = ApplicationCommandData | JSONEncodable | RESTPostAPIApplicationCommandsJSONBody; /** * Whom an application command permission targets: a channel, a role, or a user. The guild ID stands for `@everyone` * and the guild ID minus one for every channel. */ type ApplicationCommandPermissionIdResolvable = GuildChannelResolvable | RoleResolvable | UserResolvable; /** * The type of an application command option. */ type CommandOptionDataTypeResolvable = ApplicationCommandOptionType; /** * An entitlement, or its ID. */ type EntitlementResolvable = Entitlement | APIEntitlement | Snowflake; /** * A SKU, or its ID. */ type SKUResolvable = SKU | APISKU | Snowflake; /** * A subscription, or its ID. */ type SubscriptionResolvable = Subscription | APISubscription | Snowflake; /** * A `#rrggbb` color string. */ type HexColorString = `#${string}`; /** * A color: a number, a `#rrggbb` string, an RGB tuple, the name of one of the {@link Colors}, or `Random`. */ type ColorResolvable = HexColorString | number | keyof typeof Colors | readonly [red: number, green: number, blue: number] | "Random"; /** * The colors of a role to edit: see {@link RoleColorsResolvable}. */ interface RoleColorsEditResolvable { primaryColor?: ColorResolvable; secondaryColor?: ColorResolvable | null; tertiaryColor?: ColorResolvable | null; } /** * The colors of a role: `primaryColor` alone for a solid color, with `secondaryColor` for a gradient, and with * `tertiaryColor` for the holographic style. */ interface RoleColorsResolvable extends RoleColorsEditResolvable { primaryColor: ColorResolvable; secondaryColor?: ColorResolvable; tertiaryColor?: ColorResolvable; } /** * A date: a `Date`, a timestamp in milliseconds, or a string `Date` can parse. */ type DateResolvable = Date | number | string; /** * Matches the invite URLs Discord hands out, capturing their `code`, like discord.js's `BaseInvite.InvitesPattern`. */ export declare const InvitesPattern: RegExp; /** * Matches guild template URLs, capturing their `code`, like discord.js's `GuildTemplate.GuildTemplatesPattern`. */ export declare const GuildTemplatesPattern: RegExp; /** * Data resolving to a base64 data URI, typically to upload an image: its contents, or the data URI itself. */ export type Base64Resolvable = Uint8Array | ArrayBuffer | string; /** * An image to upload: a data URI, or anything {@link resolveFile} reads (contents, a path, a URL, a stream, a blob). */ export type ImageResolvable = Base64Resolvable | BufferResolvable; /** * The contents of a resolved file, and its content type when known (e.g. from a download's headers). */ export interface ResolvedFile { data: Uint8Array; contentType?: string; } /** * Extracts a code from a string with a pattern capturing it, or returns the string itself when it does not match. * * @param data The string to resolve. * @param pattern The pattern capturing the code as its first group. */ export declare function resolveCode(data: string, pattern: RegExp): string; /** * Resolves an invite URL, or code, to the code. * * @param data The invite resolvable to resolve. */ export declare function resolveInviteCode(data: InviteResolvable): string; /** * Resolves a guild template URL, or code, to the code. * * @param data The template resolvable to resolve. */ export declare function resolveGuildTemplateCode(data: GuildTemplateResolvable): string; /** * Resolves a {@link BufferResolvable} to its contents: reads paths from disk, downloads URLs, and drains streams. * * @remarks * A URL is fetched as is. Sanitize URLs that come from users: fetching them may reach internal services. * @param resource The resource to resolve. * @throws A `GatewayError` when a path is not a file, or a download fails. */ export declare function resolveFile(resource: BufferResolvable): Promise; /** * Resolves contents to a base64 data URI. A string is taken to be one already, and returned as is. * * @param data The contents, or a data URI. * @param contentType The content type of the contents. */ export declare function resolveBase64(data: Base64Resolvable, contentType?: string): string; /** * Resolves an image to the base64 data URI Discord expects for avatars, icons, banners, and the like. Data URIs are * kept; anything else is read with {@link resolveFile}. * * @param image The image, `null` or `undefined` to remove it. * @returns The data URI, `null` when there is no image. */ export declare function resolveImage(image: ImageResolvable | null | undefined): Promise; /** * Resolves an optional image option: `undefined` leaves the image unchanged, `null` removes it, anything else is * resolved with {@link resolveImage}. * * @param image The image option. * @internal */ export declare function resolveImageOption(image: ImageResolvable | null | undefined): Promise; /** * The fields of a soundboard sound that can be edited. */ export interface SoundboardSoundEditOptions { name?: string; /** * The volume, from 0 to 1. */ volume?: number | null; emojiId?: string | null; emojiName?: string | null; reason?: string; } /** * The options to upload a soundboard sound with. */ export interface SoundboardSoundCreateOptions extends SoundboardSoundEditOptions { name: string; /** * The MP3 or OGG sound: a data URI, or anything `resolveFile` reads (contents, a path, a URL, a stream, a blob). */ sound: ImageResolvable; /** * The content type of the sound, `audio/mpeg` or `audio/ogg`, when it cannot be inferred from a download or a blob. */ contentType?: string; } /** * Manages the soundboard sounds of one guild. */ export declare class GuildSoundboardSoundManager extends CachedManager<"soundboardSounds", SoundboardSound, [soundId: string]> { readonly guildId: string; constructor(client: GatewayClient, guildId: string); protected createStructure(data: CacheEntityTypes["soundboardSounds"]): SoundboardSound; keyOf(data: CacheEntityTypes["soundboardSounds"]): string; resolveKey(soundId: string): string; /** * Adds a sound to the cache, and its uploader to `client.users`. * * @internal */ _add(data: CacheEntityTypes["soundboardSounds"], cache?: boolean, options?: AddOptions): Promise; _hydrate(data: CacheEntityTypes["soundboardSounds"]): Awaitable; /** * Fetches every soundboard sound of the guild, and caches them. */ fetchAll(): Promise; /** * Uploads a soundboard sound. * * @param options The sound file, its name, volume, and emoji. */ create(options: SoundboardSoundCreateOptions): Promise; /** * Edits a soundboard sound. * * @param soundId The ID of the sound. * @param options The fields to edit, and the reason for the audit log. */ edit(soundId: string, options: SoundboardSoundEditOptions): Promise; /** * Deletes a soundboard sound. * * @param soundId The ID of the sound. * @param reason The reason for the audit log. */ delete(soundId: string, reason?: string): Promise; protected fetchRaw(soundId: string): Promise; private withGuildId; } /** * The relations of a {@link SoundboardSound}, resolved from the cache by the guild's soundboard manager. */ export interface SoundboardSoundRelations { user?: User | null; guild?: Guild | null; /** * The custom emoji of the sound, when it belongs to the sound's guild and is cached. */ emoji?: GuildEmoji | null; } export interface SoundboardSound extends StructureMixin {} /** * A soundboard sound, one of Discord's defaults or a guild's: `@discordjs/structures`' `SoundboardSound`, with its * uploader, guild, and URL, and actions through the client. */ export declare class SoundboardSound extends SoundboardSound$1 { /** * @param data The raw sound. * @param relations The uploader and guild as resolved from the cache, by the guild's soundboard manager. */ constructor(data: APISoundboardSound, relations?: SoundboardSoundRelations); [kPatch](data: Readonly>): this; /** * The user who uploaded a guild sound, when the payload includes it. */ get user(): User | null; /** * The emoji of the sound, like discord.js's `SoundboardSound#emoji`: the cached custom emoji of the sound's guild, * else the emoji of the payload. `null` when the sound has none. */ get emoji(): GuildEmoji | ReactionEmoji | null; get guild(): Guild | null; /** * The URL of the sound file. */ get url(): string; /** * Whether the sound is partial: built from its IDs alone for an event about an uncached sound, see * `Partials.SoundboardSound`. Only `soundId` and `guildId` are reliable then, and {@link SoundboardSound.fetch} * completes it. */ get partial(): boolean; /** * Fetches the guild sound from the API and patches this structure with the result. */ fetch(): Promise; edit(options: SoundboardSoundEditOptions): Promise; delete(reason?: string): Promise; /** * Whether this sound has the same data as another one, like discord.js's `SoundboardSound#equals`. `false` for * anything that is neither a sound nor a raw one. * * @param other The sound, or raw sound, to compare with. */ equals(other: unknown): boolean; private withGuild; } export interface VoiceChannel extends StructureMixin, ChannelRelations>, MixinTypes, TextChannelMixin, TextGuildChannelMixin, GuildChannelMixin, ChannelParentMixin, ChannelPermissionMixin, ChannelSlowmodeMixin, VoiceChannelMixin, ChannelWebhooksMixin]> {} /** * A guild voice channel. */ export declare class VoiceChannel extends VoiceChannel$1 { /** * @param data The raw channel. * @param relations The guild as resolved from the cache, by `client.channels` or `client.threads`. */ constructor(data: ChannelDataType, relations?: ChannelRelations); /** * The status of the channel, `null` when it has none or it is not known yet. Kept up to date by the * `voiceChannelStatusUpdate` event; `client.channels.requestInfo` asks Discord for it. */ get status(): string | null; /** * When the voice session of the channel started, as a Unix timestamp in milliseconds, `null` when no session is * running or it is not known yet. */ get voiceStartTimestamp(): number | null; /** * When the voice session of the channel started, `null` when no session is running or it is not known yet. */ get voiceStartAt(): Date | null; /** * Sets the status of the channel. Needs the `SetVoiceChannelStatus` permission, plus `ManageChannels` when the bot * is not connected to the channel. The cache is updated by the `VOICE_CHANNEL_STATUS_UPDATE` that follows. * * @param status The status, up to 500 characters, `null` or an empty string to clear it. * @param reason The reason for the audit log. */ setStatus(status: string | null, reason?: string): Promise; /** * Plays a soundboard sound in the channel. The bot must be connected to it. * * @param sound The sound, or its ID with the ID of its guild (none for a default sound). */ sendSoundboardSound(sound: SoundboardSound | { soundId: string; guildId?: string | null; }): Promise; } /** * The options to list the bans of a guild with. `before` and `after` are user IDs. */ export interface GuildBanListOptions { /** * How many bans to fetch, up to 1000. */ limit?: number; before?: string; after?: string; } /** * Manages the bans of one guild. * * @remarks * The gateway does not send ban reasons, so bans cached from `guildBanAdd` have none. `fetch` with `force` gets it. */ export declare class GuildBanManager extends CachedManager<"bans", GuildBan, [userId: string]> { readonly guildId: string; constructor(client: GatewayClient, guildId: string); protected createStructure(data: CacheEntityTypes["bans"]): GuildBan; keyOf(data: CacheEntityTypes["bans"]): string; resolveKey(userId: string): string; /** * Adds a ban to the cache, and its user to `client.users`. * * @internal */ _add(data: CacheEntityTypes["bans"], cache?: boolean, options?: AddOptions): Promise; _hydrate(data: CacheEntityTypes["bans"]): Awaitable; /** * Lists the bans of the guild, paginated by user ID, and caches them. * * @param options How many bans, and around which user ID. */ list(options?: GuildBanListOptions): Promise; /** * Bans a user, member or not. The same as `client.members.ban`. * * @param user The user, or its ID. * @param options The reason, and how many seconds of the user's messages to delete. */ create(user: IdResolvable, options?: BanOptions): Promise; /** * Lifts a ban, and drops it from the cache. * * @param user The user, or its ID. * @param reason The reason for the audit log. */ remove(user: IdResolvable, reason?: string): Promise; /** * Bans up to 200 users at once. * * @param users The users, or their IDs. * @param options The reason, and how many seconds of the users' messages to delete. */ bulkCreate(users: readonly IdResolvable[], options?: BanOptions): Promise<{ bannedUsers: string[]; failedUsers: string[]; }>; protected fetchRaw(userId: string): Promise; private toData; } /** * The relations of an {@link Integration}, resolved from the cache by the guild's integration manager. */ export interface IntegrationRelations { user?: User | null; guild?: Guild | null; role?: Role | null; } /** * An integration of a guild: a bot, a Twitch or YouTube subscription, or a guild subscription. */ export declare class Integration extends Structure { [kRelations]: IntegrationRelations; protected optimizeData(data: Partial): void; /** * @param data The raw integration. * @param relations The user and guild as resolved from the cache, by the guild's integration manager. */ constructor(data: CacheEntityTypes["integrations"], relations?: IntegrationRelations); get id(): string; get guildId(): string; get name(): string; get type(): import("discord-api-types/v10").APIGuildIntegrationType; get enabled(): boolean | null; /** * Whether the integration is syncing. Bot integrations have none. */ get syncing(): boolean | null; /** * The role given to the integration's subscribers. */ get roleId(): string | null; /** * The role given to the integration's subscribers, from the cache, like discord.js's `Integration#role`: `null` * when it has none, when it is not cached, or when the cache is asynchronous. */ get role(): Role | null; [kPatch](data: Readonly>): this; get enableEmoticons(): boolean | null; get expireBehavior(): import("discord-api-types/v10").IntegrationExpireBehavior | null; /** * The grace period, in days, before expiring subscribers. */ get expireGracePeriod(): number | null; /** * The user who added the integration. */ get user(): User | null; /** * The account on the integration's service. */ get account(): import("discord-api-types/v10").APIIntegrationAccount; get syncedTimestamp(): number | null; get syncedAt(): Date | null; get subscriberCount(): number | null; get revoked(): boolean | null; /** * The application of a bot integration. */ get application(): import("discord-api-types/v10").APIGuildIntegrationApplication | null; /** * The OAuth2 scopes the application was authorized with. */ get scopes(): import("discord-api-types/v10").OAuth2Scopes[]; get guild(): Guild | null; /** * Removes the integration from the guild, kicking its bot if it has one. * * @param reason The reason for the audit log. */ delete(reason?: string): Promise; } /** * Manages the integrations of one guild. * * @remarks * Discord has no route to fetch a single integration: `fetch` lists them all, and rejects when the ID is not among * them. */ export declare class GuildIntegrationManager extends CachedManager<"integrations", Integration, [integrationId: string]> { readonly guildId: string; constructor(client: GatewayClient, guildId: string); protected createStructure(data: CacheEntityTypes["integrations"]): Integration; keyOf(data: CacheEntityTypes["integrations"]): string; resolveKey(integrationId: string): string; /** * Adds an integration to the cache, and its user to `client.users`. * * @internal */ _add(data: CacheEntityTypes["integrations"], cache?: boolean, options?: AddOptions): Promise; _hydrate(data: CacheEntityTypes["integrations"]): Awaitable; /** * Fetches every integration of the guild, and caches them. */ fetchAll(): Promise; /** * Removes an integration from the guild, kicking its bot if it has one, and drops it from the cache. * * @param integrationId The ID of the integration. * @param reason The reason for the audit log. */ delete(integrationId: string, reason?: string): Promise; protected fetchRaw(integrationId: string): Promise; private list; } /** * The public preview of a guild, available for discoverable guilds and the ones the bot is in. */ export declare class GuildPreview extends Structure { get id(): string; get name(): string; get icon(): string | null; get splash(): string | null; get discoverySplash(): string | null; get description(): string | null; get features(): import("discord-api-types/v10").GuildFeature[]; get approximateMemberCount(): number; get approximatePresenceCount(): number; get emojis(): GuildEmoji[]; get stickers(): Sticker[]; get createdTimestamp(): number; get createdAt(): Date; iconURL(options?: ImageURLOptions): string | null; splashURL(options?: BaseImageURLOptions): string | null; discoverySplashURL(options?: BaseImageURLOptions): string | null; toString(): string; } /** * The relations of a {@link GuildOnboarding}, shared with its prompts and their options: its guild, and the channels, * roles, and custom emojis its prompts refer to, resolved from the cache by `client.guilds`. */ export interface GuildOnboardingRelations { guild?: Guild | null; channels?: ReadonlyMap; roles?: ReadonlyMap; emojis?: ReadonlyMap; } /** * An answer of an onboarding prompt, with the channels and roles it gives. */ export declare class GuildOnboardingPromptOption extends Structure { [kRelations]: GuildOnboardingRelations; /** * The guild, from the cache, like discord.js's `GuildOnboardingPromptOption#guild`. */ get guild(): Guild | null; /** * The cached channels the option gives access to, by ID, like discord.js's `GuildOnboardingPromptOption#channels`. */ get channels(): Map; /** * The cached roles the option gives, by ID, like discord.js's `GuildOnboardingPromptOption#roles`. */ get roles(): Map; get id(): string; get title(): string; get description(): string | null; get channelIds(): string[]; get roleIds(): string[]; /** * The emoji of the option: the cached custom emoji of the guild, like discord.js, else the payload's. */ get emoji(): GuildEmoji | ReactionEmoji | null; } /** * A question of a guild's onboarding. */ export declare class GuildOnboardingPrompt extends Structure { [kRelations]: GuildOnboardingRelations; /** * The guild, from the cache, like discord.js's `GuildOnboardingPrompt#guild`. */ get guild(): Guild | null; get id(): string; get title(): string; get type(): import("discord-api-types/v10").GuildOnboardingPromptType; get singleSelect(): boolean; get required(): boolean; /** * Whether the prompt is asked during onboarding, rather than only in the channels & roles page. */ get inOnboarding(): boolean; get options(): GuildOnboardingPromptOption[]; } /** * The onboarding of a guild: the prompts new members answer, and the channels they start in. */ export declare class GuildOnboarding extends Structure { [kRelations]: GuildOnboardingRelations; /** * @param data The raw onboarding. * @param relations The guild, as resolved from the cache. */ constructor(data: APIGuildOnboarding, relations?: GuildOnboardingRelations); get guildId(): string; get prompts(): GuildOnboardingPrompt[]; /** * The channels members are in by default. */ get defaultChannelIds(): string[]; /** * The cached channels members are added to by default, by ID, like discord.js's * `GuildOnboarding#defaultChannels`. */ get defaultChannels(): Map; get enabled(): boolean; get mode(): import("discord-api-types/v10").GuildOnboardingMode; get guild(): Guild | null; /** * Edits the onboarding. * * @param options The changes to apply. */ edit(options: GuildOnboardingEditOptions): Promise; } /** * The kind of entity an audit log entry targets, like discord.js's `GuildAuditLogs.Targets`. */ type AuditLogTargetType = "ApplicationCommand" | "AutoModeration" | "Channel" | "Emoji" | "Guild" | "GuildOnboardingPrompt" | "GuildScheduledEvent" | "Integration" | "Invite" | "Message" | "Role" | "SoundboardSound" | "StageInstance" | "Sticker" | "Thread" | "Unknown" | "User" | "Webhook"; /** * The entity an audit log entry targets, like discord.js's `AuditLogEntryTarget`: the cached structure, else a * structure (or an object) built from the entry's changes, at least holding the target's ID. */ type AuditLogEntryTarget = AnyChannel | APIApplicationCommand | AutoModerationRule | Guild | GuildEmoji | GuildInvite | GuildOnboardingPrompt | GuildScheduledEvent | Integration | Role | SoundboardSound | StageInstance | Sticker | User | Webhook | AuditLogPartialTarget; /** * A target known only by the entry: its ID, and the fields the entry changed. */ interface AuditLogPartialTarget { id: string | null; [key: string]: unknown; } /** * Whether an audit log action created, deleted, or updated something, like discord.js's `actionType`. */ export type AuditLogActionType = "Create" | "Delete" | "Update"; /** * The relations of a {@link GuildAuditLogsEntry}: the users of the audit log page, or of the cache. */ export interface GuildAuditLogsEntryRelations { executor?: User | null; guild?: Guild | null; /** * The entity the entry targets, see {@link GuildAuditLogsEntry.target}. */ target?: AuditLogEntryTarget | null; } /** * An entry of a guild's audit log. */ export declare class GuildAuditLogsEntry extends Structure { [kRelations]: GuildAuditLogsEntryRelations; /** * @param data The raw entry, with its guild's ID. * @param relations The executor and guild, resolved by `guild.fetchAuditLogs()` or the event. */ constructor(data: CacheEntityTypes["auditLogEntries"], relations?: GuildAuditLogsEntryRelations); get id(): string; get guildId(): string; get action(): AuditLogEvent; get actionType(): AuditLogActionType; /** * The ID of the user or application that made the change. */ get executorId(): string | null; /** * The ID of the affected entity: a user, role, channel, webhook, ... */ get targetId(): string | null; /** * The kind of entity the entry targets, like discord.js's `GuildAuditLogsEntry#targetType`. */ get targetType(): AuditLogTargetType; /** * The entity the entry targets, like discord.js's `GuildAuditLogsEntry#target`: the cached structure, else one (or * an object) built from the entry's changes, holding at least the target's ID. `null` for users that are not * cached, and for entries without a target. Without a manager, only `{ id }`. */ get target(): AuditLogEntryTarget | null; get reason(): string | null; /** * The changed fields, with their `old` and `new` values, like discord.js's `GuildAuditLogsEntry#changes`. */ get changes(): AuditLogChange[]; /** * The extra details of some actions, e.g. the channel of a message deletion. */ get extra(): import("discord-api-types/v10").APIAuditLogOptions | null; get executor(): User | null; get guild(): Guild | null; get createdTimestamp(): number; get createdAt(): Date; } /** * The raw data of a welcome screen, with the ID of its guild. */ export type WelcomeScreenData = APIGuildWelcomeScreen & { guild_id: string; }; /** * A channel suggested by a welcome screen. */ export interface WelcomeChannel { channelId: string; /** * The channel, from the cache, like discord.js's `WelcomeChannel#channel`: `null` when it is not cached, or when * the welcome screen was not built by `client.guilds`. */ channel: AnyChannel | null; description: string; /** * The emoji shown next to the channel, if any: the cached custom emoji of the guild, else the payload's. */ emoji: GuildEmoji | ReactionEmoji | null; } /** * The relations of a {@link WelcomeScreen}: its guild, and the channels and emojis of its welcome channels, when * cached. */ export interface WelcomeScreenRelations { guild?: Guild | null; /** * The cached channels of the welcome channels, by ID. */ channels?: ReadonlyMap; /** * The cached custom emojis of the welcome channels, by ID. */ emojis?: ReadonlyMap; } /** * The screen new members of a community guild see, suggesting channels to start with. */ export declare class WelcomeScreen extends Structure { [kRelations]: WelcomeScreenRelations; /** * @param data The raw welcome screen. * @param relations The guild, as resolved from the cache. */ constructor(data: WelcomeScreenData, relations?: WelcomeScreenRelations); get guildId(): string; get description(): string | null; get welcomeChannels(): WelcomeChannel[]; get guild(): Guild | null; /** * Whether the welcome screen is shown, from the features of the cached guild; `null` when it is not cached. */ get enabled(): boolean | null; /** * Edits the welcome screen. * * @param options The changes to apply. */ edit(options: GuildWelcomeScreenEditOptions): Promise; } /** * The options of {@link GuildManager.searchMessages}, camel-cased and with the IDs as resolvables. */ interface GuildSearchMessagesOptions { /** * The content to search for, up to 1024 characters. */ content?: string; /** * How many words may be skipped between the matching tokens of `content`, up to 100. Discord defaults to `2`. */ slop?: number; /** * Only the messages after this one. */ minId?: MessageResolvable; /** * Only the messages before this one. */ maxId?: MessageResolvable; /** * Only the messages of these channels (or threads), up to 500. */ channelIds?: readonly ChannelResolvable[]; /** * Only the messages of these author types. Prefix a type with `-` (`MessageSearchAuthorType.NotBot`) to exclude it. */ authorType?: readonly MessageSearchAuthorType[]; /** * Only the messages of these users, up to 100. */ authorIds?: readonly UserResolvable[]; /** * Only the messages mentioning these users, up to 100. */ mentions?: readonly UserResolvable[]; /** * Only the messages mentioning these roles, up to 100. */ mentionsRoleIds?: readonly RoleResolvable[]; /** * Whether the messages mention `@everyone`. */ mentionEveryone?: boolean; /** * Only the messages replying to these users, up to 100. */ repliedToUserIds?: readonly UserResolvable[]; /** * Only the messages replying to these messages, up to 100. */ repliedToMessageIds?: readonly MessageResolvable[]; /** * Whether the messages are pinned. */ pinned?: boolean; /** * Only the messages with these things. Prefix a type with `-` (`MessageSearchHasType.NotImage`) to exclude it. */ has?: readonly MessageSearchHasType[]; /** * Only the messages with these embed types. */ embedType?: readonly MessageSearchEmbedType[]; /** * Only the messages with an embed of these providers (case-sensitive, like `Tenor`), up to 100. */ embedProvider?: readonly string[]; /** * Only the messages linking these hostnames (like `discordapp.com`), up to 100. */ linkHostname?: readonly string[]; /** * Only the messages with an attachment of these filenames, up to 100. */ attachmentFilename?: readonly string[]; /** * Only the messages with an attachment of these extensions (like `txt`), up to 100. */ attachmentExtension?: readonly string[]; /** * What to sort by. Discord defaults to the timestamp. */ sortBy?: MessageSearchSortMode; /** * The direction to sort in, ignored when sorting by relevance. Discord defaults to `"desc"`. */ sortOrder?: "asc" | "desc"; /** * Whether to include the results of age-restricted channels. Discord defaults to `false`. */ includeNsfw?: boolean; /** * How many messages to return, from 1 to 25. Discord defaults to `25`. */ limit?: number; /** * How many messages to skip, up to 9975. */ offset?: number; /** * Whether to write the results to the cache. * * @defaultValue `true` */ cache?: boolean; /** * Whether to wait and retry while Discord indexes the guild, rather than throwing `SearchIndexNotYetAvailable`. * * @defaultValue `true` */ retryOnMissingIndex?: boolean; /** * Aborts the request, and the wait before a retry. */ signal?: AbortSignal; } /** * The result of {@link GuildManager.searchMessages}. */ interface GuildSearchMessagesResult { /** * The matching messages, in the order of the response. */ messages: Collection; /** * The threads holding the messages. */ threads: Collection; /** * The thread members of the threads the bot joined, by thread ID and then user ID. */ threadMembers: Collection>; /** * How many messages match the query. Approximate while messages are created or deleted. */ totalResults: number; /** * Whether the guild is going through a deep historical indexing. */ doingDeepHistoricalIndex: boolean; /** * How many documents the current indexing indexed so far, only when Discord sends it. */ documentsIndexed?: number; } /** * Manages the application commands of one guild, like discord.js's `GuildApplicationCommandManager`: an * {@link ApplicationCommandManager} bound to the guild, whose `guildId` options are ignored. * * @remarks * Reachable from `guild.commands` and `client.guilds.commands(guildId)`, a new instance on every access. */ export declare class GuildApplicationCommandManager extends ApplicationCommandManager { readonly guildId: string; /** * @param client The client. * @param guildId The ID of the guild. */ constructor(client: GatewayClient, guildId: string); } /** * The options to create an invite with. */ export interface InviteCreateOptions { /** * How long the invite lasts, in seconds, up to 7 days. `0` never expires. * * @default 86_400 */ maxAge?: number; /** * How many times the invite can be used, `0` for unlimited. */ maxUses?: number; /** * Whether the invite only grants temporary membership. */ temporary?: boolean; /** * Whether to always create a new invite, instead of reusing a similar one. */ unique?: boolean; targetType?: InviteTargetType; targetUserId?: string; targetApplicationId?: string; reason?: string; } /** * Manages the invites of one guild. */ export declare class GuildInviteManager extends CachedManager<"invites", GuildInvite, [code: string]> { /** * The ID of the guild. */ readonly guildId: string; constructor(client: GatewayClient, guildId: string); protected createStructure(data: CacheEntityTypes["invites"]): GuildInvite; keyOf(data: CacheEntityTypes["invites"]): string; /** * Adds an invite to the cache, and its inviter and target user to `client.users`. * * @internal */ _add(data: CacheEntityTypes["invites"], cache?: boolean, options?: AddOptions): Promise; _hydrate(data: CacheEntityTypes["invites"]): Awaitable; resolveKey(code: string): string; /** * Fetches every invite of the guild, with their metadata, and caches them. */ fetchAll(): Promise; /** * Fetches every invite of a channel of the guild, and caches them. * * @param channelId The ID of the channel. */ fetchChannel(channelId: string): Promise; /** * Creates an invite to a channel of the guild. * * @param channelId The ID of the channel. * @param options The invite's limits and target. */ create(channelId: string, options?: InviteCreateOptions): Promise; /** * Deletes an invite. * * @param code The code of the invite. * @param reason The reason for the audit log. */ delete(code: string, reason?: string): Promise; protected fetchRaw(code: string): Promise; private store; private toCached; } /** * Manages the presences of guild members. * * @remarks * Presences only come from the gateway, with the `GuildPresences` intent: there is no API to fetch them, so `fetch` * rejects on a cache miss. Use `cache.get`, which answers `undefined` instead. * * The cache is keyed by guild and user. `guild.presences` (or `client.guilds.presences(guildId)`) reads it by user * ID alone, like discord.js: `guild.presences.cache.get(userId)`. * * `guild.presences` (or `client.guilds.presences(guildId)`) is this manager built for one guild, like discord.js's: * `cache` takes the user's ID alone, and the methods lose their `guildId` argument. * * @typeParam InGuild Whether the manager was built for one guild. */ export declare class PresenceManager extends CachedManager<"presences", Presence, [guildId: string, userId: string], GuildArgs> { /** * The ID of the guild this manager was built for, `undefined` on `client.presences`. */ readonly guildId: InGuild extends true ? string : undefined; /** * @param client The client. * @param guildId The guild to build the manager for. */ constructor(client: GatewayClient, guildId?: string); protected createStructure(data: CacheEntityTypes["presences"]): Presence; keyOf(data: CacheEntityTypes["presences"]): string; resolveKey(guildId: string, userId: string): string; _hydrate(data: CacheEntityTypes["presences"]): Awaitable; /** * Resolves a {@link PresenceResolvable} to the cached presence of its user in a guild. * * @remarks * A string is a **user ID**, not a cache key: read `guild.presences.cache.get(userId)`, or build the key with * {@link PresenceManager.resolveKey} to read `cache.get` directly. It is a pure cache read, no request is made and * a miss is `null`; presences only come from the gateway. * * The guild comes from a member or a message, else from a thread member's member or thread, and otherwise from * `guildId`. A message sent in a direct message belongs to no guild, so it resolves to `null` unless `guildId` is * given. * * @param presence The presence, something holding a user, or a user ID. * @param guildId The guild to look the presence up in, when the value carries none. * @returns The presence, or `null` if it is not cached or its guild is unknown. */ resolve(presence: PresenceResolvable, guildId?: string): Awaitable; /** * Resolves a {@link PresenceResolvable} to a user ID. * * @remarks * This is the ID of the presence's user, like discord.js, and not the cache key {@link PresenceManager.resolveKey} * builds from a guild and a user. * * @param presence The presence, something holding a user, or a user ID. * @returns The user ID, or `null` if the value holds none. */ resolveId(presence: PresenceResolvable): string | null; private guildOf; /** * Lists the cached presences of a guild. * * @param guildId The ID of the guild. * @returns The cached entries, `[]` when this entity is not cached. * @throws {TypeError} When the store cannot enumerate its entries. */ listCached(...args: GuildArgs): Promise; protected fetchRaw(guildId: string, userId: string): Promise; } /** * Manages the voice states of the members connected to voice channels. * * @remarks * The cache holds them when the bot has the `GuildVoiceStates` intent. `fetch` falls back to the API, which only * knows the voice states of connected members. * * `guild.voiceStates` (or `client.guilds.voiceStates(guildId)`) is this manager built for one guild, like * discord.js's: `cache` takes the user's ID alone, and the methods lose their `guildId` argument. * * @typeParam InGuild Whether the manager was built for one guild. */ export declare class VoiceStateManager extends CachedManager<"voiceStates", VoiceState, [guildId: string, userId: string], GuildArgs> { /** * The ID of the guild this manager was built for, `undefined` on `client.voiceStates`. */ readonly guildId: InGuild extends true ? string : undefined; /** * @param client The client. * @param guildId The guild to build the manager for. */ constructor(client: GatewayClient, guildId?: string); protected createStructure(data: CacheEntityTypes["voiceStates"]): VoiceState; keyOf(data: CacheEntityTypes["voiceStates"]): string; resolveKey(guildId: string, userId: string): string; _hydrate(data: CacheEntityTypes["voiceStates"]): Awaitable; /** * Lists the cached voice states of a guild. * * @param guildId The ID of the guild. * @returns The cached entries, `[]` when this entity is not cached. * @throws {TypeError} When the store cannot enumerate its entries. */ listCached(...args: GuildArgs): Promise; protected fetchRaw(guildId: string, userId: string): Promise<{ channel_id: import("discord-api-types/globals").Snowflake | null; user_id: import("discord-api-types/globals").Snowflake; member?: import("discord-api-types/v10").APIGuildMember; session_id: string; deaf: boolean; mute: boolean; self_deaf: boolean; self_mute: boolean; self_stream?: boolean; self_video: boolean; suppress: boolean; request_to_speak_timestamp: string | null; guild_id: string; }>; } /** * Until when to pause invites and direct messages in a guild, at most 24 hours ahead; `null` resumes them. */ export interface GuildIncidentActionsOptions { invitesDisabledUntil?: Date | number | null; dmsDisabledUntil?: Date | number | null; } /** * The options to fetch a page of a guild's audit log with. */ export interface GuildAuditLogsFetchOptions { /** * Only the entries of this user's actions. */ user?: IdResolvable; /** * Only the entries of this action. */ type?: AuditLogEvent; /** * The entry (or ID) to fetch entries before. */ before?: IdResolvable; after?: IdResolvable; /** * How many entries to fetch, up to 100. */ limit?: number; } /** * A page of a guild's audit log, with the entities its entries refer to. */ export interface GuildAuditLogs { entries: GuildAuditLogsEntry[]; users: User[]; webhooks: Webhook[]; autoModerationRules: AutoModerationRule[]; threads: AnyThreadChannel[]; /** * The integrations the entries refer to, partial: an ID, a name, a type, and an account. */ integrations: Integration[]; applicationCommands: APIApplicationCommand[]; guildScheduledEvents: APIGuildScheduledEvent[]; } /** * A channel to suggest in a welcome screen. */ export interface WelcomeChannelData { channel: IdResolvable; description: string; emoji?: EmojiIdentifierResolvable | null; } /** * The options to edit a welcome screen with. */ export interface GuildWelcomeScreenEditOptions { enabled?: boolean; description?: string | null; welcomeChannels?: readonly WelcomeChannelData[]; reason?: string; } /** * The widget settings of a guild. */ export interface GuildWidgetSettings { enabled: boolean; /** * The channel the widget's invite leads to. */ channelId: string | null; } /** * The options to edit the widget settings of a guild with. */ export interface GuildWidgetSettingsEditOptions { enabled?: boolean; channel?: IdResolvable | null; reason?: string; } /** * An answer of an onboarding prompt. Without an ID, it is a new one. */ export interface GuildOnboardingPromptOptionData { id?: string; title: string; description?: string | null; channels?: readonly IdResolvable[]; roles?: readonly IdResolvable[]; emoji?: EmojiIdentifierResolvable | null; } /** * A question of an onboarding. Without an ID, it is a new one. */ export interface GuildOnboardingPromptData { id?: string; title: string; options: readonly GuildOnboardingPromptOptionData[]; type?: GuildOnboardingPromptType; singleSelect?: boolean; required?: boolean; inOnboarding?: boolean; } /** * The options to edit an onboarding with. The prompts replace every existing one. */ export interface GuildOnboardingEditOptions { prompts?: readonly GuildOnboardingPromptData[]; defaultChannels?: readonly IdResolvable[]; enabled?: boolean; mode?: GuildOnboardingMode; reason?: string; } /** * The options to request the soundboard sounds of guilds over the gateway with. */ export interface GuildSoundboardSoundsRequestOptions { /** * How long to wait for the replies, in milliseconds, before rejecting with a `GuildSoundboardSoundsTimeoutError`. Each * reply restarts it. * * @default 10_000 */ time?: number; } /** * Manages the {@link Guild}s known to the client. */ export declare class GuildManager extends CachedManager<"guilds", Guild, [guildId: string]> { #private; constructor(client: GatewayClient); protected createStructure(data: CacheEntityTypes["guilds"]): Guild; keyOf(data: CacheEntityTypes["guilds"]): string; /** * Builds a guild, resolving its AFK, system, widget, rules, public updates, and safety alerts channels from the * cache. * * @internal */ _hydrate(data: CacheEntityTypes["guilds"]): Awaitable; /** * Gets a guild from the cache without resolving its channels, for the relations of other structures: a message * resolving its guild should not read six more channels. Its channel getters fall back to a synchronous cache. * * @param guildId The ID of the guild. * @internal */ _getShallow(guildId: string): Awaitable; resolveKey(guildId: string): string; /** * Gets the manager of a guild's scheduled events. * * @param guildId The ID of the guild. */ scheduledEvents(guildId: string): GuildScheduledEventManager; /** * Gets the manager of a guild's stage instances. * * @param guildId The ID of the guild. */ stageInstances(guildId: string): StageInstanceManager; /** * Gets the manager of a guild's soundboard sounds. * * @param guildId The ID of the guild. */ soundboardSounds(guildId: string): GuildSoundboardSoundManager; /** * Requests the soundboard sounds of several guilds over the gateway, and caches them. discord.js: * `client.guilds.fetchSoundboardSounds()`. * * @remarks * Discord answers with one `SOUNDBOARD_SOUNDS` dispatch per guild, which also updates the cache and is emitted as * `soundboardSounds`. The guilds are grouped by shard and each shard gets one request, so every shard of the guilds must * be one this client runs. The replies carry no nonce, so a reply resolves every pending request waiting for its guild, * and only the process that sent a request resolves it. A reply arriving after the request timed out is only cached. * * @param guildIds The IDs of the guilds, repeated IDs are requested once. * @param options How long to wait for the replies. * @returns The sounds of each guild, keyed by guild ID in the order of `guildIds` and then by sound ID, once all of them * are cached. */ fetchSoundboardSounds(guildIds: readonly string[], options?: GuildSoundboardSoundsRequestOptions): Promise>>; /** * Hands the cached sounds of a `SOUNDBOARD_SOUNDS` dispatch to the pending requests waiting for their guild, resolving * the ones that now have every guild. * * @internal */ handleSoundboardSounds(sounds: SoundboardSound[], guildId: string): void; /** * Gets the manager of a guild's integrations. * * @param guildId The ID of the guild. */ integrations(guildId: string): GuildIntegrationManager; /** * Fetches the welcome screen of a guild. * * @param guildId The ID of the guild. */ fetchWelcomeScreen(guildId: string): Promise; /** * Edits the welcome screen of a guild. * * @param guildId The ID of the guild. * @param options The changes to apply. */ editWelcomeScreen(guildId: string, options: GuildWelcomeScreenEditOptions): Promise; /** * Fetches whether the widget of a guild is enabled, and its channel. * * @param guildId The ID of the guild. */ fetchWidgetSettings(guildId: string): Promise; /** * Edits the widget settings of a guild, and patches the cached guild. * * @param guildId The ID of the guild. * @param options Whether to enable the widget, and its channel. */ editWidgetSettings(guildId: string, options: GuildWidgetSettingsEditOptions): Promise; /** * Fetches the onboarding of a guild. * * @param guildId The ID of the guild. */ fetchOnboarding(guildId: string): Promise; /** * Edits the onboarding of a guild. * * @param guildId The ID of the guild. * @param options The changes to apply. The prompts replace every existing one. */ editOnboarding(guildId: string, options: GuildOnboardingEditOptions): Promise; /** * Gets the manager of a guild's bans. * * @param guildId The ID of the guild. */ bans(guildId: string): GuildBanManager; /** * Gets the manager of a guild's auto moderation rules. * * @param guildId The ID of the guild. */ autoModerationRules(guildId: string): AutoModerationRuleManager; /** * Fetches a page of a guild's audit log, newest first, and caches its users. * * @param guildId The ID of the guild. * @param options Which user and action to filter by, and the page. */ fetchAuditLogs(guildId: string, options?: GuildAuditLogsFetchOptions): Promise; /** * Searches the messages of a guild. * * @remarks * Needs the `ReadMessageHistory` permission, and the content of the messages is empty without the `MessageContent` * intent. Discord may return fewer messages than `limit`, and `totalResults` is approximate while messages are * created or deleted, so do not paginate on `messages.size`: advance `offset` by `limit` until it passes * `totalResults`. * * While Discord indexes the guild, the search waits the `retry_after` it answers and retries until the index is * ready, so pass a `signal` to bound it, or `retryOnMissingIndex: false` to throw `SearchIndexNotYetAvailable` * instead. Threads of the results are cached before their messages. * * @param guildId The ID of the guild. * @param options What to search for, and how. * @throws {GatewayRangeError} When an option exceeds a limit Discord documents. * @throws {GatewayError} `SearchIndexNotYetAvailable` when the index is not ready and `retryOnMissingIndex` is * `false`, with the `retryAfter` (in seconds) and the `documentsIndexed` Discord answered. */ searchMessages(guildId: string, options?: GuildSearchMessagesOptions): Promise; private searchResult; /** * Gets the manager of a guild's channels. * * @param guildId The ID of the guild. */ channels(guildId: string): GuildChannelManager; /** * Gets the manager of a guild's custom emojis. * * @param guildId The ID of the guild. */ emojis(guildId: string): GuildEmojiManager; /** * Gets the manager of a guild's application commands. * * @param guildId The ID of the guild. */ commands(guildId: string): GuildApplicationCommandManager; /** * Gets the manager of a guild's custom stickers. * * @param guildId The ID of the guild. */ stickers(guildId: string): GuildStickerManager; /** * Gets the manager of a guild's invites. * * @param guildId The ID of the guild. */ invites(guildId: string): GuildInviteManager; /** * Gets the manager of a guild's presences. * * @param guildId The ID of the guild. */ presences(guildId: string): PresenceManager; /** * Gets the manager of a guild's members. * * @param guildId The ID of the guild. */ members(guildId: string): GuildMemberManager; /** * Gets the manager of a guild's roles. * * @param guildId The ID of the guild. */ roles(guildId: string): RoleManager; /** * Gets the manager of a guild's voice states. * * @param guildId The ID of the guild. */ voiceStates(guildId: string): VoiceStateManager; /** * Gets the URL of a guild's widget image. * * @param guild The guild, or anything carrying its ID. * @param style The style of the image. */ widgetImageURL(guild: GuildResolvable, style?: GuildWidgetStyle): string; /** * Lists the guilds the bot is in, as the partial guilds the API returns, paginated by guild ID. * * @param options How many guilds to list (up to 200), around which guild ID, and whether to include counts. */ fetchPartials(options?: { limit?: number; before?: string; after?: string; withCounts?: boolean; }): Promise; /** * Creates a guild owned by the bot, which Discord only allows to bots in fewer than 10 guilds. * * @param options The guild's name and initial setup. */ create(options: RESTPostAPIGuildsJSONBody): Promise; /** * Edits a guild. * * @param guildId The ID of the guild. * @param options The changes to apply. */ edit(guildId: string, options: GuildEditOptions): Promise; /** * Makes the bot leave a guild, and drops it from the cache with everything it scopes. * * @param guildId The ID of the guild. */ leave(guildId: string): Promise; /** * Deletes a guild the bot owns, and drops it from the cache with everything it scopes. * * @param guildId The ID of the guild. */ delete(guildId: string): Promise; /** * Fetches the public preview of a guild. * * @param guildId The ID of the guild. */ fetchPreview(guildId: string): Promise; /** * Fetches the voice regions available to a guild. * * @param guildId The ID of the guild. */ fetchVoiceRegions(guildId: string): Promise; /** * Fetches the vanity invite code of a guild and how many times it was used. * * @param guildId The ID of the guild. */ fetchVanityData(guildId: string): Promise; /** * Pauses invites or direct messages in a guild for up to a day. * * @param guildId The ID of the guild. * @param options Until when to pause each, `null` to resume. */ setIncidentActions(guildId: string, options: GuildIncidentActionsOptions): Promise; protected fetchRaw(guildId: string): Promise; private store; private welcomeScreen; private onboarding; private forget; } /** * The options to create a template with. */ export interface GuildTemplateCreateOptions { name: string; description?: string | null; } /** * The options to edit a template with. */ export interface GuildTemplateEditOptions { name?: string; description?: string | null; } /** * The options to create a guild from a template with. */ export interface GuildTemplateCreateGuildOptions { name: string; /** * The icon: a data URI, or anything `resolveImage` reads. */ icon?: ImageResolvable; } /** * Manages guild templates. Discord does not send them over the gateway, so they are never cached. */ export declare class GuildTemplateManager extends BaseManager { constructor(client: GatewayClient); /** * Fetches a template by its code. * * @param code The code of the template, or its URL. */ fetch(code: string): Promise; /** * Fetches the templates of a guild. * * @param guildId The ID of the guild. */ list(guildId: string): Promise; /** * Creates a template of a guild. * * @param guildId The ID of the guild. * @param options The name and description of the template. */ create(guildId: string, options: GuildTemplateCreateOptions): Promise; /** * Edits a template. * * @param guildId The ID of the template's guild. * @param code The code of the template. * @param options The name and description. */ edit(guildId: string, code: string, options: GuildTemplateEditOptions): Promise; /** * Syncs a template with the current state of its guild. * * @param guildId The ID of the template's guild. * @param code The code of the template. */ sync(guildId: string, code: string): Promise; /** * Deletes a template. * * @param guildId The ID of the template's guild. * @param code The code of the template. */ delete(guildId: string, code: string): Promise; /** * Creates a guild from a template, which Discord only allows to bots in fewer than 10 guilds. * * @param code The code of the template. * @param options The name and icon of the guild. */ createGuild(code: string, options: GuildTemplateCreateGuildOptions): Promise; private build; } /** * The relations of a {@link GuildTemplate}: its source guild, when cached, and its creator. */ export interface GuildTemplateRelations { guild?: Guild | null; creator?: User; } /** * A guild template: a snapshot of a guild's channels, roles, and settings, to create guilds from. */ export declare class GuildTemplate extends Structure { /** * Matches guild template URLs, capturing their `code`, like discord.js's `GuildTemplate.GuildTemplatesPattern`. */ static readonly GuildTemplatesPattern: RegExp; [kRelations]: GuildTemplateRelations; protected optimizeData(data: Partial): void; /** * @param data The raw template. * @param relations The source guild, as resolved from the cache. */ constructor(data: APITemplate, relations?: GuildTemplateRelations); [kPatch](data: Readonly>): this; get code(): string; get name(): string; get description(): string | null; get usageCount(): number; get creatorId(): string; /** * The user who created the template, from the cache, like discord.js, else from the payload. */ get creator(): User; get createdTimestamp(): number; get createdAt(): Date; /** * When the template was last synced with its guild. */ get updatedTimestamp(): number; get updatedAt(): Date; /** * The ID of the guild the template was made from. */ get guildId(): string; /** * The snapshot of the guild the template creates. */ get serializedGuild(): import("discord-api-types/v10").APITemplateSerializedSourceGuild; /** * Whether the guild changed since the template was last synced. */ get unSynced(): boolean | null; get guild(): Guild | null; /** * The URL to create a guild from the template in the Discord app. */ get url(): string; /** * Creates a guild from the template, which Discord only allows to bots in fewer than 10 guilds. * * @param options The name and icon of the guild. */ createGuild(options: GuildTemplateCreateGuildOptions): Promise; /** * Edits the template. * * @param options The name and description. */ edit(options: GuildTemplateEditOptions): Promise; /** * Syncs the template with the current state of its guild. */ sync(): Promise; delete(): Promise; toString(): string; } /** * A member shown by a guild's widget. Its ID is only an index, not the user's: the widget hides who they are. */ export declare class WidgetMember extends Structure { get id(): string; get username(): string; get discriminator(): string; get avatar(): string | null; get avatarURL(): string; get status(): import("discord-api-types/v10").PresenceUpdateReceiveStatus; /** * The name of what the member is playing, if anything. */ get activity(): string | null; } /** * The public widget of a guild: its online members and voice channels. */ export declare class Widget extends Structure { get id(): string; get name(): string; /** * The invite of the widget's channel, if it has one. */ get instantInvite(): string | null; /** * The voice channels everyone can join. */ get channels(): import("discord-api-types/v10").APIGuildWidgetChannel[]; /** * The online members, up to 100. */ get members(): WidgetMember[]; get presenceCount(): number; /** * Gets the URL of the widget's image. * * @param style The style of the image. */ imageURL(style?: GuildWidgetStyle): string; /** * Fetches the current state of the widget. */ fetch(): Promise; } /** * The relations of a {@link Guild}: its special channels, resolved from the cache by `client.guilds`. */ export interface GuildRelations { afkChannel?: AnyChannel | null; systemChannel?: AnyChannel | null; widgetChannel?: AnyChannel | null; rulesChannel?: AnyChannel | null; publicUpdatesChannel?: AnyChannel | null; safetyAlertsChannel?: AnyChannel | null; } /** * The raw field holding the ID of each channel of {@link GuildRelations}. * * @internal */ export declare const GuildChannelFields: { readonly afkChannel: "afk_channel_id"; readonly systemChannel: "system_channel_id"; readonly widgetChannel: "widget_channel_id"; readonly rulesChannel: "rules_channel_id"; readonly publicUpdatesChannel: "public_updates_channel_id"; readonly safetyAlertsChannel: "safety_alerts_channel_id"; }; /** * The options to edit a guild with. Images are data URIs (`data:image/png;base64,...`) or anything `resolveImage` * reads (contents, a path, a URL, a stream, a blob), channels are IDs. */ export interface GuildEditOptions { afkChannel?: string | null; afkTimeout?: RESTPatchAPIGuildJSONBody["afk_timeout"]; banner?: ImageResolvable | null; defaultMessageNotifications?: GuildDefaultMessageNotifications | null; description?: string | null; discoverySplash?: ImageResolvable | null; explicitContentFilter?: GuildExplicitContentFilter | null; features?: APIGuild["features"]; icon?: ImageResolvable | null; name?: string; /** * The ID of the member to transfer the ownership to. */ owner?: string; preferredLocale?: Locale | null; premiumProgressBarEnabled?: boolean; publicUpdatesChannel?: string | null; reason?: string; rulesChannel?: string | null; safetyAlertsChannel?: string | null; splash?: ImageResolvable | null; systemChannel?: string | null; systemChannelFlags?: SystemChannelFlagsResolvable; verificationLevel?: GuildVerificationLevel | null; } /** * A Discord guild. * * @remarks * The collections sent in `GUILD_CREATE` (channels, members, roles, ...) are not kept on the guild: they are stored in * their own entity caches and exposed by the client's managers, e.g. `client.members.fetch(guild.id, userId)`. The * guild-scoped ones discord.js exposes on the guild itself (`emojis`, `stickers`, `invites`) are here too. */ export declare class Guild extends AnonymousGuild { [kRelations]: GuildRelations; /** * @param data The raw guild. * @param relations The channels of the guild, as resolved from the cache by `client.guilds`. */ constructor(data: CacheEntityTypes["guilds"], relations?: GuildRelations); protected optimizeData(data: Partial): void; get ownerId(): string; get discoverySplash(): string | null; get afkChannelId(): string | null; /** * The time, in seconds, before a member is moved to the AFK channel. */ get afkTimeout(): 60 | 300 | 900 | 1800 | 3600; get widgetEnabled(): boolean; get widgetChannelId(): string | null; get verificationLevel(): GuildVerificationLevel; get defaultMessageNotifications(): GuildDefaultMessageNotifications; get explicitContentFilter(): GuildExplicitContentFilter; get mfaLevel(): import("discord-api-types/v10").GuildMFALevel; /** * The ID of the application that created the guild, for bot-created guilds. */ get applicationId(): string | null; get systemChannelId(): string | null; /** * The flags deciding which system messages are suppressed in the system channel. */ get systemChannelFlags(): Readonly; get rulesChannelId(): string | null; get publicUpdatesChannelId(): string | null; get safetyAlertsChannelId(): string | null; /** * The channel members are moved to when idle, from the cache, like discord.js's `Guild#afkChannel`. `null` when * the guild has none, when it is not cached, or when the guild was not built by a manager. */ get afkChannel(): AnyChannel | null; /** * The channel system messages are sent to, from the cache. */ get systemChannel(): AnyChannel | null; /** * The channel the widget's invite leads to, from the cache. */ get widgetChannel(): AnyChannel | null; /** * The rules channel of a community guild, from the cache. */ get rulesChannel(): AnyChannel | null; /** * The channel Discord sends community updates to, from the cache. */ get publicUpdatesChannel(): AnyChannel | null; /** * The channel Discord sends safety alerts to, from the cache. */ get safetyAlertsChannel(): AnyChannel | null; /** * Gets one of the channels of {@link GuildRelations}: the one `client.guilds` resolved, else, for guilds built * without their channels (e.g. `message.guild`), a lookup in a synchronous cache. */ private relatedChannel; /** * Forgets the channels a patch changes. * * @internal */ [kPatchRelations](data: object): void; /** * The maximum number of presences of the guild, `null` for the default limit. */ get maximumPresences(): number | null; get maximumMembers(): number | null; /** * The maximum number of users in a video channel. */ get maxVideoChannelUsers(): number | null; /** * The maximum number of users in a stage video channel. */ get maxStageVideoChannelUsers(): number | null; get nsfwLevel(): import("discord-api-types/v10").GuildNSFWLevel; get premiumTier(): GuildPremiumTier; get premiumProgressBarEnabled(): boolean; get preferredLocale(): Locale; /** * Until when invites or direct messages are paused because of raid activity, as set with `setIncidentActions`. */ get incidentsData(): IncidentActions | null; /** * Whether the guild is considered large by the gateway, `false` if unknown. */ get large(): boolean; /** * The member count, as sent in `GUILD_CREATE` or by the API, or `null` if unknown. */ get memberCount(): number | null; /** * The approximate member count, only present when fetched with counts. */ get approximateMemberCount(): number | null; /** * The approximate number of online members, only present when fetched with counts. */ get approximatePresenceCount(): number | null; /** * The timestamp the client user joined the guild at, as sent in `GUILD_CREATE`, or `null` if unknown. */ get joinedTimestamp(): number | null; get joinedAt(): Date | null; /** * Whether the guild is available, `false` during a Discord outage. */ get available(): boolean; /** * The maximum bitrate, in bits per second, voice channels of the guild can use. */ get maximumBitrate(): number; /** * The maximum bitrate, in bits per second, stage channels of the guild can use. */ get maximumStageBitrate(): number; /** * The custom emojis of the guild. */ get emojis(): GuildEmojiManager; /** * The application commands of the guild. Fetch-only: see `ApplicationCommandManager`. */ get commands(): GuildApplicationCommandManager; /** * The custom stickers of the guild. */ get stickers(): GuildStickerManager; /** * Fetches the active threads of the guild, and caches them. */ fetchActiveThreads(): Promise; /** * Fetches the webhooks of the guild. */ fetchWebhooks(): Promise; /** * The scheduled events of the guild. */ get scheduledEvents(): GuildScheduledEventManager; /** * The live stages of the guild. */ get stageInstances(): StageInstanceManager; /** * The soundboard sounds of the guild. */ get soundboardSounds(): GuildSoundboardSoundManager; /** * The integrations of the guild. */ get integrations(): GuildIntegrationManager; /** * Fetches every integration of the guild. */ fetchIntegrations(): Promise; /** * Fetches the templates of the guild. */ fetchTemplates(): Promise; /** * Creates a template of the guild. * * @param name The name of the template. * @param description The description of the template. */ createTemplate(name: string, description?: string | null): Promise; /** * Fetches the welcome screen of the guild. */ fetchWelcomeScreen(): Promise; /** * Edits the welcome screen of the guild. * * @param options The changes to apply. */ editWelcomeScreen(options: GuildWelcomeScreenEditOptions): Promise; /** * Fetches the public widget of the guild, which must be enabled. */ fetchWidget(): Promise; /** * Fetches whether the widget of the guild is enabled, and its channel. */ fetchWidgetSettings(): Promise; /** * Edits the widget settings of the guild, and patches {@link Guild.widgetEnabled} and * {@link Guild.widgetChannelId} in place. * * @param options Whether to enable the widget, and its channel. */ setWidgetSettings(options: GuildWidgetSettingsEditOptions): Promise; /** * Fetches the onboarding of the guild. */ fetchOnboarding(): Promise; /** * Edits the onboarding of the guild. * * @param options The changes to apply. The prompts replace every existing one. */ editOnboarding(options: GuildOnboardingEditOptions): Promise; /** * The bans of the guild. */ get bans(): GuildBanManager; /** * The auto moderation rules of the guild. */ get autoModerationRules(): AutoModerationRuleManager; /** * Fetches a page of the guild's audit log. * * @param options Which user and action to filter by, and the page. */ fetchAuditLogs(options?: GuildAuditLogsFetchOptions): Promise; /** * Searches the messages of the guild, see `GuildManager#searchMessages`. * * @param options What to search for, and how. */ searchMessages(options?: GuildSearchMessagesOptions): Promise; /** * The channels of the guild. */ get channels(): GuildChannelManager; /** * The invites of the guild. */ get invites(): GuildInviteManager; /** * The presences of the guild: `guild.presences.cache.get(userId)`. */ get presences(): PresenceManager; /** * The members of the guild: `guild.members.cache.get(userId)`. */ get members(): GuildMemberManager; /** * The roles of the guild: `guild.roles.cache.get(roleId)`. */ get roles(): RoleManager; /** * The voice states of the guild: `guild.voiceStates.cache.get(userId)`. */ get voiceStates(): VoiceStateManager; /** * Gets the URL of the guild's discovery splash image, or `null` if it has none. * @param options The image options. */ discoverySplashURL(options?: BaseImageURLOptions): string | null; /** * Fetches this guild from the API, with its approximate counts, and patches it in place. */ fetch(): Promise; /** * Fetches the member owning this guild. */ fetchOwner(): Promise; /** * Requests the members of this guild over the gateway, every one of them by default, and caches them. discord.js: * `guild.members.fetch()`. See `client.members.request`. * * @param options Which members to request. */ requestMembers(options?: GuildMembersRequestOptions): Promise; /** * Requests the ephemeral info (status, start time of the voice session) of the voice channels of this guild over the * gateway, and caches it. discord.js: `guild.fetchChannelInfo()`. See `client.channels.requestInfo`. * * @param options The fields to request. */ requestChannelInfo(options: ChannelInfoRequestOptions): Promise; /** * Fetches every invite of this guild. */ fetchInvites(): Promise; /** * Fetches the public preview of this guild. */ fetchPreview(): Promise; /** * Fetches the voice regions available to this guild. */ fetchVoiceRegions(): Promise; /** * Fetches the vanity URL of this guild, patching {@link AnonymousGuild.vanityURLCode} in place. */ fetchVanityData(): Promise; /** * Edits this guild. * * @param options The changes to apply. */ edit(options: GuildEditOptions): Promise; setName(name: string, reason?: string): Promise; /** * Sets the icon of this guild, `null` to remove it. */ setIcon(icon: ImageResolvable | null, reason?: string): Promise; /** * Sets the banner of this guild, `null` to remove it. */ setBanner(banner: ImageResolvable | null, reason?: string): Promise; /** * Sets the invite splash image of this guild, `null` to remove it. */ setSplash(splash: ImageResolvable | null, reason?: string): Promise; /** * Sets the discovery splash image of this guild, `null` to remove it. */ setDiscoverySplash(discoverySplash: ImageResolvable | null, reason?: string): Promise; setSystemChannel(systemChannel: string | null, reason?: string): Promise; setSystemChannelFlags(systemChannelFlags: SystemChannelFlagsResolvable, reason?: string): Promise; setAFKChannel(afkChannel: string | null, reason?: string): Promise; /** * Sets the AFK timeout of this guild, in seconds. */ setAFKTimeout(afkTimeout: RESTPatchAPIGuildJSONBody["afk_timeout"], reason?: string): Promise; setRulesChannel(rulesChannel: string | null, reason?: string): Promise; setPublicUpdatesChannel(publicUpdatesChannel: string | null, reason?: string): Promise; setSafetyAlertsChannel(safetyAlertsChannel: string | null, reason?: string): Promise; setVerificationLevel(verificationLevel: GuildVerificationLevel | null, reason?: string): Promise; setExplicitContentFilter(explicitContentFilter: GuildExplicitContentFilter | null, reason?: string): Promise; setDefaultMessageNotifications(defaultMessageNotifications: GuildDefaultMessageNotifications | null, reason?: string): Promise; setPreferredLocale(preferredLocale: Locale | null, reason?: string): Promise; setPremiumProgressBarEnabled(enabled?: boolean, reason?: string): Promise; /** * Transfers the ownership of this guild to another member. The client user must own the guild. * * @param owner The ID of the new owner. */ setOwner(owner: string, reason?: string): Promise; /** * Pauses or resumes invites to this guild, through the `INVITES_DISABLED` feature. * * @param disabled Whether to pause invites. */ disableInvites(disabled?: boolean): Promise; /** * Pauses invites or direct messages for up to a day, e.g. during a raid. * * @param options Until when to pause each, `null` to resume. */ setIncidentActions(options: GuildIncidentActionsOptions): Promise; /** * Makes the client user leave this guild. */ leave(): Promise; /** * Deletes this guild. The client user must own it. */ delete(): Promise; /** * Whether this guild has the same data as another one, like discord.js's `Guild#equals`: the same ID, availability, * name, icon, splashes, owner, member count, `large`, verification level, and features, in the same order. `false` * for anything that is not a guild. * * @param guild The guild to compare with. */ equals(guild: unknown): boolean; } /** * The raw data of a channel of type `Type`. Channels sent within a guild payload carry their `guild_id` too. */ export type ChannelDataType = Extract & { guild_id?: Snowflake; }; /** * The relations of a channel, resolved from the cache by `client.channels` and `client.threads`. */ export interface ChannelRelations { guild?: Guild | null; /** * The parent of a guild channel: its category, or the channel a thread belongs to. */ parent?: AnyChannel | null; /** * The user a direct message is with. */ recipient?: User | null; /** * The live stage of a stage channel. */ stageInstance?: StageInstance | null; /** * Whether the bot is a member of a thread, as the thread member cache knows it. */ joined?: boolean; } /** Whether a raw channel type belongs in the thread cache. */ export declare function isThreadChannelType(type: ChannelType): boolean; export interface Channel extends StructureMixin, ChannelRelations>, MixinTypes, [BaseChannelMixin]> {} /** * A channel: `@discordjs/structures`' `Channel`, with what every channel type shares. * * @remarks * Concrete channels (`TextChannel`, `DMChannel`, ...) extend `@discordjs/structures`' own and add their fields through * mixins, following its design. `ChannelManager` picks the right one for a raw channel. * * @typeParam Type The type of the channel. */ export declare class Channel extends Channel$1 { /** * Whether a value is a channel of this package. The concrete channels extend `@discordjs/structures`' own rather than * this class, so `instanceof Channel` matches any `@discordjs/structures` channel carrying {@link StructureMixin}. * Subclasses keep the default `instanceof` behavior. * * @param value The value to check. */ static [Symbol.hasInstance](value: unknown): boolean; /** * @param data The raw channel. * @param relations The guild as resolved from the cache, by `client.channels` or `client.threads`. */ constructor(data: ChannelDataType, relations?: ChannelRelations); } export interface DMChannel extends StructureMixin, ChannelRelations>, MixinTypes, DMChannelMixin, TextChannelMixin]> {} /** * A direct message channel. */ export declare class DMChannel extends DMChannel$1 { /** * @param data The raw channel. * @param relations The guild as resolved from the cache, by `client.channels` or `client.threads`. */ constructor(data: ChannelDataType, relations?: ChannelRelations); /** * Whether the direct message is partial: built from its ID alone for an event in an uncached direct message, see * `Partials.Channel`. Only its ID (and its recipient, when the event carried them) is reliable then, and `fetch()` * completes it. */ get partial(): boolean; /** * The ID of the user the direct message is with, when the payload included them. */ get recipientId(): string | null; /** * The user the direct message is with, like discord.js's `DMChannel#recipient`: the cached user, else the one of the * payload. `null` when the payload did not include them. */ get recipient(): User | null; } export interface User extends StructureMixin {} /** * A Discord user: `@discordjs/structures`' `User`, with CDN URLs and actions through the client. */ export declare class User extends User$1 { /** * @param data The raw user. * @param relations The related structures, resolved from the cache. */ constructor(data: CacheEntityTypes["users"], relations?: object); /** * The user's tag: their username for migrated users, `username#discriminator` for legacy ones. */ get tag(): string; /** * The user's accent color as a `#rrggbb` string, with the same `undefined`/`null` semantics. */ get hexAccentColor(): `#${string}` | null | undefined; /** * The user's avatar decoration, camel-cased like discord.js's `User#avatarDecorationData`. */ get avatarDecorationData(): AvatarDecorationData | null; /** * The user's collectibles, camel-cased like discord.js's `User#collectibles`. */ get collectibles(): Collectibles | null; /** * The guild whose tag the user displays, if any, camel-cased like discord.js's `User#primaryGuild`. */ get primaryGuild(): UserPrimaryGuild | null; /** * The user's public flags (badges). */ get flags(): Readonly; get createdTimestamp(): number; get createdAt(): Date; /** * Gets the URL of the user's avatar, or `null` if they have none. * @param options The image options. */ avatarURL(options?: ImageURLOptions): string | null; /** * The URL of the user's default avatar. */ get defaultAvatarURL(): string; /** * Gets the URL of the user's avatar, falling back to their default avatar. * @param options The image options. */ displayAvatarURL(options?: ImageURLOptions): string; /** * The index of the user's default avatar: migrated users (discriminator `"0"`) derive it from their ID, legacy ones * from their discriminator. */ get defaultAvatarIndex(): number; /** * Gets the URL of the user's avatar decoration, or `null` if they have none. */ avatarDecorationURL(): string | null; /** * Gets the URL of the user's banner: `undefined` when unknown (not fetched), `null` when they have none. * @param options The image options. */ bannerURL(options?: ImageURLOptions): string | null | undefined; /** * Gets the URL of the badge of the guild tag the user displays, or `null` if they display none. * @param options The image options. */ guildTagBadgeURL(options?: BaseImageURLOptions): string | null; /** * The cached direct message channel with the user, see `UserManager#dmChannel`: `null` when there is none, or when * the channel cache cannot be searched. Synchronous when the channel cache is. */ get dmChannel(): Awaitable; /** * Opens a direct message channel with the user, reusing the cached one. * * @param force Whether to skip the cache lookup and always call the API. */ createDM(force?: boolean): Promise; /** * Closes the direct message channel with the user. */ deleteDM(): Promise; /** * Sends a direct message to the user. * * @param options The message, or its content. */ send(options: MessagePayloadResolvable): Promise; /** * Whether the user is partial: built from its ID alone for an event about an uncached user, see `Partials.User`. * Only its ID is reliable then, and {@link User.fetch} completes it. */ get partial(): boolean; /** * Fetches the user from the API and patches this structure with the result. */ fetch(): Promise; /** * Whether this user has the same data as another one, like discord.js's `User#equals`: the same ID, username, * discriminator, global name, avatar, flags, banner, accent color, avatar decoration, nameplate, and primary guild. * * @param user The user to compare with. */ equals(user: User | null | undefined): boolean; toString(): `<@${string}>`; } /** * Converts a camel-cased key to snake case, like lodash's `snakeCase` on the keys discord.js passes it: `byNWeekday` * becomes `by_n_weekday`, and a key already in snake case is kept. * * @param key The key. */ export declare function snakeCase(key: string): string; /** * Transforms camel-cased keys into snake-cased keys, deeply, like discord.js's `toSnakeCase`. Dates are kept, and * anything with a `toJSON` method (a builder, a structure) is replaced by its JSON first. * * @param value The value to transform. */ export declare function toSnakeCase(value: unknown): Value; /** * The settings of an auto moderation rule's trigger, like discord.js's `AutoModerationTriggerMetadata`. */ export interface AutoModerationTriggerMetadata { /** * The substrings searched for in the content. */ keywordFilter: string[]; /** * The regular expressions matched against the content. Only Rust-flavored ones are supported. */ regexPatterns: string[]; /** * The internally pre-defined word sets searched for in the content. */ presets: AutoModerationRuleKeywordPresetType[]; /** * The substrings exempt from triggering the rule. */ allowList: string[]; /** * The total number of role and user mentions a message may have. */ mentionTotalLimit: number | null; /** * Whether mention raids are detected. */ mentionRaidProtectionEnabled: boolean; } /** * The trigger settings to set on an auto moderation rule, like discord.js's `AutoModerationTriggerMetadataOptions`. */ export type AutoModerationTriggerMetadataOptions = Partial; /** * The metadata of an auto moderation action, like discord.js's `AutoModerationActionMetadata`. */ export interface AutoModerationActionMetadata { /** * The ID of the channel content is logged to, for `SendAlertMessage` actions. */ channelId: Snowflake | null; /** * How long the member is timed out for, in seconds, for `Timeout` actions. */ durationSeconds: number | null; /** * The message shown to the member when their message is blocked, for `BlockMessage` actions. */ customMessage: string | null; } /** * An action of an auto moderation rule, like discord.js's `AutoModerationAction`. */ export interface AutoModerationAction { type: AutoModerationActionType; metadata: AutoModerationActionMetadata; } /** * An action to set on an auto moderation rule, like discord.js's `AutoModerationActionOptions`. */ export interface AutoModerationActionOptions { type: AutoModerationActionType; metadata?: { /** * The channel content is logged to, for `SendAlertMessage` actions. */ channel?: IdResolvable; /** * How long the member is timed out for, in seconds, for `Timeout` actions. */ durationSeconds?: number; /** * The message shown to the member when their message is blocked, for `BlockMessage` actions. */ customMessage?: string; }; } /** * Transforms an API auto moderation trigger metadata object to a camel-cased variant. * * @param metadata The metadata to transform. */ export declare function transformAPIAutoModerationRuleTriggerMetadata(metadata: APIAutoModerationRuleTriggerMetadata): AutoModerationTriggerMetadata; /** * Transforms camel-cased auto moderation trigger metadata to the API's shape. Raw metadata is passed through. * * @param metadata The metadata to transform. */ export declare function transformAutoModerationRuleTriggerMetadata(metadata: AutoModerationTriggerMetadataOptions | APIAutoModerationRuleTriggerMetadata): APIAutoModerationRuleTriggerMetadata; /** * Transforms an API auto moderation action to a camel-cased variant, like discord.js's * `_transformAPIAutoModerationAction`. * * @param action The action to transform. */ export declare function transformAPIAutoModerationAction(action: APIAutoModerationAction): AutoModerationAction; /** * Transforms a camel-cased auto moderation action to the API's shape. Raw actions are passed through. * * @param action The action to transform. */ export declare function transformAutoModerationAction(action: AutoModerationActionOptions | AutoModerationAction | APIAutoModerationAction): APIAutoModerationAction; /** * The emoji of a forum tag or a forum's default reaction: its ID for a custom emoji, its name for a unicode one. */ export interface GuildForumTagEmoji { id: Snowflake | null; name: string | null; } /** * A tag of a forum or media channel, like discord.js's `GuildForumTag`. */ export interface GuildForumTag { id: Snowflake; name: string; /** * Whether only moderators can apply the tag. */ moderated: boolean; emoji: GuildForumTagEmoji | null; } /** * A forum tag to set: an existing one (with its ID) or a new one, like discord.js's `GuildForumTagData`. */ export interface GuildForumTagOptions { id?: Snowflake; name: string; moderated?: boolean; emoji?: GuildForumTagEmoji | null; } /** * The default reaction of a forum or media channel, like discord.js's `DefaultReactionEmoji`. */ export type DefaultReactionEmoji = GuildForumTagEmoji; /** * Transforms an API forum tag to a camel-cased variant. * * @param tag The tag to transform. */ export declare function transformAPIGuildForumTag(tag: APIGuildForumTag): GuildForumTag; /** * Transforms a camel-cased forum tag to the API's shape. Raw tags are passed through. * * @param tag The tag to transform. */ export declare function transformGuildForumTag(tag: GuildForumTagOptions | Partial): Partial; /** * Transforms an API forum default reaction to a camel-cased variant. * * @param defaultReaction The default reaction to transform. */ export declare function transformAPIGuildDefaultReaction(defaultReaction: APIGuildForumDefaultReactionEmoji): DefaultReactionEmoji; /** * Transforms a camel-cased forum default reaction to the API's shape. Raw ones are passed through. * * @param defaultReaction The default reaction to transform. */ export declare function transformGuildDefaultReaction(defaultReaction: DefaultReactionEmoji | APIGuildForumDefaultReactionEmoji): APIGuildForumDefaultReactionEmoji; /** * The incident actions of a guild, like discord.js's `IncidentActions`. */ export interface IncidentActions { /** * When invites are enabled again. */ invitesDisabledUntil: Date | null; /** * When direct messages are enabled again. */ dmsDisabledUntil: Date | null; /** * When direct message spam was detected. */ dmSpamDetectedAt: Date | null; /** * When a raid was detected. */ raidDetectedAt: Date | null; } /** * Transforms API incidents data to a camel-cased variant, like discord.js's `_transformAPIIncidentsData`. * * @param data The incidents data to transform. */ export declare function transformAPIIncidentsData(data: APIIncidentsData): IncidentActions; /** * The tags of a role, like discord.js's `RoleTagData`: each is only set when it applies. */ export interface RoleTagData { /** * The ID of the bot the role belongs to. */ botId?: Snowflake; /** * The ID of the integration the role belongs to. */ integrationId?: Snowflake; /** * Whether this is the guild's booster role. */ premiumSubscriberRole?: true; /** * The ID of the role's subscription SKU and listing. */ subscriptionListingId?: Snowflake; /** * Whether the role can be purchased. */ availableForPurchase?: true; /** * Whether this is a linked role of the guild. */ guildConnections?: true; } /** * Transforms API role tags to a camel-cased variant. Discord marks boolean tags as present with `null`, which * becomes `true` here. * * @param tags The tags to transform. */ export declare function transformAPIRoleTags(tags: APIRoleTags): RoleTagData; /** * A change recorded by an audit log entry, like discord.js's `AuditLogChange`. */ export interface AuditLogChange { /** * The property that changed, e.g. `nick`. For application command permission updates, the ID of what was updated. */ key: string; /** * The old value, absent when the property was added. */ old?: unknown; /** * The new value, absent when the property was removed. */ new?: unknown; } /** * Transforms an API audit log change to a camel-cased variant, renaming `old_value` and `new_value`. * * @param change The change to transform. */ export declare function transformAPIAuditLogChange(change: APIAuditLogChange): AuditLogChange; /** * The recurrence rule of a scheduled event, like discord.js's `GuildScheduledEventRecurrenceRule`. */ export interface GuildScheduledEventRecurrenceRule { startTimestamp: number; readonly startAt: Date; endTimestamp: number | null; readonly endAt: Date | null; frequency: GuildScheduledEventRecurrenceRuleFrequency; interval: number; byWeekday: GuildScheduledEventRecurrenceRuleWeekday[] | null; byNWeekday: APIGuildScheduledEventRecurrenceRuleNWeekday[] | null; byMonth: GuildScheduledEventRecurrenceRuleMonth[] | null; byMonthDay: number[] | null; byYearDay: number[] | null; count: number | null; } /** * The recurrence rule to set on a scheduled event, like discord.js's `GuildScheduledEventRecurrenceRuleOptions`. */ export interface GuildScheduledEventRecurrenceRuleOptions { startAt: DateResolvable; frequency: GuildScheduledEventRecurrenceRuleFrequency; interval: number; byWeekday?: readonly GuildScheduledEventRecurrenceRuleWeekday[] | null; byNWeekday?: readonly APIGuildScheduledEventRecurrenceRuleNWeekday[] | null; byMonth?: readonly GuildScheduledEventRecurrenceRuleMonth[] | null; byMonthDay?: readonly number[] | null; } /** * Transforms an API recurrence rule to a camel-cased variant. * * @param rule The rule to transform. */ export declare function transformAPIGuildScheduledEventRecurrenceRule(rule: APIGuildScheduledEventRecurrenceRule): GuildScheduledEventRecurrenceRule; /** * Transforms a camel-cased recurrence rule to the API's shape, like discord.js's * `_transformGuildScheduledEventRecurrenceRule`. Raw rules are passed through. * * @param rule The rule to transform. */ export declare function transformGuildScheduledEventRecurrenceRule(rule: GuildScheduledEventRecurrenceRuleOptions | Partial): Partial; /** * The metadata of a scheduled event, like discord.js's `GuildScheduledEventEntityMetadata`. */ export interface GuildScheduledEventEntityMetadata { /** * Where an external event takes place. */ location: string | null; } /** * Transforms API scheduled event metadata to a camel-cased variant. * * @param metadata The metadata to transform. */ export declare function transformAPIGuildScheduledEventEntityMetadata(metadata: APIGuildScheduledEventEntityMetadata): GuildScheduledEventEntityMetadata; /** * The avatar decoration of a user or member, like discord.js's `AvatarDecorationData`. */ export interface AvatarDecorationData { asset: string; skuId: Snowflake; } /** * Transforms API avatar decoration data to a camel-cased variant. * * @param data The data to transform. */ export declare function transformAPIAvatarDecorationData(data: APIAvatarDecorationData): AvatarDecorationData; /** * The nameplate of a user or member, like discord.js's `NameplateData`. */ export interface NameplateData { skuId: Snowflake; asset: string; label: string; palette: NameplatePalette; } /** * The collectibles of a user or member, like discord.js's `Collectibles`. */ export interface Collectibles { nameplate: NameplateData | null; } /** * Transforms API collectibles to a camel-cased variant, like discord.js's `_transformCollectibles`. * * @param collectibles The collectibles to transform. */ export declare function transformCollectibles(collectibles: APICollectibles): Collectibles; /** * The primary guild of a user, whose tag they display, like discord.js's `UserPrimaryGuild`. */ export interface UserPrimaryGuild { identityGuildId: Snowflake | null; identityEnabled: boolean | null; tag: string | null; badge: string | null; } /** * Transforms an API primary guild to a camel-cased variant. * * @param primaryGuild The primary guild to transform. */ export declare function transformAPIUserPrimaryGuild(primaryGuild: APIUserPrimaryGuild): UserPrimaryGuild; /** * What a message references: the message it replies to or forwards, like discord.js's `MessageReference`. */ export interface MessageReference { channelId: Snowflake; guildId: Snowflake | undefined; messageId: Snowflake | undefined; type: MessageReferenceType; } /** * Transforms an API message reference to a camel-cased variant. * * @param reference The reference to transform. */ export declare function transformAPIMessageReference(reference: APIMessageReference): MessageReference; /** * The Rich Presence activity of a message, like discord.js's `MessageActivity`. */ export interface MessageActivity { partyId: string | undefined; type: MessageActivityType; } /** * Transforms an API message activity to a camel-cased variant. * * @param activity The activity to transform. */ export declare function transformAPIMessageActivity(activity: APIMessageActivity): MessageActivity; /** * The call a message is about, like discord.js's `MessageCall`. */ export interface MessageCall { endedTimestamp: number | null; readonly endedAt: Date | null; participants: Snowflake[]; } /** * Transforms an API message call to a camel-cased variant. * * @param call The call to transform. */ export declare function transformAPIMessageCall(call: APIMessageCall): MessageCall; /** * The role subscription a message is about, like discord.js's `RoleSubscriptionData`. */ export interface RoleSubscriptionData { roleSubscriptionListingId: Snowflake; tierName: string; totalMonthsSubscribed: number; isRenewal: boolean; } /** * Transforms API role subscription data to a camel-cased variant. * * @param data The data to transform. */ export declare function transformAPIRoleSubscriptionData(data: APIMessageRoleSubscriptionData): RoleSubscriptionData; /** * The custom client theme shared via a message, camel-cased like discord.js's `SharedClientTheme`. */ export interface SharedClientTheme { colors: string[]; gradientAngle: number; baseMix: number; baseTheme?: APIMessageSharedClientTheme["base_theme"]; } /** * Transforms the shared client theme of a message. * * @param data The data to transform. */ export declare function transformAPIMessageSharedClientTheme(data: APIMessageSharedClientTheme): SharedClientTheme; /** * A channel a crossposted message was published in, like discord.js's `CrosspostedChannel`. */ export interface CrosspostedChannel { channelId: Snowflake; guildId: Snowflake; type: ChannelType; name: string; } /** * Transforms an API channel mention to a camel-cased variant. * * @param channel The channel mention to transform. */ export declare function transformAPIChannelMention(channel: APIChannelMention): CrosspostedChannel; /** * The metadata of the interaction a message answers, like discord.js's `MessageInteractionMetadata`. */ export interface MessageInteractionMetadata { id: Snowflake; type: InteractionType; /** * The user who triggered the interaction. */ user: User; /** * The IDs of the installation contexts the interaction was authorized for, keyed by their type. */ authorizingIntegrationOwners: APIAuthorizingIntegrationOwnersMap; /** * The ID of the original response, for a follow-up message. */ originalResponseMessageId: Snowflake | null; /** * The ID of the message holding the component that was interacted with. */ interactedMessageId: Snowflake | null; /** * The user a user command targeted. */ targetUser: User | null; /** * The ID of the message a message command targeted. */ targetMessageId: Snowflake | null; /** * The metadata of the interaction that opened the modal, for a modal submission. */ triggeringInteractionMetadata: MessageInteractionMetadata | null; } /** * Transforms API message interaction metadata to a camel-cased variant, like discord.js's * `_transformAPIMessageInteractionMetadata`. Its users are built as {@link User} structures. * * @param metadata The metadata to transform. * @param client The client to bind the users to, the most recently constructed one by default. */ export declare function transformAPIMessageInteractionMetadata(metadata: APIMessageInteractionMetadata, client?: GatewayClient): MessageInteractionMetadata; /** * An image, thumbnail, or video of an embed, like discord.js's `EmbedAssetData`. */ export interface EmbedAssetData { url: string; proxyURL: string | undefined; height: number | undefined; width: number | undefined; } /** * The author of an embed, like discord.js's `EmbedAuthorData`. */ export interface EmbedAuthorData { name: string; url: string | undefined; iconURL: string | undefined; proxyIconURL: string | undefined; } /** * The footer of an embed, like discord.js's `EmbedFooterData`. */ export interface EmbedFooterData { text: string; iconURL: string | undefined; proxyIconURL: string | undefined; } /** * Transforms an API embed image, thumbnail, or video to a camel-cased variant. * * @param asset The asset to transform. */ export declare function transformAPIEmbedAsset(asset: APIEmbedImage | APIEmbedThumbnail | APIEmbedVideo): EmbedAssetData; /** * Transforms an API embed author to a camel-cased variant. * * @param author The author to transform. */ export declare function transformAPIEmbedAuthor(author: APIEmbedAuthor): EmbedAuthorData; /** * Transforms an API embed footer to a camel-cased variant. * * @param footer The footer to transform. */ export declare function transformAPIEmbedFooter(footer: APIEmbedFooter): EmbedFooterData; /** * Something with an ID: a structure, or the ID itself. */ export type IdResolvable = string | { id: string | null; }; /** * Gets the ID of an {@link IdResolvable}. * * @param value The ID, or something with one. */ export declare function resolveId(value: IdResolvable): string; /** * A permission overwrite to set on a channel: whom it targets, and what it allows and denies. */ export interface OverwriteData { /** * The role or member the overwrite targets. */ id: IdResolvable; /** * Whether `id` is a role or a member. Required when `id` is a plain ID. */ type: OverwriteType; allow?: PermissionResolvable; deny?: PermissionResolvable; } /** * Permissions to change in an overwrite: `true` allows, `false` denies, `null` falls back to the role or `@everyone`. */ export type PermissionOverwriteOptions = Partial>; /** * Converts an {@link OverwriteData} to the API's shape. */ export declare function toAPIOverwrite(overwrite: OverwriteData): APIOverwrite; /** * Applies {@link PermissionOverwriteOptions} to an overwrite's allowed and denied permissions. * * @param options The permissions to change. * @param initial The overwrite's current permissions, none by default. */ export declare function resolveOverwriteOptions(options: PermissionOverwriteOptions, initial?: { allow?: bigint; deny?: bigint; }): { allow: bigint; deny: bigint; }; /** * A forum tag to set: an existing one (with its ID) or a new one, camel-cased like discord.js's `GuildForumTagData` * or raw. */ export type GuildForumTagData = GuildForumTagOptions | (Omit & Partial>); /** * The fields of a guild channel that can be edited. Each applies to the channel types that have it. */ export interface GuildChannelEditOptions { name?: string; /** * Converts a text channel to an announcement channel, or back. */ type?: ChannelType.GuildText | ChannelType.GuildAnnouncement; position?: number; topic?: string | null; nsfw?: boolean; rateLimitPerUser?: number; bitrate?: number; userLimit?: number; permissionOverwrites?: readonly OverwriteData[]; /** * The category, `null` to move the channel out of its category. */ parent?: IdResolvable | null; /** * Whether to copy the category's overwrites: the new one with `parent`, else the current one. Exclusive with * `permissionOverwrites`. */ lockPermissions?: boolean; rtcRegion?: string | null; videoQualityMode?: VideoQualityMode; defaultAutoArchiveDuration?: ThreadAutoArchiveDuration; availableTags?: readonly GuildForumTagData[]; /** * The default reaction, camel-cased (`{ id, name }`) or raw. */ defaultReactionEmoji?: DefaultReactionEmoji | APIGuildForumDefaultReactionEmoji | null; defaultThreadRateLimitPerUser?: number; defaultSortOrder?: SortOrderType | null; defaultForumLayout?: ForumLayoutType; flags?: ChannelFlags; /** * Whether a thread is archived. */ archived?: boolean; /** * Whether a thread is locked: only moderators can unarchive it. */ locked?: boolean; /** * Whether non-moderators can add members to a private thread. */ invitable?: boolean; /** * The minutes of inactivity after which a thread is archived. */ autoArchiveDuration?: ThreadAutoArchiveDuration; /** * The IDs of the tags of a thread of a forum or media channel. */ appliedTags?: readonly string[]; reason?: string; } /** * Converts {@link GuildChannelEditOptions} to the API's body, without `lockPermissions` which needs the parent. */ export declare function toChannelBody(options: GuildChannelEditOptions | GuildChannelCreateOptions): RESTPatchAPIChannelJSONBody; /** * The options to create a guild channel with. */ export interface GuildChannelCreateOptions extends Omit { name: string; type?: ChannelType; } export interface AnnouncementChannel extends StructureMixin, ChannelRelations>, MixinTypes, TextChannelMixin, TextGuildChannelMixin, GuildChannelMixin, ChannelParentMixin, ChannelPermissionMixin, ChannelSlowmodeMixin, ChannelTopicMixin, ChannelWebhooksMixin, ChannelThreadsMixin]> {} /** * A guild announcement channel. */ export declare class AnnouncementChannel extends AnnouncementChannel$1 { /** * @param data The raw channel. * @param relations The guild as resolved from the cache, by `client.channels` or `client.threads`. */ constructor(data: ChannelDataType, relations?: ChannelRelations); /** * Makes another channel follow this one: messages published here are crossposted there by a webhook. * * @param channel The channel to post to, or its ID. * @param reason The reason for the audit log. * @returns The ID of the follower webhook created in the target channel. */ addFollower(channel: IdResolvable, reason?: string): Promise; } /** * A channel of a type no other structure covers yet. */ export declare class BaseChannel extends Channel {} /** * Any of the channel structures {@link ChannelManager} builds. */ export type AnyChannel = AnnouncementChannel | AnnouncementThreadChannel | BaseChannel | CategoryChannel | DMChannel | ForumChannel | GroupDMChannel | MediaChannel | PrivateThreadChannel | PublicThreadChannel | StageChannel | TextChannel | VoiceChannel; /** * Builds the channel structure matching the type of a raw channel, {@link BaseChannel} for unknown types. * * @param data The raw channel. */ export declare function createChannel(data: CacheEntityTypes["channels"], relations?: ChannelRelations): AnyChannel; /** * The options to request the ephemeral info of the voice channels of a guild over the gateway with. */ export interface ChannelInfoRequestOptions { /** * The fields to request: `"status"` and `"voice_start_time"` for now. A field Discord does not know is ignored by it. */ fields: readonly (`${GatewayRequestChannelInfoField}` | (string & {}))[]; /** * How long to wait for the reply, in milliseconds, before rejecting with a `GuildChannelInfoTimeoutError`. * * @default 10_000 */ time?: number; } /** * Manages the channels known to the client, threads included. * * @remarks * Threads live in their own entity cache, managed by `client.threads`, which {@link ChannelManager.cache} falls back * to, so a thread ID resolves like any other channel ID. */ export declare class ChannelManager extends CachedManager<"channels", AnyChannel, [channelId: string]> { #private; constructor(client: GatewayClient); protected createCache(): Cache; protected createStructure(data: CacheEntityTypes["channels"]): AnyChannel; keyOf(data: CacheEntityTypes["channels"]): string; _hydrate(data: CacheEntityTypes["channels"]): Awaitable; /** * Builds a channel (or a thread) whose guild is already resolved, resolving its other relations from the cache: its * parent, within the same guild, the recipient of a direct message, the live stage of a stage channel, and whether * the bot joined a thread. Used by * `client.threads` and by the guild's own channel relations, which must not resolve the guild again. * * @param data The raw channel. * @param guild The guild of the channel, `null` outside of guilds or when it is not cached. * @param depth How many parents deep the channel is, which bounds the parent chain (a thread, its channel, and its * category) against a corrupted cache. * @internal */ _hydrateInGuild(data: CacheEntityTypes["channels"], guild: Guild | null, depth?: number): Awaitable; /** * Gets a channel of a guild whose structure is already built, for the guild's own channel relations. * * @param channelId The ID of the channel. * @param guild The guild. * @internal */ _getInGuild(channelId: string, guild: Guild): Awaitable; /** * Finds the cached direct message channel with a user, for `client.users`. * * @remarks * Only a synchronous channel cache that can enumerate its entries is searched: scanning every channel of a remote * store costs more than asking Discord for the channel. * * @param userId The ID of the user. * @returns The channel, `null` when the cache was searched and holds none, `undefined` when it cannot be searched. * @internal */ _findDM(userId: string): Awaitable; /** * Counts the cached channels of a guild, threads excluded, for `GuildChannelManager.channelCountWithoutThreads`. * Synchronous when the channel cache is. * * @param guildId The ID of the guild. * @returns The count, `0` when channels are not cached. * @throws {TypeError} When the store cannot enumerate its entries. * @internal */ _countInGuild(guildId: string): Awaitable; /** * Gets the cached channels of a guild whose category is the given one, for `CategoryChannelChildManager`. * Synchronous when the channel cache is. * * @param guildId The ID of the guild. * @param categoryId The ID of the category. * @returns The channels, none when channels are not cached. * @throws {TypeError} When the store cannot enumerate its entries. * @internal */ _inCategory(guildId: string, categoryId: string): Awaitable; private readRaw; resolveKey(channelId: string): string; /** * Adds a channel to the cache, handing threads to `client.threads`, whose cache holds them. * * @internal */ _add(data: CacheEntityTypes["channels"], cache?: boolean, options?: AddOptions): Promise; /** * Requests the ephemeral info (status, start time of the voice session) of the voice channels of a guild over the * gateway, and caches it. discord.js: `guild.fetchChannelInfo()`. * * @remarks * Discord answers with a `CHANNEL_INFO` dispatch, which also updates the cached channels and is emitted as * `channelInfo`. The reply has no nonce, so requests for the same guild run one after the other. The request is sent * on the guild's shard, which must be one this client runs, and only the process that sent it resolves it. * * Because the reply cannot be matched to a request, a reply arriving after its request timed out resolves the next * request queued for the guild instead, with info that may lack that request's `fields`. Read the cache after such a * timeout, or request the same fields again. * * @param guildId The ID of the guild. * @param options The fields to request. * @returns The cached voice channels of the guild Discord sent info for, once it is cached. */ requestInfo(guildId: string, options: ChannelInfoRequestOptions): Promise; private sendInfoRequest; /** * Resolves the pending request of the guild a cached `CHANNEL_INFO` is for. * * @internal */ handleChannelInfo(channels: VoiceChannel[], data: GatewayChannelInfoDispatchData): void; private settleInfo; /** * Edits a channel. * * @param channelId The ID of the channel. * @param options The fields to edit, and the reason for the audit log. */ edit(channelId: string, options: GuildChannelEditOptions): Promise; /** * Deletes a channel, or closes a direct message, and drops it from the cache with its messages. * * @param channelId The ID of the channel. * @param reason The reason for the audit log. */ delete(channelId: string, reason?: string): Promise; /** * Sends a message to a channel, like discord.js's `ChannelManager#createMessage`. The same as `client.messages.send` * and `channel.send`. * * @param channel The channel, or its ID. * @param options The message, or its content. * @throws {@link GatewayTypeError} `IdUnresolvable` when `channel` holds no ID. */ createMessage(channel: TextBasedChannelResolvable, options: MessagePayloadResolvable): Promise; /** * Gets the permission overwrites of a channel, cache first. * * @param channelId The ID of the channel. */ permissionOverwrites(channelId: string): Promise; protected fetchRaw(channelId: string): Promise; } /** * The options to open a direct message channel with. */ export interface CreateDMOptions { /** * Whether to skip the cache lookup and always call the API. * * @default false */ force?: boolean; /** * Whether to store the channel fetched from the API in the cache. * * @default true */ cache?: boolean; } /** * Manages the {@link User}s known to the client. */ export declare class UserManager extends CachedManager<"users", User, [userId: string]> { constructor(client: GatewayClient); protected createStructure(data: CacheEntityTypes["users"]): User; keyOf(data: CacheEntityTypes["users"]): string; resolveKey(userId: string): string; /** * Resolves a {@link UserResolvable} to a user: the user of a member or a thread member, the author of a message, or * the cached user of an ID. * * @param user The user, something holding one, or an ID. * @returns The user, or `null` if it is not known. */ resolve(user: UserResolvable): Awaitable; /** * Resolves a {@link UserResolvable} to a user ID. * * @param user The user, something holding one, or an ID. * @returns The ID, or `null` if the value holds none. */ resolveId(user: UserResolvable): string | null; /** * Gets a user from the cache, fetching it from the API (and caching it) on a cache miss. * * @param user The user, something holding one, or an ID. * @param options Whether to skip the cache, and whether to store the result. */ fetch(user: UserResolvable, options?: FetchOptions): Promise; /** * Gets the cached direct message channel with a user. * * @remarks * It searches the channel cache, which only a synchronous cache that can enumerate its entries allows: the default * `CollectionCache` and the in-memory stores. Other caches (a Redis store, `cache: null`) answer `null`. * * @param user The user, something holding one, or an ID. * @returns The channel, or `null` when there is none or the cache cannot be searched. */ dmChannel(user: UserResolvable): Awaitable; /** * Opens a direct message channel with a user, and caches it. The cached channel is returned without calling the * API, unless `force` is set. * * @param user The user, something holding one, or an ID. * @param options Whether to skip the cache, and whether to store the result. */ createDM(user: UserResolvable, { cache, force }?: CreateDMOptions): Promise; /** * Closes the direct message channel with a user. * * @remarks * When the channel cache cannot be searched (see {@link UserManager.dmChannel}), whether a channel exists is * unknown: Discord is asked for it first, and nothing is thrown. * * @param user The user, something holding one, or an ID. * @returns The closed channel. * @throws {GatewayError} `UserNoDMChannel` when the cache was searched and holds no channel with the user. */ deleteDM(user: UserResolvable): Promise; /** * Sends a direct message to a user. * * @param user The user, something holding one, or an ID. * @param options The message, or its content. */ send(user: UserResolvable, options: MessagePayloadResolvable): Promise; protected fetchRaw(userId: string): Promise; private requireId; } /** * The relations of an {@link ApplicationEmoji}, resolved from the cache by `client.application.emojis`. */ export interface ApplicationEmojiRelations { author?: User; } /** * A custom emoji owned by the application rather than by a guild, usable by the bot everywhere. Like discord.js's * `ApplicationEmoji`. * * @remarks * Discord sends no event for application emojis, so they are never cached: `client.application.emojis` fetches them * from the API. The payload also carries no `managed`, `requires_colons`, `available` nor `roles`. */ export declare class ApplicationEmoji extends Emoji { /** * @param data The raw emoji. * @param relations The uploader as resolved from the cache, by `client.application.emojis`. */ constructor(data: APIApplicationEmoji, relations?: ApplicationEmojiRelations); [kPatch](data: Readonly>): this; get id(): string; get name(): string; /** * The application that owns the emoji: the application of the client. */ get application(): ClientApplication; /** * The user who uploaded the emoji. The API always sends it for application emojis. */ get author(): User; /** * Fetches the user who uploaded the emoji, from the API. */ fetchAuthor(): Promise; /** * Edits the emoji, and patches this structure with the result. * * @param options The changes to apply. * @returns This emoji. */ edit(options: ApplicationEmojiEditOptions): Promise; /** * Sets the name of the emoji. * * @param name The new name. */ setName(name: string): Promise; /** * Deletes the emoji. * * @returns This emoji. */ delete(): Promise; /** * Whether this emoji has the same data as another one, like discord.js's `ApplicationEmoji#equals`. Against an * application emoji or a raw one, it compares the ID, name, and `animated`: the only fields the API sends, so unlike * `GuildEmoji#equals` there is no `managed`, `available`, `requiresColons` nor roles to compare. `false` for * anything else, including another kind of emoji. * * @param other The application emoji, or raw one, to compare with. */ equals(other: unknown): boolean; } /** * An application emoji, or its ID. */ export type ApplicationEmojiResolvable = ApplicationEmoji | string; /** * The options to create an application emoji with. */ export interface ApplicationEmojiCreateOptions { /** * The image, up to 256 KiB: a data URI (`data:image/png;base64,...`), its contents, a path, a URL, a stream, or a * blob. */ attachment: ImageResolvable; name: string; } /** * The options to edit an application emoji with. */ export interface ApplicationEmojiEditOptions { name?: string; } /** * Manages the emojis of the application, `client.application.emojis`. Discord does not send them over the gateway, so * they are never cached: every method calls the API. */ export declare class ApplicationEmojiManager extends BaseManager { constructor(client: GatewayClient); /** * The ID of the application the emojis belong to. */ get applicationId(): string; /** * Fetches an emoji of the application, or every one of them. * * @param emojiId The ID of the emoji, omit it to fetch them all. * @returns The emoji, or a `Collection` of every emoji by ID. */ fetch(): Promise>; fetch(emojiId: string): Promise; /** * Uploads an emoji. * * @param options The image and name. */ create(options: ApplicationEmojiCreateOptions): Promise; /** * Edits an emoji. * * @param emoji The emoji, or its ID. * @param options The changes to apply. */ edit(emoji: ApplicationEmojiResolvable, options: ApplicationEmojiEditOptions): Promise; /** * Deletes an emoji. * * @param emoji The emoji, or its ID. */ delete(emoji: ApplicationEmojiResolvable): Promise; /** * Fetches the user who uploaded an emoji. * * @param emoji The emoji, or its ID. */ fetchAuthor(emoji: ApplicationEmojiResolvable): Promise; /** * Builds the structure of a raw emoji, resolving its uploader from the cache. * * @param data The raw emoji. */ hydrate(data: APIApplicationEmoji): Promise; } /** * The options to list the entitlements of the application with. * * @remarks * With both `before` and `after`, Discord only respects `before`. */ export interface EntitlementFetchOptions { /** * How many entitlements to fetch, up to 100. */ limit?: number; /** * Only the entitlements of this guild. */ guild?: Guild | string; /** * Only the entitlements of this user. */ user?: UserResolvable; /** * Only the entitlements to these SKUs. */ skus?: readonly SKUResolvable[]; /** * Whether to leave out the entitlements that ended. */ excludeEnded?: boolean; /** * Whether to leave out the entitlements that were deleted. */ excludeDeleted?: boolean; /** * Whether to store the fetched entitlements in the cache. * * @default true */ cache?: boolean; /** * Only the entitlements before this entitlement ID. */ before?: string; /** * Only the entitlements after this entitlement ID. */ after?: string; } /** * The options to create a test entitlement with. It is for a guild or for a user: exactly one of them. */ export interface EntitlementCreateOptions { /** * The SKU to grant. */ sku: SKUResolvable; /** * The guild to grant it to. */ guild?: Guild | string; /** * The user to grant it to. */ user?: UserResolvable; } /** * Manages the entitlements of the application, reached through `client.application.entitlements`: the access users * and guilds were granted to its SKUs. * * @remarks * Entitlements are cached as `ENTITLEMENT_CREATE`, `ENTITLEMENT_UPDATE` and `ENTITLEMENT_DELETE` come in, and as they * are fetched. */ export declare class EntitlementManager extends CachedManager<"entitlements", Entitlement, [entitlementId: string]> { constructor(client: GatewayClient); protected createStructure(data: CacheEntityTypes["entitlements"]): Entitlement; keyOf(data: CacheEntityTypes["entitlements"]): string; resolveKey(entitlementId: string): string; /** * Resolves an {@link EntitlementResolvable} to an entitlement ID. * * @param entitlement The entitlement, or its ID. * @returns The ID, or `null` if the value holds none. */ resolveId(entitlement: EntitlementResolvable): string | null; /** * Gets an entitlement from the cache, fetching it from the API (and caching it) on a cache miss. * * @example * ```typescript * const entitlement = await client.application.entitlements.fetch(entitlementId); * ``` * * @param entitlement The entitlement, or its ID. * @param options Whether to skip the cache, and whether to store the result. */ fetch(entitlement: EntitlementResolvable, options?: FetchOptions): Promise; /** * Lists the entitlements of the application from the API. * * @example * ```typescript * const active = await client.application.entitlements.fetch({ user, excludeEnded: true }); * ``` * * @param options What to list. */ fetch(options?: EntitlementFetchOptions): Promise>; /** * Creates a test entitlement, which grants a user or a guild a SKU without a purchase. * * @remarks * The entitlement is not cached by this call: Discord sends its `ENTITLEMENT_CREATE` too, which does. * * @param options The SKU, and the guild or user to grant it to. * @throws {GatewayTypeError} `InvalidType` for a SKU, guild or user that does not resolve, and * `EntitlementCreateInvalidOwner` unless exactly one of the guild and user is given. */ createTest({ sku, guild, user }: EntitlementCreateOptions): Promise; /** * Deletes a test entitlement, and drops it from the cache. * * @param entitlement The entitlement, or its ID. * @throws {GatewayTypeError} `InvalidType` when the value does not resolve. */ deleteTest(entitlement: EntitlementResolvable): Promise; /** * Marks an entitlement as consumed. Only available for one-time purchase consumable SKUs. * * @param entitlement The entitlement, or its ID. * @throws {GatewayTypeError} `InvalidType` when the value does not resolve. */ consume(entitlement: EntitlementResolvable): Promise; protected fetchRaw(entitlementId: string): Promise; private fetchMany; private requireId; private requireGuildId; private requireUserId; private requireSKUId; } /** * The raw fields of an application: its ID, and any of the others. `READY` only carries the ID and flags, so a * partial application holds just these. */ export type ApplicationData = Pick & Partial>; /** * The public attributes of an application, like discord.js's `Application`. * * @typeParam Data The raw application data this structure wraps. */ export declare class Application extends Structure { get id(): string; /** * The name of the application, or `null` while it is not known. */ get name(): string | null; /** * The description of the application, or `null` if it has none or is not known. */ get description(): string | null; /** * The hash of the application's icon, or `null` if it has none or is not known. */ get icon(): string | null; /** * The hash of the application's cover image, or `null` if it has none or is not known. */ get cover(): string | null; get createdTimestamp(): number; get createdAt(): Date; /** * Gets the URL of the application's icon, or `null` if it has none. * * @param options The image options. */ iconURL(options?: BaseImageURLOptions): string | null; /** * Gets the URL of the application's cover image, or `null` if it has none. * * @param options The image options. */ coverURL(options?: BaseImageURLOptions): string | null; /** * The name of the application, its ID while the name is not known. */ toString(): string; } /** * The relations of a {@link TeamMember}, set by its {@link Team}. */ export interface TeamMemberRelations { team?: Team | null; } /** * A member of a {@link Team}, like discord.js's `TeamMember`. */ export declare class TeamMember extends Structure { #private; [kRelations]: TeamMemberRelations; /** * @param data The raw team member. * @param relations The team the member belongs to, set by the team itself. */ constructor(data: APITeamMember, relations?: TeamMemberRelations); /** * The ID of the member's user. */ get id(): string; /** * The team the member belongs to, or `null` when the member was built by hand. */ get team(): Team | null; /** * The permissions of the member in the team. Discord only ever sends `["*"]`. */ get permissions(): readonly string[]; /** * Whether the member accepted the invite to the team, or is still invited. */ get membershipState(): TeamMemberMembershipState; /** * The role of the member in the team. */ get role(): TeamMemberRole; /** * The user of the member. */ get user(): User; /** * The mention of the member's user. */ toString(): string; } /** * A team of developers owning an application, like discord.js's `Team`. */ export declare class Team extends Structure { #private; get id(): string; get name(): string; /** * The hash of the team's icon, or `null` if it has none. */ get icon(): string | null; /** * The ID of the user owning the team. */ get ownerId(): string; /** * The members of the team, by the ID of their user. */ get members(): Collection; /** * The member owning the team, if it is among {@link Team.members}. */ get owner(): TeamMember | null; get createdTimestamp(): number; get createdAt(): Date; /** * Gets the URL of the team's icon, or `null` if it has none. * * @param options The image options. */ iconURL(options?: BaseImageURLOptions): string | null; toString(): string; } /** * The install parameters of an application: the scopes and permissions it asks for when it is added. */ export interface ApplicationInstallParams { scopes: OAuth2Scopes[]; permissions: Readonly; } /** * The install parameters of an application for each integration type (guild or user install). */ export type ApplicationIntegrationTypesConfig = { [Type in ApplicationIntegrationType]?: { oauth2InstallParams: ApplicationInstallParams | null; }; }; /** * The install parameters to set, with permissions in any form a `PermissionsBitField` resolves. */ export interface ApplicationInstallParamsOptions { scopes: OAuth2Scopes[]; permissions: PermissionResolvable; } /** * The options to edit the application with. * * @remarks * Omitted fields are left unchanged. Images are data URIs (`data:image/png;base64,...`) or anything `resolveImage` * reads (contents, a path, a URL, a stream, a blob), `null` removes them. */ export interface ClientApplicationEditOptions { customInstallURL?: string; description?: string; eventWebhooksURL?: string | null; eventWebhooksStatus?: ApplicationWebhookEventStatus; eventWebhooksTypes?: ApplicationWebhookEventType[]; flags?: ApplicationFlagsResolvable; icon?: ImageResolvable | null; coverImage?: ImageResolvable | null; interactionsEndpointURL?: string | null; roleConnectionsVerificationURL?: string | null; tags?: string[]; installParams?: ApplicationInstallParamsOptions; integrationTypesConfig?: { [Type in ApplicationIntegrationType]?: { oauth2InstallParams?: ApplicationInstallParamsOptions; }; }; } /** * A role connection metadata record of an application, with camelCased fields like discord.js. */ export interface ApplicationRoleConnectionMetadata { name: string; nameLocalizations?: LocalizationMap; description: string; descriptionLocalizations?: LocalizationMap; key: string; type: ApplicationRoleConnectionMetadataType; } /** * The application of the bot, the entry point for everything owned by the application rather than by a guild, like * discord.js's `ClientApplication`. * * @remarks * Unlike discord.js, `client.application` exists from the construction of the client, with only its ID known until * `READY` patches in the flags, and {@link ClientApplication.fetch} the rest: check {@link ClientApplication.partial} * before relying on the other fields. */ export declare class ClientApplication extends Application { #private; /** * Whether only the ID and flags of the application are known: it has neither been fetched nor edited yet. */ get partial(): boolean; /** * The global application commands, and the commands of any guild through their `guildId` option. Fetch-only: see * {@link ApplicationCommandManager}. */ get commands(): ApplicationCommandManager; /** * The flags of the application. */ get flags(): Readonly; /** * The tags describing the application, at most five. */ get tags(): string[]; /** * The scopes and permissions the application asks for when it is added to a guild, or `null` if it sets none. */ get installParams(): ApplicationInstallParams | null; /** * The install parameters of the application for each integration type, or `null` if it sets none. */ get integrationTypesConfig(): ApplicationIntegrationTypesConfig | null; /** * The URL the application is installed through, instead of Discord's own install link. */ get customInstallURL(): string | null; /** * The team owning the application, else the user who does, `null` while it is not known. */ get owner(): Team | User | null; /** * Whether anyone can add the bot to a guild, or `null` if it is not known. */ get botPublic(): boolean | null; /** * Whether the bot only joins guilds after the full OAuth2 code grant flow, or `null` if it is not known. */ get botRequireCodeGrant(): boolean | null; /** * The ID of the guild linked to the application, or `null` if there is none. */ get guildId(): string | null; /** * The guild linked to the application, from the cache. */ get guild(): Guild | null; /** * The approximate number of guilds the bot is in, or `null` if it is not known. */ get approximateGuildCount(): number | null; /** * The approximate number of users who installed the application, or `null` if it is not known. */ get approximateUserInstallCount(): number | null; /** * The URL interactions are sent to, or `null` if there is none. */ get interactionsEndpointURL(): string | null; /** * The URL of the role connections verification, or `null` if there is none. */ get roleConnectionsVerificationURL(): string | null; /** * The URL event webhooks are sent to, or `null` if there is none. */ get eventWebhooksURL(): string | null; /** * Whether event webhooks are enabled, or `null` if it is not known. */ get eventWebhooksStatus(): ApplicationWebhookEventStatus | null; /** * The event types sent to {@link ClientApplication.eventWebhooksURL}, or `null` if it is not known. */ get eventWebhooksTypes(): ApplicationWebhookEventType[] | null; /** * The emojis of the application, fetched from the API: they are not cached. */ get emojis(): ApplicationEmojiManager; /** * The entitlements of the application: the access users and guilds were granted to its SKUs. Cached from the * gateway, like discord.js's `ClientApplication#entitlements`. */ get entitlements(): EntitlementManager; /** * Gets the manager of the subscriptions to a SKU, which never caches them. The same as `sku.subscriptions`, for when * only the ID of the SKU is known. * * @param sku The SKU, or its ID. * @throws {GatewayTypeError} `InvalidType` when the value does not resolve. */ subscriptions(sku: SKUResolvable): SubscriptionManager; /** * Fetches the SKUs of the application, by ID. */ fetchSKUs(): Promise>; /** * Fetches the application from the API, and patches this structure with it. * * @returns This application. */ fetch(): Promise; /** * Edits the application, and patches this structure with the result. * * @param options The fields to edit. * @returns This application. */ edit(options: ClientApplicationEditOptions): Promise; /** * Fetches the role connection metadata records of the application. */ fetchRoleConnectionMetadataRecords(): Promise; /** * Replaces the role connection metadata records of the application. * * @param records The records to set, up to five. Records left out are removed. * @returns The records as stored. */ editRoleConnectionMetadataRecords(records: readonly ApplicationRoleConnectionMetadata[]): Promise; } /** * The presence to set for the bot user. Omitted fields keep their current value. */ export interface PresenceData { status?: PresenceUpdateStatus; afk?: boolean; activities?: GatewayActivityUpdateData[]; /** * The shards to update, every shard by default. */ shardId?: number | readonly number[]; } /** * An activity to set, with its type defaulting to `Playing`. */ export interface ActivityOptions extends Omit { type?: ActivityType; /** * The shards to update, every shard by default. */ shardId?: number | readonly number[]; } /** * The options to edit the bot user with. Images are data URIs (`data:image/png;base64,...`) or anything * `resolveImage` reads (contents, a path, a URL, a stream, a blob), `null` removes them. */ export interface ClientUserEditOptions { username?: string; avatar?: ImageResolvable | null; banner?: ImageResolvable | null; } /** * The bot user, as known to the {@link GatewayClient}: a {@link User} that can edit its profile and presence. */ export declare class ClientUser extends User { #private; /** * Whether the bot's owner account has two-factor authentication enabled. */ get mfaEnabled(): boolean; /** * Whether the bot is verified. */ get verified(): boolean; /** * The presence last set through this structure. */ get presence(): Readonly; /** * Edits the bot user's profile. * * @param options The fields to edit. */ edit(options: ClientUserEditOptions): Promise; setUsername(username: string): Promise; setAvatar(avatar: ImageResolvable | null): Promise; setBanner(banner: ImageResolvable | null): Promise; /** * Sets the bot's presence on its shards. * * @param data The presence to set. */ setPresence(data: PresenceData): Promise>; setStatus(status: PresenceUpdateStatus, shardId?: number | readonly number[]): Promise>; /** * Sets the bot's activity, or clears it when called without a name. * * @param name The activity's name. * @param options The activity's type and other fields. */ setActivity(name?: string, options?: ActivityOptions): Promise>; setAFK(afk?: boolean, shardId?: number | readonly number[]): Promise>; } /** * The data of the dispatch of type `Type`. */ export type DispatchData = Extract["d"]; /** * Describes how a gateway dispatch turns into a {@link GatewayEventMap} event. * * @typeParam Type The dispatch type. * @typeParam Event The event emitted for it. */ export interface DispatchHandler { /** * The event to emit. */ event: Event; /** * Runs before the dispatch is written to the cache, used to read the previous state of the entity. */ before?(client: GatewayClient, data: DispatchData): Promise; /** * Runs after the dispatch is written to the cache, and builds the arguments of the event. * * @param state The value `before` resolved to, if any. */ build(client: GatewayClient, data: DispatchData, state: any, shardId: number): Awaitable; } /** * An event with its arguments, as emitted by a {@link MultiDispatchHandler}. */ export type GatewayEventTuple = { [Event in GatewayEventName]: [event: Event, ...args: GatewayEventMap[Event]]; }[GatewayEventName]; /** * Describes how a gateway dispatch turns into any number of {@link GatewayEventMap} events, e.g. one per emoji a * `GUILD_EMOJIS_UPDATE` changes. */ export interface MultiDispatchHandler { /** * Runs before the dispatch is written to the cache, used to read the previous state. */ before?(client: GatewayClient, data: DispatchData): Promise; /** * Runs after the dispatch is written to the cache, and lists the events to emit, in order. */ emit(client: GatewayClient, data: DispatchData, state: any): Awaitable; } /** * A {@link DispatchHandler} for the dispatch of type `Type`, emitting any event. */ export type AnyDispatchHandler = { [Event in GatewayEventName]: DispatchHandler; }[GatewayEventName]; /** * The table mapping every supported dispatch to its event. * * @remarks * `INTERACTION_CREATE` is deliberately absent: interactions are served by the HTTP endpoint, and the gateway may * deliver some of them as well. Dispatches without an entry are still written to the cache and emitted as `raw`. */ export declare const DispatchHandlers: { [Type in GatewayDispatchEvents]?: AnyDispatchHandler; }; /** * The table of the dispatches that turn into several events, diffed against the cache. * * @remarks * Their aggregate event (e.g. `guildEmojisUpdate`) is always emitted. Without a cache there is nothing to diff * against, so the granular events are not. */ export declare const MultiDispatchHandlers: { [Type in GatewayDispatchEvents]?: MultiDispatchHandler; }; /** Processes one kind of gateway dispatch around the cache write. */ export declare abstract class Action { protected readonly client: GatewayClient; constructor(client: GatewayClient); /** Captures the state required to build the event before the cache changes. */ before(_data: GatewayDispatchPayload["d"]): Promise; /** * Builds and emits events after the cache has been updated. * * @param awaitListeners Waits for the listeners of the events, rejecting when one fails, instead of leaving their * promises to the client's `error` event. Replays use it, as their caller acknowledges the dispatch afterwards. */ abstract handle(data: GatewayDispatchPayload["d"], state: unknown, shardId: number, awaitListeners?: boolean): Promise; protected emit([event, ...args]: GatewayEventTuple, awaitListeners?: boolean): Awaitable; } /** An action producing one public event. */ export declare class DispatchAction extends Action { private readonly handler; constructor(client: GatewayClient, handler: DispatchHandler); before(data: GatewayDispatchPayload["d"]): Promise; handle(data: GatewayDispatchPayload["d"], state: unknown, shardId: number, awaitListeners?: boolean): Promise; } /** An action producing several public events from one dispatch. */ export declare class MultiDispatchAction extends Action { private readonly handler; constructor(client: GatewayClient, handler: MultiDispatchHandler); before(data: GatewayDispatchPayload["d"]): Promise; handle(data: GatewayDispatchPayload["d"], state: unknown, _shardId: number, awaitListeners?: boolean): Promise; } /** Holds one action per handled dispatch, like discord.js's ActionsManager. */ export declare class ActionsManager { #private; constructor(client: GatewayClient); get(event: GatewayDispatchPayload["t"]): Action | undefined; /** The dispatch types that have an action. */ types(): GatewayDispatchPayload["t"][]; } /** * A snapshot of a {@link DispatchQueue}. */ export interface DispatchQueueStats { /** * The dispatches received but not processed yet, across every shard. */ pending: number; /** * The partitions currently holding at least one pending dispatch. */ partitions: number; } /** * Gets the partition a dispatch is processed in: its guild, else its channel (direct messages), else `null`. * * @remarks * A `null` partition is a barrier: the dispatch waits for every pending dispatch of its shard, and every later one * waits for it. `READY`, `RESUMED`, and user-level dispatches such as `USER_UPDATE` are barriers. * * @param payload The dispatch payload. */ export declare function dispatchPartition(payload: GatewayDispatchPayload): string | null; /** * Runs tasks in order within a partition, and partitions of the same shard concurrently. * * @remarks * An asynchronous cache (Redis) would otherwise let a later dispatch of a guild finish before an earlier one. Guilds * are independent, so a slow guild does not hold the others back. Tasks must never reject: the queue has no way to * report their errors. */ export declare class DispatchQueue { #private; /** * Queues a task. * * @param shardId The shard the dispatch was received on. * @param partition The partition from {@link dispatchPartition}, `null` for a barrier. * @param task The task to run once the previous task of its partition is done. * @returns The task's completion. */ enqueue(shardId: number, partition: string | null, task: () => Promise): Promise; /** * Queues a task in a guild's partition, on the shard the guild's dispatches come from: a cache write the client * makes on its own then stays in order with them. Before any dispatch of the guild, there is nothing to order it * with, and it runs on shard 0. * * @param guildId The ID of the guild. * @param task The task to run once the previous task of the guild is done. */ enqueueGuild(guildId: string, task: () => Promise): Promise; /** * Resolves once every task queued so far has run. */ idle(): Promise; /** * A snapshot of the pending work. */ get stats(): DispatchQueueStats; private shard; } /** * The structures a `GatewayClient` builds partially when an event concerns one it has not cached, like discord.js's * `Partials`. Pass them to `GatewayClientOptions.partials`. * * @remarks * Unlike discord.js, events are always emitted, even without the matching partial: an uncached entity is `null` then, * as it always was. With the partial enabled, it is a structure built from the IDs the dispatch carries instead, whose * `partial` is `true`: only its IDs are reliable, and `fetch()` completes it. Partial structures are never written to * the cache. * * `Reaction` and `PollAnswer` are accepted for parity only: the reaction and the poll answer of an uncached message * have always been emitted, and are partial whether or not they are enabled. */ export declare const Partials: { readonly User: 0; readonly Channel: 1; readonly GuildMember: 2; readonly Message: 3; readonly Reaction: 4; readonly GuildScheduledEvent: 5; readonly ThreadMember: 6; readonly Poll: 7; readonly PollAnswer: 8; readonly SoundboardSound: 9; }; /** * One of the {@link Partials}. */ export type Partials = (typeof Partials)[keyof typeof Partials]; /** * The structures held by the caches {@link Sweepers} can sweep, by entity. */ export interface SweepableEntities { autoModerationRules: AutoModerationRule; bans: GuildBan; emojis: GuildEmoji; invites: GuildInvite; members: GuildMember; messages: Message; presences: Presence; stageInstances: StageInstance; stickers: Sticker; threadMembers: ThreadMember; threads: AnyThreadChannel; users: User; voiceStates: VoiceState; } /** * The name of an entity whose cache {@link Sweepers} can sweep. */ export type SweepableEntityName = keyof SweepableEntities; /** * Every {@link SweepableEntityName}. */ export declare const SweepableEntityNames: readonly ["autoModerationRules", "bans", "emojis", "invites", "members", "messages", "presences", "stageInstances", "stickers", "threadMembers", "threads", "users", "voiceStates"]; /** * The entities whose sweeper can be set with a `lifetime` instead of a `filter`. */ export type LifetimeSweepableEntityName = "invites" | "messages" | "threads"; /** * Decides whether a sweep evicts an entry: `true` evicts it. */ export type SweepFilter = (value: Value, key: string, collection: Collection) => boolean; /** * Builds the {@link SweepFilter} of one sweep, called once per sweep so that it can read the clock. Answering `null` * skips the sweep. */ export type SweepFilterFactory = () => SweepFilter | null; /** * Sweeps an entity with a filter, every `interval` seconds. */ export interface SweeperFilterOptions { /** * The seconds between two sweeps. A non-positive or infinite interval does not schedule any. */ interval: number; /** * Builds the filter of each sweep, see {@link SweepFilterFactory}. */ filter: SweepFilterFactory; lifetime?: never; } /** * Sweeps an entity every `interval` seconds, evicting the entries older than `lifetime` seconds. */ export interface SweeperLifetimeOptions { /** * The seconds between two sweeps. A non-positive or infinite interval does not schedule any. */ interval: number; /** * The seconds an entry lives: messages since they were created or last edited, threads since they were archived (an * active thread is never swept), invites since they expired (an invite that never expires is never swept). A * non-positive lifetime skips the sweep. */ lifetime: number; filter?: never; } /** * The sweepers of the client, by entity, see {@link GatewayClientOptions.sweepers}. */ export type SweeperOptions = { [Name in SweepableEntityName]?: Name extends LifetimeSweepableEntityName ? SweeperFilterOptions | SweeperLifetimeOptions : SweeperFilterOptions; }; /** * The options of {@link Sweepers.filterByLifetime}. */ export interface FilterByLifetimeOptions { /** * The seconds an entry lives, a non-positive value skips the sweep. * * @default 14400 */ lifetime?: number; /** * Gets the timestamp the lifetime is counted from, an entry without one is never swept. * * @default (value) => value.createdTimestamp */ getComparisonTimestamp?: (value: Value, key: string, collection: Collection) => number | null | undefined; /** * Whether an entry is never swept. * * @default () => false */ excludeFromSweep?: SweepFilter; } /** * Evicts entries from the caches of instances, on a schedule or on demand, like discord.js's `Sweepers`. * * @remarks * It works with the caches the client builds from {@link GatewayClientOptions.cacheConstructor}, the default * `CollectionCache` included: they are `Map`s. The stores of `@wolfstar/plugin-cache` hold raw data, and expire it * with the `ttl` of their policies instead, so sweeping them throws. * * A sweep only evicts entries from the cache: it emits no event but `cacheSweep`, and the structures the application * keeps stay valid. * * @example * ```typescript * const client = new GatewayClient({ * intents, * sweepers: { * // Every hour, forget the messages not touched for half an hour. * messages: { interval: 3_600, lifetime: 1_800 }, * // Every hour, forget the bots. * users: { interval: 3_600, filter: () => (user) => user.bot }, * }, * }); * * // On demand. * client.sweepers.sweepMessages(600); * ``` */ export declare class Sweepers { #private; /** * The options the sweepers were scheduled from. */ readonly options: SweeperOptions; constructor(client: GatewayClient, options?: SweeperOptions); /** * Evicts the entries of an entity's cache the filter answers `true` for. * * @param entity The name of the entity. * @param filter Builds the filter of the sweep. * @returns The amount of entries evicted, `0` when the filter skips the sweep or the entity is not cached. */ sweep(entity: Name, filter: SweepFilterFactory): number; /** * Evicts the auto moderation rules the filter answers `true` for. */ sweepAutoModerationRules(filter: SweepFilterFactory): number; /** * Evicts the bans the filter answers `true` for. */ sweepBans(filter: SweepFilterFactory): number; /** * Evicts the emojis the filter answers `true` for. */ sweepEmojis(filter: SweepFilterFactory): number; /** * Evicts the invites that expired more than `lifetime` seconds ago. * * @param lifetime The seconds an invite lives past its expiration. */ sweepInvites(lifetime?: number): number; /** * Evicts the members the filter answers `true` for. */ sweepMembers(filter: SweepFilterFactory): number; /** * Evicts the messages created or last edited more than `lifetime` seconds ago. * * @param lifetime The seconds a message lives. */ sweepMessages(lifetime?: number): number; /** * Evicts the presences the filter answers `true` for. */ sweepPresences(filter: SweepFilterFactory): number; /** * Evicts the stage instances the filter answers `true` for. */ sweepStageInstances(filter: SweepFilterFactory): number; /** * Evicts the stickers the filter answers `true` for. */ sweepStickers(filter: SweepFilterFactory): number; /** * Evicts the thread members the filter answers `true` for. */ sweepThreadMembers(filter: SweepFilterFactory): number; /** * Evicts the threads archived more than `lifetime` seconds ago, see {@link Sweepers.outdatedThreadSweepFilter}. * * @param lifetime The seconds a thread lives past its archival. */ sweepThreads(lifetime?: number): number; /** * Evicts the users the filter answers `true` for. */ sweepUsers(filter: SweepFilterFactory): number; /** * Evicts the voice states the filter answers `true` for. */ sweepVoiceStates(filter: SweepFilterFactory): number; /** * Stops the scheduled sweeps. On-demand sweeps keep working. */ destroy(): void; /** * Builds a filter factory evicting the entries older than a lifetime, for {@link Sweepers.sweep} and the `filter` * of a sweeper. * * @param options The lifetime, and what it is counted from. */ static filterByLifetime(options?: FilterByLifetimeOptions): SweepFilterFactory; /** * Builds a filter factory evicting the archived threads that have been so for longer than a lifetime. Active * threads are never evicted. * * @param lifetime The seconds a thread lives past its archival. * @default 14400 */ static outdatedThreadSweepFilter(lifetime?: number): SweepFilterFactory; } export interface GatewayClientOptions extends ClientOptions, GatewayClientMessageDefaults { /** * The gateway intents to identify with, e.g. `GatewayIntentBits.Guilds | GatewayIntentBits.GuildMessages`. */ intents: GatewayIntentBits | number; /** * The total number of shards across every process, `null` to use the amount recommended by Discord. * * @default null */ shardCount?: number | null; /** * The IDs of the shards this client manages, `null` to manage all of them. * * @default null */ shardIds?: number[] | ShardRange | null; /** * Builds the cache of each entity, the one its managers expose as `manager.cache`: the `cacheConstructor` of the * discord.js RFC #11426. The caches hold structure instances, which dispatches patch in place. * * @remarks * The class is instantiated once per entity with `(creator, name, options)`, see {@link CacheConstructor}: * `options` carries `keyOf`, the key of raw data, which `add` must use since most entities are not keyed by their * `id`, `refresh`, to call on what `get` and `add` hand out so that relations are resolved again, and the entity's * {@link GatewayClientOptions.cacheOptions}. Extending {@link CollectionCache} is the recommended way. * * A cache that is not a `Map` cannot be enumerated: the dispatch cascades (`GUILD_DELETE`, `CHANNEL_DELETE`), the * reconciliation on `READY`, the emoji and sticker diff events, and `listCached` do not work with it. * * It cannot be combined with {@link GatewayClientOptions.cache} or {@link GatewayClientOptions.makeCache}, which * back the managers with raw `@wolfstar/plugin-cache` stores instead: passing both throws. `cache: null` wins over * it: nothing is cached, and the class is never instantiated. * * The structures of a cache of instances are built synchronously, so the caches their relations are read from * must be synchronous too. * * @default CollectionCache */ cacheConstructor?: CacheConstructor; /** * The options of the cache of each entity, passed to {@link GatewayClientOptions.cacheConstructor} (the default * `CollectionCache` included) next to `keyOf` and `refresh`. `maxSize` bounds the amount of entries of an entity, * the oldest one being evicted first. * * @remarks * By default every received entity stays in memory until a dispatch removes it: this is what bounds it, next to * {@link GatewayClientOptions.policies} and `cache: null`. * * It only applies to caches built by a constructor. Like `cacheConstructor`, it cannot be combined with * {@link GatewayClientOptions.cache} or {@link GatewayClientOptions.makeCache}, whose stores have their own * bounds: passing both throws. With `cache: null` it is ignored. * * @example * ```typescript * // Keep the 1000 most recent messages, and no presence. * const client = new GatewayClient({ * intents, * cacheOptions: { messages: { maxSize: 1_000 }, presences: { maxSize: 0 } }, * }); * ``` * * @default undefined */ cacheOptions?: Partial>; /** * Evicts entries from the caches of instances on a schedule, like discord.js's `sweepers` option: each entity has * its own sweeper, evicting what a `filter` selects or what outlived a `lifetime`, every `interval` seconds. See * {@link Sweepers}, whose methods sweep on demand, and {@link DefaultSweeperSettings}. * * @remarks * The timers do not keep the process alive, and stop on {@link GatewayClient.destroy}. A sweep that throws (e.g. a * filter) is reported through `cacheError`, and the next one runs as scheduled. * * It only applies to caches built by a constructor, the default included: like `cacheConstructor`, combining it with * {@link GatewayClientOptions.cache} or {@link GatewayClientOptions.makeCache} throws, their stores expire entries * with the `ttl` of {@link GatewayClientOptions.policies}. With `cache: null` it is ignored. * * @example * ```typescript * sweepers: { * messages: { interval: 3_600, lifetime: 1_800 }, * users: { interval: 3_600, filter: () => (user) => user.bot }, * } * ``` * * @default undefined */ sweepers?: SweeperOptions; /** * A `@wolfstar/plugin-cache` cache (in memory or Redis) whose raw stores back the managers, instead of the * in-memory caches of instances built by {@link GatewayClientOptions.cacheConstructor}: structures are then built * on every read. `null` disables caching: the managers' `cache.get` always answer `undefined`, update events * receive `null` as their previous state, and `fetch` always hits the API. * * @remarks * Every entity cache is optional: an entity kind the cache does not hold is simply not cached, see * `createInMemoryCache`'s `entities` option. * * @default undefined */ cache?: Cache$1 | null; /** * Creates the raw `@wolfstar/plugin-cache` store of each entity kind, `null` or `undefined` not to cache it. Called * once per entity kind when the client is constructed, and takes precedence over * {@link GatewayClientOptions.cache}. Not to be confused with {@link GatewayClientOptions.cacheConstructor}, which * builds caches of structure instances. * * @example * ```typescript * import { MemoryEntityCache } from '@wolfstar/plugin-cache'; * * // Cache guilds, channels, and roles only. * const client = new GatewayClient({ * intents, * makeCache: (entity) => (['guilds', 'channels', 'roles'].includes(entity) ? new MemoryEntityCache() : null), * }); * ``` * * @default undefined */ makeCache?: CacheFactory; /** * The policies deciding which entries get cached, and for how long, per entity kind, see `withPolicy`. They apply to * every write, from dispatches as well as from the managers: an entry its `filter` rejects is not cached, and the * entry already cached under its key is deleted. * * @remarks * `ttl` only applies to `@wolfstar/plugin-cache` stores ({@link GatewayClientOptions.cache}, * {@link GatewayClientOptions.makeCache}): the caches of instances built by * {@link GatewayClientOptions.cacheConstructor}, the default included, have no per-entry time-to-live. * * @example * ```typescript * // Do not cache bots, and forget messages after an hour. * policies: { users: { filter: (user) => !user.bot }, messages: { ttl: () => 3_600_000 } } * ``` * * @default undefined */ policies?: CachePolicies; /** * What the managers do when a cache read or write fails, e.g. while Redis is unreachable. A `cacheError` event is * emitted either way. * * - `"miss"`: treat it as a cache miss, falling back to the API or to the data at hand. * - `"throw"`: reject with the error. * * @remarks * Dispatches follow {@link GatewayClientOptions.cacheFailure} instead. * * @default "miss" */ cacheErrors?: "miss" | "throw"; /** * Additional options for the underlying `@discordjs/ws` `WebSocketManager`, e.g. `compression` or * `initialPresence`. */ gateway?: Partial>; /** * Where to keep the shards' sessions, e.g. `createRedisSessionStore` from `@wolfstar/plugin-cache`, so a restarted * process resumes them instead of identifying again: no identify quota spent, the dispatches missed meanwhile * replayed, and no `GUILD_CREATE` burst. Pair it with a persistent cache, since a resumed session does not refill an * empty one. Use {@link GatewayClient.destroy}'s `resumable` option to keep the sessions on a graceful shutdown. * * @remarks * The store is read once per shard when it first connects, then mirrored in memory, and written in the background * on every sequence change, see {@link GatewayClientOptions.sessionStoreTimeout}. Its failures are reported as * `GatewaySessionStoreError`s through the `error` event and never stop a shard: a failed read identifies. * * It replaces `gateway.retrieveSessionInfo` and `gateway.updateSessionInfo`, passing either alongside it throws. * * @default undefined */ sessionStore?: GatewaySessionStore; /** * The time, in milliseconds, after which a shard stops waiting for {@link GatewayClientOptions.sessionStore} to read * its session, and identifies instead. `null` waits forever. * * @default 5_000 */ sessionStoreTimeout?: number | null; /** * What to do with a dispatch whose cache read or write fails, e.g. while Redis is unreachable. The error is always * reported through the `error` event (or the logger when nobody listens to it). * * - `"skip"`: drop the dispatch's event, so listeners never see state the cache does not hold. * - `"emitUncached"`: still emit the event, built from the payload alone, with `null` as the previous state. * * @default "skip" */ cacheFailure?: "skip" | "emitUncached"; /** * The time, in milliseconds, after which a dispatch still being processed is reported as a `DispatchTimeoutError` * through the `error` event. The dispatch is not cancelled. `null` disables the check. * * @default 30_000 */ dispatchTimeout?: number | null; /** * The structures to build partially when an event concerns one that is not cached, like discord.js's `partials`, * e.g. `[Partials.Message, Partials.User]`. See {@link Partials}. * * @default [] */ partials?: readonly Partials[]; /** * How long, in milliseconds, the client waits for every guild `READY` listed as initially unavailable to become * available (its `GUILD_CREATE`) before emitting `clientReady` anyway, like discord.js's `waitGuildTimeout`. * * @remarks * It only bounds the wait on guild availability: `clientReady` still never fires before every shard this client * manages has connected, however long that takes, even past this timeout. * * Skipped (waits `0` ms) when `intents` does not include `GatewayIntentBits.Guilds`, since without it Discord never * sends the guilds' data, so no `GUILD_CREATE` for them ever arrives. * * @default 15_000 */ waitGuildTimeout?: number; } /** Options for loading pieces and starting both transports. */ export interface GatewayClientStartOptions { /** HTTP interaction server options. */ listen: Client.ServerListenOptions; /** Piece loading options. */ load?: Client.PieceLoadOptions; } /** Options for disconnecting the gateway shards. */ export interface GatewayClientDestroyOptions { /** * Whether to keep the shards' sessions resumable, for the next process to resume them (e.g. during a deploy): the * shards close with a code Discord does not invalidate the session on, and their sessions stay stored. Only * meaningful with {@link GatewayClientOptions.sessionStore}, or with `gateway.updateSessionInfo`. * * @default false */ resumable?: boolean; } /** * The dispatch a {@link DispatchWrapper} wraps. */ export interface WrappedDispatch { /** The payload Discord sent. */ payload: GatewayDispatchPayload; /** The gateway shard it came from. */ shardId: number; /** The partition it is ordered in (`guild:`, `channel:`...), or `null` for one ordered by shard only. */ partition: string | null; } /** * Wraps the processing of each dispatch, for code that has to run around it rather than react to an event: a tracing * span the cache and listener work becomes the child of, a timer, an `AsyncLocalStorage` store. * * @param dispatch The dispatch being processed. * @param run Processes it: writes it into the cache and emits its events. Call it exactly once and return (or await) * its promise. It rejects when the processing fails, which the client then reports as for any dispatch. */ export type DispatchWrapper = (dispatch: WrappedDispatch, run: () => Promise) => Promise; /** * Runs at the end of {@link GatewayClient.destroy}, once the shards are disconnected and every dispatch is processed: * flushing what is left to export, such as traces, before the process exits. */ export type GatewayClientDestroyHook = () => unknown; /** * A {@link Client} that, on top of serving HTTP interactions, connects to the Discord gateway, writes every dispatch * into its cache, and emits {@link GatewayEventMap} events carrying structures. * * @example * ```typescript * import { GatewayClient } from '@wolfstar/plugin-gateway'; * import { createInMemoryCache } from '@wolfstar/plugin-cache'; * import { GatewayIntentBits } from 'discord-api-types/v10'; * * const client = new GatewayClient({ * intents: GatewayIntentBits.Guilds | GatewayIntentBits.GuildMessages, * cache: createInMemoryCache(), * }); * * client.on('messageCreate', (message) => console.log(`${message.author.username}: ${message.content}`)); * * await client.start({ listen: { port: 8080 } }); * ``` */ export declare class GatewayClient extends Client { #private; /** * The raw cache every dispatch is written into, if any: the `@wolfstar/plugin-cache` cache passed as * {@link GatewayClientOptions.cache}, or a raw view of the managers' caches of instances. */ readonly cache: Cache$1 | undefined; /** * The REST manager the gateway (for its gateway bot info) and every manager's API calls go through, like * discord.js's `Client#rest`. */ readonly rest: REST; /** * The underlying `@discordjs/ws` manager, handling the shards' connections, resumes, and identify rate limits. */ readonly gateway: WebSocketManager; /** * The typed REST API every manager's calls go through, `@discordjs/core`'s `API` built from {@link GatewayClient.rest}. */ readonly api: API; /** * The discord.js core client, sharing this client's REST and gateway transports, like the RFC `next` `Client`'s * own `core`. * * @remarks * Kept protected: managers and structures reach its typed REST calls through {@link GatewayClient.api} instead, and * its gateway and REST manager are already {@link GatewayClient.gateway} and {@link GatewayClient.rest}. It is only * needed to build the discord.js core client's own event listeners, if this class ever wraps them. */ protected readonly core: Client$1; /** The actions that turn gateway dispatches into public client events. */ readonly actions: ActionsManager; /** * The bot user, set once the first shard receives `READY`. * * @remarks * A shard that resumes a stored session gets `RESUMED` instead of `READY`: the user is then restored from the cache, * or fetched from the API when the cache does not hold it. It can be stale until the next `USER_UPDATE`, and stays * `null` if neither source answers (the failure is reported through `error`). */ user: ClientUser | null; /** * The application of the bot, like discord.js's `Client#application`. * * @remarks * Unlike discord.js, it is never `null`: it is built from {@link GatewayClientOptions.clientId} when the client is, * so it exists before `READY` and without any gateway connection. It is then partial, see * {@link ClientApplication.partial}: `READY` patches the same instance with the application's flags, and * {@link ClientApplication.fetch} with the rest. It is kept on the client, not in the cache: it is a single small * object, and every process gets the same `READY`. */ readonly application: ClientApplication; readonly users: UserManager; readonly guilds: GuildManager; readonly channels: ChannelManager; readonly threads: ThreadManager; readonly threadMembers: ThreadMemberManager; readonly messages: MessageManager; readonly members: GuildMemberManager; readonly roles: RoleManager; readonly webhooks: WebhookManager; readonly templates: GuildTemplateManager; readonly voiceStates: VoiceStateManager; readonly presences: PresenceManager; /** * Evicts entries from the caches of instances, on the schedule of {@link GatewayClientOptions.sweepers} and on * demand, like discord.js's `Client#sweepers`. */ readonly sweepers: Sweepers; /** * What happens to a dispatch whose cache read or write fails, see {@link GatewayClientOptions.cacheFailure}. */ readonly cacheFailure: "skip" | "emitUncached"; /** * What the managers do when a cache read or write fails, see {@link GatewayClientOptions.cacheErrors}. */ readonly cacheErrors: "miss" | "throw"; /** * See {@link GatewayClientOptions.dispatchTimeout}. */ readonly dispatchTimeout: number | null; /** * The structures built partially for uncached entities, see {@link GatewayClientOptions.partials}. */ readonly partials: readonly Partials[]; /** * See {@link GatewayClientOptions.waitGuildTimeout}. */ readonly waitGuildTimeout: number; /** * The timestamp the client last became ready, like discord.js's `Client#readyTimestamp`. `null` until * `clientReady` is first emitted, see {@link GatewayClient.clientReadyAt}. */ clientReadyTimestamp: number | null; constructor(options: GatewayClientOptions); /** * Connects every configured shard to the gateway. */ connect(): Promise; /** Loads pieces, starts the interaction endpoint, then connects gateway shards. */ start({ listen, load }: GatewayClientStartOptions): Promise; /** * Disconnects every shard from the gateway. The HTTP server, if listening, is left untouched. * * @remarks * By default, the shards close their sessions, which Discord invalidates. Pass `resumable: true` to keep them * resumable instead, e.g. on a graceful shutdown before a deploy. Either way, it waits for the sessions to be * written to {@link GatewayClientOptions.sessionStore}. * * A call made while another one is still disconnecting the shards joins it, keeping the first call's `resumable`. * * @param options Whether to keep the sessions resumable. */ destroy(options?: GatewayClientDestroyOptions): Promise; private disconnect; /** * Wraps the processing of every dispatch received from now on, see {@link DispatchWrapper}. * * @remarks * Wrappers nest in the order they were added: the first one added is the outermost. The dispatch timeout and the * error reporting of the client are outside of every wrapper. * * @param wrapper The wrapper. * @returns A function that removes the wrapper, for the dispatches received after it is called. */ addDispatchWrapper(wrapper: DispatchWrapper): () => void; /** * Runs a hook at the end of every {@link GatewayClient.destroy}, see {@link GatewayClientDestroyHook}. * * @remarks * The hooks run one after the other, in the order they were added, even when disconnecting the shards failed. A hook * that throws is reported through the `error` event (or logged when nothing listens) and does not stop the others. * Adding the same function twice adds it once. * * @param hook The hook. * @returns A function that removes the hook. */ addDestroyHook(hook: GatewayClientDestroyHook): () => void; /** * Runs a cache write of the client's own (e.g. after leaving a guild) in order with the guild's dispatches. * * @param guildId The ID of the guild. * @param task The cache write. * @internal */ runInGuildOrder(guildId: string, task: () => Promise): Promise; /** * Gets the cache of an entity, building it on first use: the `CacheConstructor` of the discord.js RFC #11426. * Every manager of the same entity shares the same cache. * * @param creator Builds a structure from raw data, for entities the client does not know how to build. * @param name The name of the entity. */ CacheConstructor>(creator: StructureCreator, name: CacheEntityName): Cache; /** * Gets the cache of an entity if it was built already, without building it. * * @param name The name of the entity. * @internal */ cacheOf(name: CacheEntityName): Cache | undefined; /** * Runs a raw store operation, reporting its failure through `cacheError`, see * {@link GatewayClientOptions.cacheErrors}. Synchronous when the operation is. * * @internal */ guardCache(entity: CacheEntityName, operation: CacheErrorContext["operation"], key: string | null, run: () => Awaitable, fallback: T): Awaitable; /** * Gets the `filter` of an entity's policy the managers must apply themselves before writing to its cache, see * {@link GatewayClientOptions.policies}. * * @param name The name of the entity. * @returns The filter, or `undefined` when there is none or when the entity's store applies it already. * @internal */ cacheFilter(name: CacheEntityName): ((value: object, key: string) => boolean) | undefined; /** * Resolves once every dispatch received so far has been processed. */ idle(): Promise; /** * Fetches Discord's default soundboard sounds, which every guild can play. */ fetchDefaultSoundboardSounds(): Promise; /** * Fetches a webhook. discord.js: `client.fetchWebhook(id, token)`. * * @param webhookId The ID of the webhook. * @param token The webhook's token, to fetch it without the bot's authorization. */ fetchWebhook(webhookId: string, token?: string): Promise; /** * Fetches a guild template by its code. discord.js: `client.fetchGuildTemplate(code)`. * * @param code The code of the template, or its URL. */ fetchGuildTemplate(code: string): Promise; /** * Fetches the public widget of a guild, which must be enabled. Needs no membership of the guild. * * @param guildId The ID of the guild. */ fetchGuildWidget(guildId: string): Promise; /** * Fetches an invite by its code. * * @param code The code of the invite, or its URL. * @param options Whether to include the approximate counts (default), and a scheduled event to attach. */ fetchInvite(code: string, options?: { withCounts?: boolean; guildScheduledEventId?: string; }): Promise; /** * Fetches a sticker, standard or from a guild. * * @param stickerId The ID of the sticker. */ fetchSticker(stickerId: string): Promise; /** * Fetches the packs of standard stickers. */ fetchStickerPacks(): Promise; /** * Fetches the voice regions available to the bot. */ fetchVoiceRegions(): Promise; /** * The dispatches received but not processed yet, and the partitions (guilds, direct message channels) they are * queued in. A growing `pending` count usually means a slow or unreachable cache. */ get queueStats(): DispatchQueueStats; /** * The time the client last became ready, like discord.js's `Client#readyAt`. `null` until `clientReady` is first * emitted. */ get clientReadyAt(): Date | null; /** * Whether the client already emitted `clientReady`, like discord.js's `Client#isReady()`. */ isClientReady(): boolean; /** * Serializes the previous state a dispatch's handler read (the `state` of the `dispatch` event) to plain data other * processes can {@link GatewayClient.reviveDispatchState revive}. * * @param type The dispatch type, e.g. `MESSAGE_UPDATE`. * @param state The state, as passed to the `dispatch` event. * @returns The plain data, `undefined` when there is no state or the type keeps none. */ serializeDispatchState(type: string, state: unknown): unknown; /** * Builds the structures of a state {@link GatewayClient.serializeDispatchState serialized} on another process, to * hand to {@link GatewayClient.replayDispatch}. Relations resolve from this client's cache as it is now, so they can * be newer than the dispatch. * * @param type The dispatch type. * @param state The serialized state, `undefined` when there was none. * @param data The dispatch data. */ reviveDispatchState(type: string, state: unknown, data: unknown): Promise; /** * Like `emit`, but resolves once the listeners' promises settled and rejects with the first failure. * * @internal */ emitAndWait(event: string, args: readonly unknown[]): Promise; /** * Whether the dispatches of this client are forwarded to workers, which replay them on their own listeners, see * `forwardGatewayDispatches` from `@wolfstar/plugin-broker`. Listeners registered with * {@link RegisterAsDispatchListener} stay idle on a client that does. */ get forwardsDispatches(): boolean; /** * Marks this client as forwarding its dispatches, until the returned function is called. Called by * `forwardGatewayDispatches`, it counts, so the client keeps forwarding while any forwarder is left. * * @returns A function to undo the mark, which does nothing when called again. */ markDispatchesForwarded(): () => void; /** * The dispatch types {@link GatewayClient.replayDispatch} turns into events. */ get replayDispatchTypes(): readonly string[]; /** * Handles a dispatch another process received and wrote to the shared cache: emits `raw`, then the matching * {@link GatewayEventMap} event, exactly as {@link GatewayClient.handleDispatch} would for a dispatch of this * client, but without reading or writing the cache and without emitting `dispatch`, so a worker that never * connects to Discord sees the events of the gateway process's client. * * @remarks * Dispatches of a guild are handled in the order they were replayed, like the ones of a connected client. * `READY` and `INTERACTION_CREATE` are ignored. * * @param payload The dispatch type and data, and its sequence number on the shard that received it, `0` when * unknown. `raw` listeners get it as a full gateway payload, with its `op`. * @param shardId The ID of the shard that received it, on the process that did. * @param state The previous state, revived with {@link GatewayClient.reviveDispatchState}. * @returns A promise rejecting when a listener or the handler throws, so the caller can retry the dispatch. */ replayDispatch(payload: { t: string; d: unknown; s?: number; }, shardId: number, state?: unknown): Promise; /** * Processes a gateway dispatch: emits it as `raw`, writes it into the cache, emits it as `dispatch`, and emits the * matching {@link GatewayEventMap} event, if any. * * @param payload The dispatch payload. * @param shardId The ID of the shard that received it. */ protected handleDispatch(payload: GatewayDispatchPayload, shardId: number): Promise; /** * Drops the cached guilds of a shard its `READY` no longer lists, and emits `dispatch` and `guildDelete` for each of * them. * * @remarks * They are the guilds the bot left while it was disconnected, or while the process was down with a persistent * cache. Discord does not replay those removals on a new session, so the cache would otherwise keep them forever. * * Each drop is handled as a `GUILD_DELETE` (with `s: 0`) Discord would have sent, `raw` aside: `dispatch` fires once * the guild is gone from the cache, with the cached guild as its state, so forwarding `dispatch` to other processes * (`@wolfstar/plugin-broker`'s `forwardGatewayDispatches`) carries these deletions too. * * It needs a guilds cache able to enumerate its entries, and is skipped without one. * * It is best effort: any failure (cache unreachable, unknown shard count) is reported through `error` and stops the * reconciliation, keeping the remaining guilds, but never fails `READY` itself. * * @param data The `READY` data. * @param shardId The shard that received it. */ protected reconcileGuilds(data: GatewayReadyDispatchData, shardId: number): Promise; private dropUnlistedGuilds; private runDispatch; private sessionCallbacks; private reportError; } /** * The relations of an {@link AutoModerationActionExecution}, resolved from the cache. */ export interface AutoModerationActionExecutionRelations { guild?: Guild | null; user?: User | null; member?: GuildMember | null; channel?: AnyChannel | null; autoModerationRule?: AutoModerationRule | null; } /** * An action auto moderation took on a message or a member. */ export declare class AutoModerationActionExecution extends Structure { [kRelations]: AutoModerationActionExecutionRelations; /** * @param data The raw execution. * @param relations The guild and user as resolved from the cache. */ constructor(data: GatewayAutoModerationActionExecutionDispatchData, relations?: AutoModerationActionExecutionRelations); get guildId(): string; /** * The action taken: blocking the message, alerting a channel, or timing the member out. Camel-cased like * discord.js's `AutoModerationActionExecution#action`. */ get action(): AutoModerationAction; get ruleId(): string; get ruleTriggerType(): import("discord-api-types/v10").AutoModerationRuleTriggerType; get userId(): string; get channelId(): string | null; /** * The ID of the message that triggered the rule. Absent when the message was blocked. */ get messageId(): string | null; /** * The ID of the alert message sent to the alert channel, for `SendAlertMessage` actions. */ get alertSystemMessageId(): string | null; /** * The content that triggered the rule. Needs the `MessageContent` intent. */ get content(): string; get matchedKeyword(): string | null; get matchedContent(): string | null; get guild(): Guild | null; get user(): User | null; /** * The member who triggered the rule, from the cache, like discord.js's `AutoModerationActionExecution#member`. */ get member(): GuildMember | null; /** * The channel the rule was triggered in, from the cache: `null` when there is none or it is not cached. */ get channel(): AnyChannel | null; /** * The rule that was triggered, from the cache: `null` when it is not cached. */ get autoModerationRule(): AutoModerationRule | null; fetchRule(): Promise; fetchMember(): Promise; fetchChannel(): Promise; } /** * The relations of a {@link Typing}, resolved from the cache by the `typingStart` event. */ export interface TypingRelations { channel?: AnyChannel | null; user?: User | null; guild?: Guild | null; member?: GuildMember | PartialGuildMember | null; } /** * A user starting to type in a channel, carried by the `typingStart` event. */ export declare class Typing extends Structure { [kRelations]: TypingRelations; /** * @param data The raw dispatch. * @param relations The channel, user, guild, and member as resolved from the cache. */ constructor(data: GatewayTypingStartDispatchData, relations?: TypingRelations); get channelId(): string; get guildId(): string | null; get userId(): string; /** * The time the user started typing, in milliseconds. */ get startedTimestamp(): number; get startedAt(): Date; /** * The channel the user typed in, from the cache, like discord.js's `Typing#channel`: `null` when it is not cached. */ get channel(): AnyChannel | null; /** * The typing user, from the cache, else the user of the payload's member: `null` in a direct message whose user is * not cached. */ get user(): User | null; /** * The guild of the channel, from the cache: `null` outside of guilds or when it is not cached. */ get guild(): Guild | null; /** * The typing member, when the channel is in a guild: the cached member, else the one of the payload, else a partial * one with `Partials.GuildMember`. */ get member(): GuildMember | PartialGuildMember | null; /** * Whether the user typed in a guild channel. */ inGuild(): boolean; /** * Fetches the channel the user typed in. */ fetchChannel(): Promise; /** * Fetches the typing user. */ fetchUser(): Promise; } /** * Where a cache failure reported by the `cacheError` event happened. */ export interface CacheErrorContext { /** * The entity cache that failed. */ entity: CacheEntityName; /** * The key of the entry, `null` for operations spanning the whole cache. */ key: string | null; /** * The operation that failed. */ operation: "get" | "set" | "upsert" | "delete" | "has" | "clear" | "getSize" | "keys" | "entries" | "sweep"; } /** * What a reaction event says besides the reaction and the user. */ export interface MessageReactionEventDetails { /** * The ID of the user who reacted, known even when the user is not. */ userId: string; type: ReactionType; /** * Whether the reaction is a super reaction. */ burst: boolean; } /** * The events a {@link GatewayClient} emits on top of the base `Client`'s ones, and their arguments. * * @remarks * Update events receive the previous state of the entity as read from the cache before the dispatch was applied, or * `null` when it was not cached. Delete events receive the cached entity (or `null`) alongside the raw dispatch data, * which always identifies the deleted entity. * * With the matching `Partials` enabled, uncached messages, users, members, thread members, scheduled events, * soundboard sounds, polls, and direct messages are partial structures (`partial` is `true`) instead of `null`. */ export interface GatewayEventMap { /** * Emitted for every gateway dispatch, before any processing, with the raw payload. */ raw: [payload: GatewayDispatchPayload, shardId: number]; /** * Emitted for every gateway dispatch once it has been written to the cache (right away without one), before the * matching event, with the raw payload. Unlike `raw`, a listener reading the cache sees the dispatch applied, which * is what forwarding it to other processes sharing the cache needs. * * @remarks * Not emitted for `INTERACTION_CREATE`, served by the HTTP endpoint, nor for a dispatch dropped because its cache * write failed with {@link GatewayClientOptions.cacheFailure} set to `"skip"`. * * Also emitted, with `s: 0` and no `raw` before it, for the `GUILD_DELETE` the client makes up for a cached guild a * `READY` no longer lists, see {@link GatewayClient.reconcileGuilds}. * * `state` is what the dispatch's handler read before the cache write, e.g. the cached message a `MESSAGE_UPDATE` * replaces, or `undefined`. It is what {@link GatewayClient.serializeDispatchState} serializes for other processes. */ dispatch: [payload: GatewayDispatchPayload, shardId: number, state: unknown]; /** * Emitted when a shard receives `READY`. */ shardReady: [shardId: number, user: User]; /** * Emitted once, when every shard this client manages has connected and every guild `READY` listed as initially * unavailable became available, or {@link GatewayClientOptions.waitGuildTimeout} elapsed, like discord.js's * `Client#clientReady` (`ready` before discord.js deprecated it). */ clientReady: [client: GatewayClient]; /** * Emitted when a shard resumes its session. */ shardResume: [shardId: number]; /** * Emitted when a shard's connection closes, it reconnects on its own unless the close code is fatal. */ shardClose: [shardId: number, code: number]; /** * Emitted when a shard runs into an error. */ shardError: [error: Error, shardId: number]; /** * Emitted when a manager's cache read or write fails, e.g. while Redis is unreachable. With the default * `cacheErrors: "miss"`, the manager then carries on as if the entry was not cached. */ cacheError: [error: unknown, context: CacheErrorContext]; /** * Emitted when a sweep of an entity's cache ran, with the amount of entries it evicted, see `Sweepers`. */ cacheSweep: [entity: SweepableEntityName, swept: number]; guildCreate: [guild: Guild]; guildUpdate: [oldGuild: Guild | null, newGuild: Guild]; /** * Emitted when the client leaves a guild, or when it becomes unavailable because of an outage, in which case * `data.unavailable` is `true`. */ guildDelete: [guild: Guild | null, data: GatewayGuildDeleteDispatchData]; channelCreate: [channel: AnyChannel]; channelUpdate: [oldChannel: AnyChannel | null, newChannel: AnyChannel]; channelDelete: [channel: AnyChannel]; /** * Emitted when a message is pinned or unpinned; `data.last_pin_timestamp` is the time of the last pin left. */ channelPinsUpdate: [data: GatewayChannelPinsUpdateDispatchData]; /** * Emitted when a webhook of a channel is created, updated, or deleted. */ webhooksUpdate: [data: GatewayWebhooksUpdateDispatchData]; threadCreate: [thread: AnyThreadChannel]; threadUpdate: [oldThread: AnyThreadChannel | null, newThread: AnyThreadChannel]; threadDelete: [thread: AnyThreadChannel | null, data: GatewayThreadDeleteDispatchData]; /** * Emitted when the bot gains access to a channel's threads, with the active ones and the bot's membership of each. */ threadListSync: [threads: AnyThreadChannel[], members: ThreadMember[], data: GatewayThreadListSync]; /** * Emitted when the bot's own thread member changes, e.g. its notification settings. */ threadMemberUpdate: [oldMember: ThreadMember | null, newMember: ThreadMember]; /** * Emitted when members are added to or removed from a thread. The removed members are the ones the cache held. */ threadMembersUpdate: [added: ThreadMember[], removed: ThreadMember[], thread: AnyThreadChannel | null, data: GatewayThreadMembersUpdateDispatchData]; messageCreate: [message: Message]; messageUpdate: [oldMessage: Message | null, newMessage: Message]; messageDelete: [message: Message | null, data: GatewayMessageDeleteDispatchData]; messageDeleteBulk: [messages: Message[], data: GatewayMessageDeleteBulkDispatchData]; /** * Emitted when a user reacts to a message. The reaction has its counts when the message is cached (`count` is * `null` otherwise), and the user is `null` when neither the payload (outside of guilds) nor the cache has it. */ messageReactionAdd: [reaction: MessageReaction, user: User | null, details: MessageReactionEventDetails]; /** * Emitted when a user removes their reaction. Like `messageReactionAdd`, `count` is `null` only when the message is * not cached: removing the last reaction of an emoji from a cached message gives a count of `0`. */ messageReactionRemove: [reaction: MessageReaction, user: User | null, details: MessageReactionEventDetails]; /** * Emitted when every reaction is removed from a message, with the reactions the cache held, by emoji. */ messageReactionRemoveAll: [message: Message | null, reactions: Collection, data: GatewayMessageReactionRemoveAllDispatchData]; /** * Emitted when every reaction with one emoji is removed from a message. */ messageReactionRemoveEmoji: [reaction: MessageReaction]; /** * Emitted when a user votes for a poll answer. The answer has its text and counts when the message is cached. */ messagePollVoteAdd: [answer: PollAnswer, userId: string]; messagePollVoteRemove: [answer: PollAnswer, userId: string]; guildMemberAdd: [member: GuildMember]; /** * `oldMember` is partial with `Partials.GuildMember` when the member was not cached. */ guildMemberUpdate: [oldMember: GuildMember | PartialGuildMember | null, newMember: GuildMember]; /** * `member` is partial with `Partials.GuildMember` when the member was not cached. */ guildMemberRemove: [member: GuildMember | PartialGuildMember | null, data: GatewayGuildMemberRemoveDispatchData]; /** * Emitted for each chunk of members Discord sends in answer to `client.members.request`, once it is cached. * `data` has the chunk's index and count, its nonce, and the requested IDs that are not members (`not_found`). */ guildMembersChunk: [members: GuildMember[], guild: Guild | null, data: GatewayGuildMembersChunkDispatchData]; guildRoleCreate: [role: Role]; guildRoleUpdate: [oldRole: Role | null, newRole: Role]; guildRoleDelete: [role: Role | null, data: GatewayGuildRoleDeleteDispatchData]; userUpdate: [oldUser: User | null, newUser: User]; /** * Emitted for every `GUILD_EMOJIS_UPDATE`, with every emoji the guild now has. Always emitted, cache or not: the * granular `emojiCreate`, `emojiUpdate`, and `emojiDelete` need the previous emojis, so the emojis cache. */ guildEmojisUpdate: [guildId: string, emojis: GuildEmoji[]]; /** * Emitted for each emoji a `GUILD_EMOJIS_UPDATE` adds, compared with the cache. Without an emojis cache (able to * enumerate its entries), the emoji events are not emitted: listen to `guildEmojisUpdate` instead. */ emojiCreate: [emoji: GuildEmoji]; emojiUpdate: [oldEmoji: GuildEmoji, newEmoji: GuildEmoji]; emojiDelete: [emoji: GuildEmoji]; /** * Emitted for every `GUILD_STICKERS_UPDATE`, with every sticker the guild now has, like `guildEmojisUpdate`. */ guildStickersUpdate: [guildId: string, stickers: Sticker[]]; /** * Emitted for each sticker a `GUILD_STICKERS_UPDATE` adds, compared with the cache, like the emoji events. */ stickerCreate: [sticker: Sticker]; stickerUpdate: [oldSticker: Sticker, newSticker: Sticker]; stickerDelete: [sticker: Sticker]; inviteCreate: [invite: GuildInvite]; /** * Emitted when an invite is deleted or expires, with the cached invite if any. */ inviteDelete: [invite: GuildInvite | null, data: GatewayInviteDeleteDispatchData]; typingStart: [typing: Typing]; /** * Emitted when a guild's voice server changes, e.g. to hand a voice connection a new endpoint. */ voiceServerUpdate: [data: GatewayVoiceServerUpdateDispatchData]; /** * Emitted when a user is banned. Bans from the gateway have no reason. */ guildScheduledEventCreate: [event: GuildScheduledEvent]; guildScheduledEventUpdate: [oldEvent: GuildScheduledEvent | null, newEvent: GuildScheduledEvent]; guildScheduledEventDelete: [event: GuildScheduledEvent]; /** * Emitted when a user subscribes to a scheduled event, with the cached event and user when there are. */ guildScheduledEventUserAdd: [event: GuildScheduledEvent | null, user: User | null, data: GatewayGuildScheduledEventUserAddDispatchData]; guildScheduledEventUserRemove: [event: GuildScheduledEvent | null, user: User | null, data: GatewayGuildScheduledEventUserRemoveDispatchData]; stageInstanceCreate: [stageInstance: StageInstance]; stageInstanceUpdate: [oldStageInstance: StageInstance | null, newStageInstance: StageInstance]; stageInstanceDelete: [stageInstance: StageInstance]; guildSoundboardSoundCreate: [sound: SoundboardSound]; guildSoundboardSoundUpdate: [oldSound: SoundboardSound | null, newSound: SoundboardSound]; /** * Emitted when a soundboard sound is deleted, with the cached sound when there is one. */ guildSoundboardSoundDelete: [sound: SoundboardSound | null, data: GatewayGuildSoundboardSoundDeleteDispatchData]; /** * Emitted when several soundboard sounds of a guild change at once. */ guildSoundboardSoundsUpdate: [sounds: SoundboardSound[], guildId: string]; /** * Emitted with the sounds of a guild, in answer to a request for them over the gateway. */ soundboardSounds: [sounds: SoundboardSound[], guildId: string]; guildBanAdd: [ban: GuildBan]; /** * Emitted when a ban is lifted, with the cached ban (and its reason, if it was fetched) when there is one. */ guildBanRemove: [ban: GuildBan]; /** * Emitted when an entry is added to a guild's audit log. Needs the `GuildModeration` intent. */ guildAuditLogEntryCreate: [entry: GuildAuditLogsEntry]; autoModerationRuleCreate: [rule: AutoModerationRule]; autoModerationRuleUpdate: [oldRule: AutoModerationRule | null, newRule: AutoModerationRule]; autoModerationRuleDelete: [rule: AutoModerationRule]; /** * Emitted when auto moderation takes an action. Needs the `AutoModerationExecution` intent. */ autoModerationActionExecution: [execution: AutoModerationActionExecution]; /** * Emitted when an integration of a guild is created, updated, or deleted. */ guildIntegrationsUpdate: [guild: Guild | null, data: GatewayGuildIntegrationsUpdateDispatchData]; integrationCreate: [integration: Integration]; integrationUpdate: [oldIntegration: Integration | null, newIntegration: Integration]; integrationDelete: [integration: Integration | null, data: GatewayIntegrationDeleteDispatchData]; /** * Emitted when a user or a guild is granted a SKU of the application, by a purchase or a test entitlement. */ entitlementCreate: [entitlement: Entitlement]; /** * Emitted when an entitlement changes, e.g. a subscription renews. `oldEntitlement` is `null` when it was not * cached. */ entitlementUpdate: [oldEntitlement: Entitlement | null, newEntitlement: Entitlement]; /** * Emitted when an entitlement is deleted, which Discord only does for test entitlements and refunds. */ entitlementDelete: [entitlement: Entitlement]; /** * Emitted when a member joins, leaves, or moves between voice channels, or changes their voice settings. */ voiceStateUpdate: [oldState: VoiceState | null, newState: VoiceState]; /** * Emitted when the status of a cached voice channel changes. Not emitted for a channel that is not cached, which * leaves nothing to compare the new status with. */ voiceChannelStatusUpdate: [oldChannel: VoiceChannel, newChannel: VoiceChannel]; /** * Emitted when the start time of the voice session of a cached voice channel changes. Not emitted for a channel * that is not cached. */ voiceChannelStartTimeUpdate: [oldChannel: VoiceChannel, newChannel: VoiceChannel]; /** * Emitted with the cached voice channels of a guild whose info Discord sent, in answer to * `client.channels.requestInfo`. */ channelInfo: [channels: VoiceChannel[], guild: Guild | null]; /** * Emitted when a member's status or activities change. Needs the `GuildPresences` intent. */ presenceUpdate: [oldPresence: Presence | null, newPresence: Presence]; } /** * The name of any of the events listed in {@link GatewayEventMap}. */ export type GatewayEventName = keyof GatewayEventMap; /** * The events only the process that connects to Discord emits: a worker replaying forwarded dispatches never sees * them. Every other event comes from a dispatch, `raw` included, which {@link GatewayClient.replayDispatch} emits too. */ export type GatewayOnlyEventName = "dispatch" | "shardReady" | "clientReady" | "shardResume" | "shardClose" | "shardError" | "cacheError" | "cacheSweep"; /** * The name of any event that comes from a dispatch, and so reaches a worker replaying the forwarded ones. */ export type DispatchEventName = Exclude; /** * The {@link GatewayOnlyEventName} events, for telling them from {@link DispatchEventName} ones at runtime. */ export declare const gatewayOnlyEvents: ReadonlySet; /** * The name of every event a {@link GatewayClient} emits, mirroring the keys of {@link GatewayEventMap}, like * `@wolfstar/http-framework`'s own `Events`. * * @remarks * Each member's value is the plain event name, so they are interchangeable with the string literals accepted by * `GatewayClient#on`, `GatewayClient#emit`, and `Listener.Options.event`. * * @example * ```typescript * client.on(GatewayEvents.MessageCreate, (message) => console.log(message.content)); * ``` */ export declare enum GatewayEvents { Raw = "raw", Dispatch = "dispatch", ShardReady = "shardReady", ClientReady = "clientReady", ShardResume = "shardResume", ShardClose = "shardClose", ShardError = "shardError", CacheError = "cacheError", CacheSweep = "cacheSweep", GuildCreate = "guildCreate", GuildUpdate = "guildUpdate", GuildDelete = "guildDelete", ChannelCreate = "channelCreate", ChannelUpdate = "channelUpdate", ChannelDelete = "channelDelete", ChannelPinsUpdate = "channelPinsUpdate", WebhooksUpdate = "webhooksUpdate", ThreadCreate = "threadCreate", ThreadUpdate = "threadUpdate", ThreadDelete = "threadDelete", ThreadListSync = "threadListSync", ThreadMemberUpdate = "threadMemberUpdate", ThreadMembersUpdate = "threadMembersUpdate", MessageCreate = "messageCreate", MessageUpdate = "messageUpdate", MessageDelete = "messageDelete", MessageDeleteBulk = "messageDeleteBulk", MessageReactionAdd = "messageReactionAdd", MessageReactionRemove = "messageReactionRemove", MessageReactionRemoveAll = "messageReactionRemoveAll", MessageReactionRemoveEmoji = "messageReactionRemoveEmoji", MessagePollVoteAdd = "messagePollVoteAdd", MessagePollVoteRemove = "messagePollVoteRemove", GuildMemberAdd = "guildMemberAdd", GuildMemberUpdate = "guildMemberUpdate", GuildMemberRemove = "guildMemberRemove", GuildMembersChunk = "guildMembersChunk", GuildRoleCreate = "guildRoleCreate", GuildRoleUpdate = "guildRoleUpdate", GuildRoleDelete = "guildRoleDelete", UserUpdate = "userUpdate", GuildEmojisUpdate = "guildEmojisUpdate", EmojiCreate = "emojiCreate", EmojiUpdate = "emojiUpdate", EmojiDelete = "emojiDelete", GuildStickersUpdate = "guildStickersUpdate", StickerCreate = "stickerCreate", StickerUpdate = "stickerUpdate", StickerDelete = "stickerDelete", InviteCreate = "inviteCreate", InviteDelete = "inviteDelete", TypingStart = "typingStart", VoiceServerUpdate = "voiceServerUpdate", GuildScheduledEventCreate = "guildScheduledEventCreate", GuildScheduledEventUpdate = "guildScheduledEventUpdate", GuildScheduledEventDelete = "guildScheduledEventDelete", GuildScheduledEventUserAdd = "guildScheduledEventUserAdd", GuildScheduledEventUserRemove = "guildScheduledEventUserRemove", StageInstanceCreate = "stageInstanceCreate", StageInstanceUpdate = "stageInstanceUpdate", StageInstanceDelete = "stageInstanceDelete", GuildSoundboardSoundCreate = "guildSoundboardSoundCreate", GuildSoundboardSoundUpdate = "guildSoundboardSoundUpdate", GuildSoundboardSoundDelete = "guildSoundboardSoundDelete", GuildSoundboardSoundsUpdate = "guildSoundboardSoundsUpdate", SoundboardSounds = "soundboardSounds", GuildBanAdd = "guildBanAdd", GuildBanRemove = "guildBanRemove", GuildAuditLogEntryCreate = "guildAuditLogEntryCreate", AutoModerationRuleCreate = "autoModerationRuleCreate", AutoModerationRuleUpdate = "autoModerationRuleUpdate", AutoModerationRuleDelete = "autoModerationRuleDelete", AutoModerationActionExecution = "autoModerationActionExecution", GuildIntegrationsUpdate = "guildIntegrationsUpdate", IntegrationCreate = "integrationCreate", IntegrationUpdate = "integrationUpdate", IntegrationDelete = "integrationDelete", EntitlementCreate = "entitlementCreate", EntitlementUpdate = "entitlementUpdate", EntitlementDelete = "entitlementDelete", VoiceStateUpdate = "voiceStateUpdate", VoiceChannelStatusUpdate = "voiceChannelStatusUpdate", VoiceChannelStartTimeUpdate = "voiceChannelStartTimeUpdate", ChannelInfo = "channelInfo", PresenceUpdate = "presenceUpdate" } declare module "@wolfstar/http-framework" { interface ClientEvents extends GatewayEventMap {} } /** * A {@link Listener} bound to one of the {@link GatewayEventMap} events of the {@link GatewayClient}, with strongly * typed arguments. It is loaded from the `listeners` directory by `client.load()` like any other listener. * * @example * ```typescript * // listeners/log-messages.ts * import { EventGatewayListener, type Message } from '@wolfstar/plugin-gateway'; * * export class LogMessagesListener extends EventGatewayListener<'messageCreate'> { * public constructor(context: EventGatewayListener.LoaderContext) { * super(context, { event: 'messageCreate' }); * } * * public override run(message: Message) { * console.log(`${message.author.username}: ${message.content}`); * } * } * ``` */ export declare abstract class EventGatewayListener extends Listener> { /** * Whether this listener unloads itself after its first run. */ readonly once: boolean; constructor(context: EventGatewayListener.LoaderContext, options: EventGatewayListener.Options); abstract run(...args: GatewayEventMap[Event]): Awaitable; } export declare namespace EventGatewayListener { type LoaderContext = Listener.LoaderContext; interface Options extends Omit { /** * The event to listen to. */ event: Event; /** * Whether to unload the listener after its first run. * * @default false */ once?: boolean; } interface ResolvedOptions extends Listener.Options { event: Event; once?: boolean; } } /** * The message of every {@link GatewayErrorCode}: a string, or a function formatting the arguments passed to the * error's constructor. */ export declare const GatewayErrorMessages: { readonly ClientSessionStoreConflict: "sessionStore replaces gateway.retrieveSessionInfo and gateway.updateSessionInfo, pass one or the other"; readonly ClientCacheConflict: "cacheConstructor and cacheOptions cannot be combined with cache or makeCache, pass one or the other"; readonly ClientSweepersConflict: "sweepers cannot be combined with cache or makeCache, whose stores hold raw data a sweep cannot filter: use their policies' ttl instead"; readonly ClientNotConstructed: "No GatewayClient has been constructed yet"; readonly SweeperIntervalTooLong: (entity: string, interval: number) => string; readonly DispatchHandlerConflict: (event: string) => string; readonly DispatchTimeout: (type: string, shardId: number, partition: string | null, timeout: number) => string; readonly SessionStoreFailed: (operation: "get" | "set", shardId: number) => string; readonly SessionStoreTimeout: (timeout: number) => string; readonly CacheAsynchronous: (entity: string) => string; readonly CacheConstructorAsynchronous: (entity: string) => string; readonly CacheNotIterable: (entity: string) => string; readonly CacheKeyUnresolvable: (entity: string, reason: string) => string; readonly IdUnresolvable: "Cannot resolve an ID from a structure without one"; readonly MessageBulkDeleteType: "The messages must be an Array, Collection, or number."; readonly InvalidType: (name: string, expected: string, an?: boolean) => string; readonly InvalidElement: (type: string, name: string, element: unknown) => string; readonly GuildUncached: (guildId: string) => string; readonly GuildUncachedMe: (guildId: string) => string; readonly GuildMemberUncached: (guildId: string, userId: string) => string; readonly ChannelUncached: (channelId: string) => string; readonly ChannelGuildUnknown: (channelId: string) => string; readonly ChannelTypeChanged: (channelId: string, from: number, to: number) => string; readonly ChannelLockPermissionsConflict: "Pass either lockPermissions or permissionOverwrites, not both"; readonly GuildChannelOrphan: (channelId: string) => string; readonly GuildChannelUnknown: (guildId: string, channelId: string) => string; readonly CategoryChildCategory: "A category cannot be created inside a category"; readonly GuildResolve: "Cannot resolve the value to a guild ID"; readonly GuildRoleUnknown: (guildId: string, roleId: string) => string; readonly ThreadPostMessageRequired: "A forum or media post needs a first message: pass message"; readonly ThreadOptionsPostOnly: (options: string) => string; readonly ThreadOptionsThreadOnly: (options: string) => string; readonly ChannelMessagesGuildOnly: (channelId: string, action: string) => string; readonly ThreadParentUnknown: (threadId: string) => string; readonly ThreadOwnerUnknown: (threadId: string) => string; readonly ThreadMemberIdsMissing: (action: string) => string; readonly GuildIntegrationNotFound: (guildId: string, integrationId: string) => string; readonly GuildMemberUserUnknown: "This member has no user data: its ID is unknown"; readonly GuildMembersQueryConflict: "Cannot request members by both query and userIds"; readonly GuildMembersUserIdsLimit: "Cannot request more than 100 members by their IDs"; readonly MemberFetchNonceLength: "The nonce of a members request cannot exceed 32 bytes"; readonly GuildMembersNoncePending: (nonce: string) => string; readonly GuildMembersTimeout: (guildId: string, nonce: string, timeout: number) => string; readonly GuildMembersRateLimited: (guildId: string, nonce: string, retryAfter: number) => string; readonly ChannelInfoFieldsEmpty: "Cannot request the info of the channels without any field"; readonly GuildChannelInfoTimeout: (guildId: string, timeout: number) => string; readonly GuildSoundboardSoundsTimeout: (guildIds: readonly string[], timeout: number) => string; readonly PresenceNotFetchable: (guildId: string, userId: string) => string; readonly InviteGuildUnknown: (code: string) => string; readonly UserNoDMChannel: "No DM Channel exists!"; readonly EmojiEmpty: "Cannot resolve an empty string to an emoji"; readonly EmojiType: "Cannot resolve an emoji without an ID nor a name"; readonly NotGuildSticker: "Only guild stickers can be edited or deleted"; readonly NotGuildSoundboardSound: "Default soundboard sounds cannot be changed"; readonly SoundboardSoundContentType: "Could not infer the content type of the sound, pass contentType"; readonly ApplicationCommandPermissionsTokenMissing: "Editing the permissions of an application command needs a bearer token (with the applications.commands.permissions.update scope), but none was provided"; readonly GlobalCommandPermissions: "The permissions of an application command belong to a guild: provide a guild, or use the permissions manager of a guild"; readonly MessageContentType: "The content of a message must be a string"; readonly MessageNonceLength: "A message nonce must be at most 25 characters long"; readonly MessageNonceType: "A message nonce must be an integer"; readonly MessageSearchContentLength: "The content of a message search cannot exceed 1024 characters"; readonly MessageSearchSlop: "The slop of a message search must be an integer from 0 to 100"; readonly MessageSearchChannelIdsLimit: "A message search cannot filter by more than 500 channels"; readonly MessageSearchLimit: "The limit of a message search must be an integer from 1 to 25"; readonly MessageSearchOffset: "The offset of a message search must be an integer from 0 to 9975"; readonly SearchIndexNotYetAvailable: (guildId: string, retryAfter: number, documentsIndexed: number) => string; readonly MessageForwardChannelMissing: "Forwarding a message by ID needs its channel"; readonly MessageReferenceMissing: (messageId: string) => string; readonly WebhookMessage: "The message was not sent by a webhook."; readonly WebhookApplication: "This message webhook belongs to an application and cannot be fetched."; readonly MessagePollMissing: (messageId: string) => string; readonly AttachmentDownloadFailed: (url: string, status: number) => string; readonly FileNotFound: (file: string) => string; readonly ReqResourceType: "The resource must be a string, a Uint8Array, an ArrayBuffer, a Blob, or a stream"; readonly VoiceStateNotOwn: "Only the bot's own voice state can request to speak"; readonly VoiceStateGuildUnknown: "This voice state does not belong to a guild"; readonly EntitlementCreateInvalidOwner: "You must provide either a guild or a user to create an entitlement, but not both"; readonly WebhookTokenUnavailable: (webhookId: string) => string; }; /** * The code of an error thrown by this package, set as its `code`. */ export type GatewayErrorCode = keyof typeof GatewayErrorMessages; /** * Every {@link GatewayErrorCode}, keyed by itself, like discord.js's `DiscordjsErrorCodes`. * * @example * ```typescript * try { * await webhook.send("Awoo"); * } catch (error) { * if (error instanceof GatewayError && error.code === GatewayErrorCodes.WebhookTokenUnavailable) { * // ... * } * } * ``` */ export declare const GatewayErrorCodes: { readonly [Code in GatewayErrorCode]: Code; }; /** * The arguments the message of `Code` is formatted with, none when the message is a plain string. */ export type GatewayErrorArgs = (typeof GatewayErrorMessages)[Code] extends ((...args: infer Args) => string) ? Args : []; /** * An {@link Error} carrying a {@link GatewayErrorCode}, like discord.js's `DiscordjsError`. * * @remarks * Its `name` is `GatewayError []`, and its message is the code's entry in {@link GatewayErrorMessages}. */ export declare class GatewayError extends Error { /** * The code of the error. */ readonly code: Code; constructor(code: Code, ...args: GatewayErrorArgs); } /** * A {@link TypeError} carrying a {@link GatewayErrorCode}, like discord.js's `DiscordjsTypeError`. */ export declare class GatewayTypeError extends TypeError { /** * The code of the error. */ readonly code: Code; constructor(code: Code, ...args: GatewayErrorArgs); } /** * A {@link RangeError} carrying a {@link GatewayErrorCode}, like discord.js's `DiscordjsRangeError`. */ export declare class GatewayRangeError extends RangeError { /** * The code of the error. */ readonly code: Code; constructor(code: Code, ...args: GatewayErrorArgs); } /** * An invite to a group direct message. Its channel (name, icon, recipients) is exposed as `channel`. */ export declare class GroupDMInvite extends BaseInvite {} /** * Builds the invite structure matching the type of a raw invite. * * @param data The raw invite. * @param relations The related structures, resolved from the cache. */ export declare function createInvite(data: InviteData, relations?: InviteRelations): BaseInvite; /** * The optional data of an {@link AttachmentBuilder}. */ export interface AttachmentBuilderData { /** * The name of the file, inferred from a path or URL when omitted. */ name?: string; /** * The description (alt text) of the file. */ description?: string; } /** * What {@link AttachmentBuilder.from} copies: an {@link AttachmentPayload}, an {@link AttachmentBuilder}, or a received * `Attachment`, whose `attachment` is its URL. */ export interface AttachmentBuilderSource { attachment: BufferResolvable; name?: string | null; description?: string | null; title?: string | null; duration?: number | null; waveform?: string | null; spoiler?: boolean; } /** * Builds a file to send with a message, like discord.js's `AttachmentBuilder`. Pass it in the `files` of a message. * * @example * ```ts * const file = new AttachmentBuilder("./howl.ogg").setDescription("A howl").setSpoiler(); * await channel.send({ content: "Awoo", files: [file] }); * ``` */ export declare class AttachmentBuilder implements JSONEncodable { /** * The contents of the file: its data, a path on disk, a URL, a stream, or a blob. */ attachment: BufferResolvable; /** * The name of the file, `undefined` to infer it from a path or URL. */ name?: string; /** * The description (alt text) of the file. */ description?: string; /** * The title of the file. */ title?: string; /** * The duration of a voice message, in seconds. */ duration?: number; /** * The waveform of a voice message, base64-encoded. */ waveform?: string; /** * Whether the file is a spoiler while it has no name to prefix with `SPOILER_`. */ private pendingSpoiler; /** * @param attachment The contents of the file. * @param data The name and description of the file. */ constructor(attachment: BufferResolvable, data?: AttachmentBuilderData); /** * Whether the file is a spoiler: its name starts with `SPOILER_`. */ get spoiler(): boolean; /** * Sets the description (alt text) of the file. * * @param description The description. */ setDescription(description: string): this; /** * Sets the contents of the file, and its name when given. * * @param attachment The contents of the file. * @param name The name of the file, kept as is when omitted. */ setFile(attachment: BufferResolvable, name?: string): this; /** * Sets the name of the file. * * @param name The name of the file. */ setName(name: string): this; /** * Marks the file as a spoiler, or not, by adding or removing the `SPOILER_` prefix of its name. * * @param spoiler Whether the file is a spoiler. */ setSpoiler(spoiler?: boolean): this; /** * Sets the title of the file. * * @param title The title. */ setTitle(title: string): this; /** * Sets the duration of a voice message. * * @param duration The duration, in seconds. */ setDuration(duration: number): this; /** * Sets the waveform of a voice message. * * @param waveform The waveform, base64-encoded. */ setWaveform(waveform: string): this; /** * The file as an {@link AttachmentPayload}. */ toJSON(): AttachmentPayload; /** * Copies a file. * * @param other The builder, payload, or received attachment to copy. */ static from(other: AttachmentBuilderSource): AttachmentBuilder; } /** * The options of {@link CollectionCache}. */ export interface CollectionCacheOptions { /** * Gets the key of raw data, for {@link CollectionCache.add}. * * @default (data) => data.id */ keyOf?: (data: Partial) => string; /** * Called with an instance every time it is read with `get` or updated with `add`, to bring what it holds besides * its data (its relations) up to date. It returns the instance to hand out. */ refresh?: (value: Value) => Value; /** * The maximum amount of entries, the oldest one being evicted when a new one would exceed it. `0` holds nothing: * `add` still builds the structure, without keeping it. * * @default Infinity */ maxSize?: number; /** * Decides which entries `maxSize` never evicts: the oldest one it answers `false` for is evicted instead. When it * answers `true` for every entry, the cache grows past `maxSize`. */ keepOverLimit?: (value: Value, key: string, cache: Map) => boolean; } /** * The default {@link Cache}: an in-memory `Collection` of structure instances, like discord.js's caches. * * @remarks * `add` patches the cached instance in place, so a reference kept by the application sees later updates. * * Every method is synchronous. Being a `Collection`, it also has `find`, `filter`, `map`, ... which return plain * collections. Instances reached by iterating carry the relations of their last `get`. */ export declare class CollectionCache, Raw extends RawAPIType = RawAPIType> extends Collection implements Cache { #private; static get [Symbol.species](): typeof Collection; readonly synchronous = true; readonly construct: StructureCreator; /** * The name of the entity this cache holds. */ readonly name: CacheEntityName; constructor(creator: StructureCreator, name: CacheEntityName, options?: CollectionCacheOptions); add(data: Partial, overwrite?: boolean): Value; get(key: string): Value | undefined; set(key: string, value: Value): this; getSize(): number; } /** * Runs a store operation, reporting its failure and resolving it to a fallback or rethrowing it. */ export type CacheGuard = (operation: CacheErrorContext["operation"], key: string | null, run: () => Awaitable, fallback: T) => Awaitable; /** * The options of {@link EntityStoreCache}. */ export interface EntityStoreCacheOptions { /** * The raw store. */ store: EntityCache; /** * Gets the key of raw data, for {@link EntityStoreCache.add}. */ keyOf: (data: Partial) => string; /** * Builds the structure of raw data read from the store, with its relations. May be asynchronous. * * @default The creator. */ hydrate?: (data: Raw) => Awaitable; /** * Whether every method answers synchronously. The structures read their relations from other stores, so a view over * a synchronous store is only synchronous when those are too. * * @default () => store.synchronous === true */ synchronous?: () => boolean; /** * Guards every store call. * * @default Lets errors through. */ guard?: CacheGuard; } /** * A {@link Cache} over a raw `@wolfstar/plugin-cache` store (in memory or Redis): the store holds raw API data, and a * structure is built on every read. * * @remarks * Unlike `CollectionCache`, two reads of the same key return two structures: do not rely on object identity. */ export declare class EntityStoreCache, Raw extends RawAPIType = RawAPIType> implements Cache { #private; readonly construct: StructureCreator; /** * The name of the entity this cache holds. */ readonly name: CacheEntityName; /** * The raw store. */ readonly store: EntityCache; constructor(creator: StructureCreator, name: CacheEntityName, options: EntityStoreCacheOptions); get synchronous(): boolean; add(data: Partial, overwrite?: boolean): Awaitable; clear(): Awaitable; delete(key: string): Awaitable; get(key: string): Awaitable; getSize(): Awaitable; has(key: string): Awaitable; set(key: string, value: Value): Awaitable; } /** * The options of {@link NullCache}. */ export interface NullCacheOptions { /** * Builds the structure {@link NullCache.add} answers with, with its relations. May be asynchronous. * * @default The creator. */ hydrate?: (data: Raw) => Awaitable; /** * Whether `hydrate` answers synchronously. * * @default () => true */ synchronous?: () => boolean; } /** * The {@link Cache} of an entity that is not cached: always empty, writes are dropped. */ export declare class NullCache, Raw extends RawAPIType = RawAPIType> implements Cache { #private; readonly construct: StructureCreator; /** * The name of the entity this cache stands for. */ readonly name: CacheEntityName; constructor(creator: StructureCreator, name: CacheEntityName, options?: NullCacheOptions); get synchronous(): boolean; add(data: Partial): Awaitable; clear(): void; delete(): boolean; get(): undefined; getSize(): number; has(): boolean; set(): this; } /** * Gets the {@link GatewayClient} registered in the framework's container. * * @remarks * The framework's `Client` registers itself as `container.client` on construction, so this is the most recently * constructed `GatewayClient`. It throws when that client is a plain `Client`. */ export declare function getGatewayClient(): GatewayClient; declare module "@sapphire/pieces" { interface Container { /** * The most recently constructed {@link GatewayClient}, which registers itself here on construction next to * `container.client`, so pieces reach its managers without {@link getGatewayClient} or a cast. * * @remarks * `container.client` keeps the framework's `Client` type: a module augmentation cannot redeclare a property with * another type (TS2717), and under `skipLibCheck` the framework's declaration silently wins. */ gatewayClient: GatewayClient; } } type ListenerConstructor = new (...args: any[]) => EventGatewayListener; /** * Class decorator that binds the decorated {@link EventGatewayListener} to a gateway event, so it does not need to * declare a constructor. * * @example * ```typescript * import { EventGatewayListener, RegisterAsGatewayListener, type Message } from '@wolfstar/plugin-gateway'; * * @RegisterAsGatewayListener('messageCreate') * export class LogMessagesListener extends EventGatewayListener<'messageCreate'> { * public override run(message: Message) { * console.log(`${message.author.username}: ${message.content}`); * } * } * ``` * * @param event The event to listen to. * @param options The additional listener options. */ export declare function RegisterAsGatewayListener(event: Event, options?: Omit, "event">): (target: T) => T; /** * Like {@link RegisterAsGatewayListener}, for an event that comes from a dispatch, but the listener only runs on one * process: the workers replaying the dispatches while the gateway client forwards them (see `forwardGatewayDispatches` * from `@wolfstar/plugin-broker`), the gateway client itself otherwise. A bot loading the same pieces on both * processes therefore handles each dispatch once, without reading its environment to tell which process it is on. * * @remarks * The decision is made on every emit, so it does not matter whether the forwarding starts before or after the * listener is loaded, and stopping it brings the listener back. A `once` listener is not spent while it idles. * * The events only the gateway client emits (`clientReady`, `shardReady`, `shardResume`, `shardClose`, `shardError`, * `dispatch`, `cacheError`, `cacheSweep`) are never replayed on a worker: they are rejected by the types, and the * decorator throws for them. Use {@link RegisterAsGatewayListener} for those. * * Only the dispatches that are forwarded reach the workers: with `forwardGatewayDispatches`'s `events` set, a listener * of an event built from another dispatch runs nowhere. A `guildDelete` that `READY` emits for the guilds it no longer * lists is not forwarded either (wolfstar-project/plugins#243), so a listener on the workers misses it. Delivery to the * workers is at-least-once, so the listener should be idempotent. * * @example * ```typescript * import { EventGatewayListener, RegisterAsDispatchListener, type Message } from '@wolfstar/plugin-gateway'; * * @RegisterAsDispatchListener('messageCreate') * export class LogMessagesListener extends EventGatewayListener<'messageCreate'> { * public override run(message: Message) { * console.log(`${message.author.username}: ${message.content}`); * } * } * ``` * * @param event The dispatch event to listen to. * @param options The additional listener options. * @throws {TypeError} When the event is one only the gateway client emits. */ export declare function RegisterAsDispatchListener(event: Event, options?: Omit, "event">): (target: T) => T; /** * Carries the previous state a dispatch handler reads before the cache write (`DispatchHandler#before`) across * processes: {@link DispatchStateCodec.serialize} turns it into plain, codec-safe data on the gateway process, and * {@link DispatchStateCodec.revive} builds the structures again on a worker. */ export interface DispatchStateCodec { serialize(state: unknown): unknown; /** * @param client The client of the worker. * @param state What `serialize` returned, after a trip through the wire. * @param data The dispatch data. */ revive(client: GatewayClient, state: unknown, data: any): Awaitable; } /** * How the state of each dispatch type that has a `before` travels, see {@link DispatchStateCodec}. * * @remarks * A handler that gains a `before` needs an entry here; `tests/dispatch-state.test.ts` fails otherwise. */ export declare const DispatchStateCodecs: { [Type in GatewayDispatchEvents]?: DispatchStateCodec; }; /** * Compares two JSON-like values structurally, regardless of key order. `undefined` properties count as missing, like * they do once serialized. * * @param a The first value. * @param b The second value. */ export declare function isDeepEqual(a: unknown, b: unknown): boolean; /** * Emitted as an `error` when a dispatch takes longer than `GatewayClientOptions.dispatchTimeout` to process. * * @remarks * The dispatch is not cancelled: it keeps running, and later dispatches of its partition keep waiting for it, so the * event order is preserved. The error only reports that the partition is stuck, usually on a slow or unreachable * cache. */ export declare class DispatchTimeoutError extends GatewayError<"DispatchTimeout"> { /** * The type of the slow dispatch, e.g. `MESSAGE_CREATE`. */ readonly type: string; /** * The shard the dispatch was received on. */ readonly shardId: number; /** * The partition the dispatch runs in, `null` for a barrier. */ readonly partition: string | null; /** * The timeout that was exceeded, in milliseconds. */ readonly timeout: number; constructor(type: string, shardId: number, partition: string | null, timeout: number); } /** * Thrown by `GuildMemberManager#request` when Discord stops sending the chunks of the requested members. * * @remarks * The request is dropped: chunks arriving later still update the cache and emit `guildMembersChunk`. */ export declare class GuildMembersTimeoutError extends GatewayError<"GuildMembersTimeout"> { /** * The ID of the guild whose members were requested. */ readonly guildId: string; /** * The nonce of the request. */ readonly nonce: string; /** * The timeout that was exceeded, in milliseconds. */ readonly timeout: number; constructor(guildId: string, nonce: string, timeout: number); } /** * Thrown by `ChannelManager#requestInfo` when Discord does not answer with the `CHANNEL_INFO` of the guild. * * @remarks * The request is dropped: a reply arriving later still updates the cache and emits `channelInfo`. When another request * for the guild is queued, that reply also resolves it, as the reply carries no nonce to tell them apart. */ export declare class GuildChannelInfoTimeoutError extends GatewayError<"GuildChannelInfoTimeout"> { /** * The ID of the guild whose channel info was requested. */ readonly guildId: string; /** * The timeout that was exceeded, in milliseconds. */ readonly timeout: number; constructor(guildId: string, timeout: number); } /** * Thrown by `GuildManager#fetchSoundboardSounds` when Discord does not answer with the sounds of every requested guild. * * @remarks * The request is dropped: replies arriving later still update the cache and emit `soundboardSounds`. */ export declare class GuildSoundboardSoundsTimeoutError extends GatewayError<"GuildSoundboardSoundsTimeout"> { /** * The IDs of the guilds whose sounds did not arrive. */ readonly guildIds: readonly string[]; /** * The timeout that was exceeded, in milliseconds. */ readonly timeout: number; constructor(guildIds: readonly string[], timeout: number); } /** * Thrown by `GuildMemberManager#request` when Discord answers with `RATE_LIMITED` instead of the members' chunks. */ export declare class GuildMembersRateLimitError extends GatewayError<"GuildMembersRateLimited"> { /** * The ID of the guild whose members were requested. */ readonly guildId: string; /** * The nonce of the request. */ readonly nonce: string; /** * How long to wait before requesting the members again, in milliseconds. */ readonly retryAfter: number; constructor(guildId: string, nonce: string, retryAfter: number); } /** * Emitted as an `error` when `GatewayClientOptions.sessionStore` fails to read or write the session of a shard. * * @remarks * Neither failure stops the shard: a failed (or timed out) read identifies instead of resuming, and a failed write * only means the session may not be resumed after a restart. The store's error is the `cause`. */ export declare class GatewaySessionStoreError extends GatewayError<"SessionStoreFailed"> { /** * Whether the store failed to read (`"get"`) or write (`"set"`) the session. */ readonly operation: "get" | "set"; /** * The shard whose session was read or written. */ readonly shardId: number; constructor(operation: "get" | "set", shardId: number, cause: unknown); } /** * Builds the {@link GatewayClientOptions.cacheOptions} bounding the caches of some entities, like discord.js's * `Options.cacheWithLimits`. A number is the `maxSize` of the entity, an object is its whole options. * * @example * ```typescript * const client = new GatewayClient({ * intents, * // Keep the 200 most recent messages, no presences, and up to 1000 members, plus any member in a voice channel. * cacheOptions: cacheWithLimits({ * messages: 200, * presences: 0, * members: { maxSize: 1_000, keepOverLimit: (member) => member.voice?.channelId != null }, * }), * }); * ``` * * @param limits The `maxSize` or the options of each entity. */ export declare function cacheWithLimits(limits: Partial>): Partial>; /** * Ready-made {@link GatewayClientOptions.sweepers}, for a bot that only needs recent messages and threads: every hour, * messages untouched for 30 minutes are evicted, and so are threads archived for more than four hours. * * @remarks * Unlike discord.js's `Options.DefaultSweeperSettings`, which is empty, it sweeps. Spread it to override an entity: * `sweepers: { ...DefaultSweeperSettings, users: { interval: 3_600, filter: () => (user) => user.bot } }`. */ export declare const DefaultSweeperSettings: SweeperOptions; /** * What {@link computeGuildPermissions} needs to know about a member of a guild. */ export interface GuildPermissionsContext { guildId: Snowflake; ownerId: Snowflake; userId: Snowflake; /** * The IDs of the member's roles, without `@everyone`. */ memberRoleIds: readonly Snowflake[]; /** * Every role of the guild, `@everyone` (whose ID is the guild's) included. */ roles: readonly Pick[]; } /** * Computes a member's guild-wide permissions, the way Discord does before channel overwrites apply: the owner and * administrators get every permission, everyone else gets `@everyone`'s permissions combined with their roles'. * * @param context The member and the guild's roles. */ export declare function computeGuildPermissions(context: GuildPermissionsContext): PermissionsBitField; /** * Compares two roles the way Discord orders them: by position, then by ID for equal positions (older first). * * @returns A negative number when `a` is lower than `b`, a positive one when it is higher, `0` when they are the same. */ export declare function compareRolePositions(a: Pick, b: Pick): number; /** * What {@link computeChannelPermissions} needs to know about a channel and whom the permissions are for. */ export interface ChannelPermissionsContext { guildId: Snowflake; /** * The ID of the member, whose own overwrite applies last. Absent when computing a role's permissions. */ userId?: Snowflake; /** * The IDs of the roles whose overwrites apply, without `@everyone`. */ roleIds: readonly Snowflake[]; overwrites: readonly APIOverwrite[]; } /** * Applies a channel's permission overwrites to guild-wide permissions, the way Discord does: administrators keep * every permission, then the `@everyone` overwrite applies, then the roles' overwrites (combined), then the member's. * * @param base The guild-wide permissions, from {@link computeGuildPermissions}. * @param context The channel's overwrites, and the member or role. */ export declare function computeChannelPermissions(base: Readonly, context: ChannelPermissionsContext): PermissionsBitField; /** * Computes the permissions of a member or role in a channel, given the channel's overwrites. * * @param guildId The ID of the channel's guild. * @param overwrites The channel's permission overwrites. * @param target A member, a role, or the ID of a member. */ export declare function computeTargetPermissions(guildId: Snowflake, overwrites: readonly APIOverwrite[], target: GuildMember | Role | Snowflake): Promise; /** * Computes the permissions of a member or role in a channel, fetching the channel if needed. Threads use their parent * channel's overwrites, like Discord does. * * @param channel The channel, or its ID. * @param target A member, a role, or the ID of a member. */ export declare function computePermissionsIn(channel: AnyChannel | Snowflake, target: GuildMember | Role | Snowflake): Promise; /** * Gets a guild from the cache, for the getters that cannot answer without it. Synchronous when the cache is. * * @param client The client. * @param guildId The ID of the guild. * @throws A `GatewayError` (`GuildUncached`) when the guild is not cached. * @internal */ export declare function requireGuild(client: GatewayClient, guildId: Snowflake): Awaitable; /** * Gets the bot's own member of a guild from the cache, for the getters checking what the bot can do. Synchronous * when the cache is. * * @param client The client. * @param guildId The ID of the guild. * @throws A `GatewayError` (`GuildUncachedMe`) when the member is not cached. * @internal */ export declare function requireMe(client: GatewayClient, guildId: Snowflake): Awaitable; /** * {@link computeTargetPermissions} from the cache alone, never the API. Synchronous when the cache is. * * @param guildId The ID of the channel's guild. * @param overwrites The channel's permission overwrites. * @param target A member, a role, or the ID of a cached member. * @param client The client whose cache is read: the target's own by default, or the most recently constructed one * for an ID. * @throws A `GatewayError` (`GuildMemberUncached`, `GuildUncached`) when a needed entity is not cached. */ export declare function computeCachedTargetPermissions(guildId: Snowflake, overwrites: readonly APIOverwrite[], target: GuildMember | Role | Snowflake, client?: GatewayClient): Awaitable; /** * {@link computePermissionsIn} from the cache alone, never the API: the channel, and the parent of a thread, are * read from it. Synchronous when the cache is. * * @param channel The channel, or the ID of a cached one. * @param target A member, a role, or the ID of a cached member. * @throws A `GatewayError` (`ChannelUncached`, `GuildMemberUncached`, `GuildUncached`) when a needed entity is not * cached. */ export declare function computeCachedPermissionsIn(channel: AnyChannel | Snowflake, target: GuildMember | Role | Snowflake): Awaitable; /** * An emoji parsed from a string: a Unicode emoji has no `id`. */ export interface PartialEmoji { animated: boolean; name: string; id: Snowflake | undefined; } /** * An emoji known only by its ID. */ export interface PartialEmojiOnlyId { id: Snowflake; } /** * Parses an emoji out of a string: a Unicode emoji (URL-encoded or not), a custom emoji mention (``), or a * `name:id` pair. * * @param text The string to parse. * @returns The emoji, or `null` when the string holds a colon but no custom emoji. */ export declare function parseEmoji(text: string): PartialEmoji | null; /** * Resolves an emoji from anything {@link EmojiIdentifierResolvable}, without looking it up in a cache. * * @param emoji The emoji to resolve. * @returns The emoji, only its ID when given a bare ID, or `null` when the value identifies no emoji. */ export declare function resolvePartialEmoji(emoji: EmojiIdentifierResolvable): PartialEmoji | PartialEmojiOnlyId | null; /** * Resolves a {@link ColorResolvable} to its number. * * @param color The color to resolve. * @throws A `TypeError` when the value is no color, a `RangeError` when it is outside `0x000000`-`0xffffff`. */ export declare function resolveColor(color: ColorResolvable): number; /** * Flattens an object for serialization, like discord.js's `flatten`: maps become the array of their keys, arrays are * flattened element by element, objects with a `toJSON` are replaced by its result, and keys starting with `_` are * dropped. * * @param object The object to flatten. * @param props Specific properties to include (`true`), exclude (`false`), or rename (a string). */ export declare function flatten(object: unknown, ...props: Record[]): Record; /** * Names by ID, as a map or a plain object. */ export type NamesById = ReadonlyMap | Readonly>; /** * The names to replace mentions with in {@link cleanContent}, by ID. A mention whose ID has no name is kept. */ export interface CleanContentNames { /** * The display names of users, used for `<@id>` and `<@!id>` when `members` has none. */ users?: NamesById; /** * The display names of guild members, preferred over `users`. */ members?: NamesById; /** * The names of roles, used for `<@&id>`. */ roles?: NamesById; /** * The names of channels, used for `<#id>`. */ channels?: NamesById; } /** * Replaces the mentions of a string with the text they display, like discord.js's `cleanContent`: `@name`, `@role`, * `#channel`, `/command`, and `:emoji:`. * * @remarks * discord.js reads the names from its synchronous cache. The cache of this package is asynchronous, so the names * are passed in instead; `Message#cleanContent` does it with the message's own mentions. * @param text The string to clean. * @param names The names to replace mentions with, by ID. */ export declare function cleanContent(text: string, names?: CleanContentNames): string; /** * Escapes the code block fences of a string, to put it in a code block. * * @param text The string to escape. */ export declare function cleanCodeBlockContent(text: string): string; /** * The ID and token of a webhook. */ export interface WebhookDataIdWithToken { id: string; token: string; } /** * Parses a webhook URL for its ID and token. * * @param url The URL to parse. * @returns The ID and token, `null` when the URL is no webhook URL. */ export declare function parseWebhookURL(url: string): WebhookDataIdWithToken | null; /** * Verifies that a value is a string, throwing otherwise. * * @param data The value to verify. * @param error The constructor of the error to throw. * @param errorMessage The message of the error to throw. * @param allowEmpty Whether an empty string is allowed. */ export declare function verifyString(data: unknown, error?: new (message: string) => Error, errorMessage?: string, allowEmpty?: boolean): string; /** * Something Discord sorts by position and ID: a role or a guild channel. */ export interface Positioned { id: string; position?: number | null; rawPosition?: number | null; type?: unknown; } /** * Sorts roles or guild channels the way Discord displays them, like discord.js's `discordSort`: by position, then by * ID, ascending for channels and descending for roles (told apart by channels having a `type`). * * @param items The roles or channels to sort, or a map of them. * @returns A new sorted array. */ export declare function discordSort(items: Iterable | ReadonlyMap): Item[]; /** * Moves an element of an array in place. * * @param array The array. * @param element The element to move. * @param newIndex The index to move it to, or the offset to move it by. * @param offset Whether `newIndex` is an offset. * @returns The new index of the element. */ export declare function moveElementInArray(array: Element[], element: Element, newIndex: number, offset?: boolean): number; /** * Gets the channel types sorted together with a channel type: text-like channels are listed above voice ones, and * categories on their own. * * @param type The type of the channel. */ export declare function getSortableGroupTypes(type: ChannelType): readonly ChannelType[]; /** * The plain information of an error, e.g. to send it to another process. */ export interface MakeErrorOptions { name: string; message: string; stack?: string; } /** * Makes an error from its plain information. * * @param options The error's name, message, and stack. */ export declare function makeError(options: MakeErrorOptions): Error; /** * Gets the plain information of an error. * * @param error The error. */ export declare function makePlainError(error: Error): MakeErrorOptions; /** * Gets the name of a path or URL without its query string, like discord.js's `basename`. * * @param path The path or URL. * @param ext The extension to remove, if the name has it. */ export declare function basename(path: string, ext?: string): string; /** * Finds the name of a file to attach: the name of a path or URL, or of a stream's `path`, `file.jpg` otherwise. * * @param thing The file. */ export declare function findName(thing: unknown): string; /** * Finds a custom emoji by its ID in the cache of every guild, like discord.js's `resolveGuildEmoji`. * * @remarks * Emojis are cached per guild, so it enumerates the whole emoji cache: it needs a store able to list its entries, and * never calls the API. * * @param client The client whose cache to search. * @param emojiId The ID of the emoji. * @returns The emoji, `null` when no cached guild has it. * @throws {TypeError} When the emoji cache cannot enumerate its entries. */ export declare function resolveGuildEmoji(client: GatewayClient, emojiId: Snowflake): Promise; /** * Resolves a SKU, or its ID, to its ID. * * @param resolvable The SKU or its ID. * @returns The ID, `null` when the value is neither. */ export declare function resolveSKUId(resolvable: SKUResolvable): string | null; /** * Computes the positions to send to Discord to move a role or channel among its sorted siblings: the body discord.js's * `setPosition` sends. * * @param id The ID of the role or channel to move. * @param position The index to move it to, or the offset to move it by with `relative`. * @param relative Whether `position` is relative to its current index. * @param sorted The role or channel and its siblings, sorted with {@link discordSort}. * @returns Every sibling, with its index as its new position. * @internal */ export declare function computePositions(id: Snowflake, position: number, relative: boolean, sorted: readonly { id: Snowflake; }[]): { id: Snowflake; position: number; }[]; /** * The data {@link transformResolved} resolves: each entry is either an ID, read from the cache, or raw API data, * resolved to its cached structure or built from the data when it is not cached. */ export interface ResolvableData { users?: Iterable; /** * The members of {@link SupportingResolvedData.guildId}: their raw data needs its `user`. */ members?: Iterable>; /** * The roles of {@link SupportingResolvedData.guildId}. */ roles?: Iterable>; channels?: Iterable; /** * The messages, e.g. an interaction's `resolved.messages`: IDs are read from the cache of * {@link SupportingResolvedData.channelId}, raw data (which carries its own `channel_id`) is resolved to the cached * message or built from the data. */ messages?: Iterable; /** * The raw attachments, e.g. an interaction's `resolved.attachments`. Nothing caches attachments, so they are always * built. */ attachments?: Iterable; } /** * The context {@link transformResolved} resolves data in. */ export interface SupportingResolvedData { client: GatewayClient; /** * The guild of the members and roles: without it, they are not resolved. */ guildId?: Snowflake | null; /** * The channel the message IDs belong to: without it, only the messages given as raw data are resolved. */ channelId?: Snowflake | null; } /** * The structures {@link transformResolved} resolved, by ID. */ export interface TransformedResolvedData { users?: Map; members?: Map; roles?: Map; channels?: Map; messages?: Map; attachments?: Map; } /** * Resolves the users, members, roles, channels, messages, and attachments some data refers to into structures, like * discord.js's `transformResolved`. `client.messages` builds the relations of a message's `MessageMentions` with it. * * @remarks * Nothing is written to the cache. Synchronous when every cache it reads is. * * @param supportingData The client, the guild of the members and roles, and the channel of the message IDs. * @param data The IDs or raw data to resolve. * @returns A map for each kind of data given, keyed by ID, without duplicates nor the IDs that are not cached. */ export declare function transformResolved({ client, guildId, channelId }: SupportingResolvedData, { users, members, roles, channels, messages, attachments }: ResolvableData): Awaitable; export { type AllowedPartial, type AnnouncementChannelResolvable, type ApplicationCommandDataResolvable, type ApplicationCommandPermissionIdResolvable, type ApplicationCommandResolvable, type ApplicationResolvable, type AttachmentPayload, type AttachmentResolvable, type AutoModerationRuleResolvable, type BaseMessageOptions, BitField, type BitFieldResolvable, type BufferResolvable, type Cache, type CacheConstructor, type CacheConstructorOptions, type CacheEntityOptions, type CacheRead, type CacheReadOf, type CategoryChannelResolvable, type ChannelResolvable, type ColorResolvable, type CommandOptionDataTypeResolvable, type ComponentEmojiResolvable, type DateResolvable, type EmojiResolvable, type EntitlementResolvable, type ForwardOptions, type GatewayCacheConfig, type GatewayClientMessageDefaults, type GuildAuditLogsResolvable, type GuildBanResolvable, type GuildBasedChannel, type GuildChannelResolvable, type GuildInvitableChannel, type GuildInvitableChannelResolvable, type GuildInviteResolvable, type GuildResolvable, type GuildScheduledEventResolvable, type GuildSearchMessagesOptions, type GuildSearchMessagesResult, type GuildTemplateResolvable, type GuildTextBasedChannel, type GuildTextChannelResolvable, type GuildVoiceChannelResolvable, type HexColorString, type If, type InviteResolvable, type JSONEncodable, type MessageActionRowComponentResolvable, type MessageCreateOptions, type MessageEditOptions, type MessageMentionOptions, type MessagePayloadContext, type MessagePayloadOptions, type MessagePayloadResolvable, type MessageReactionResolvable, type MessageResolvable, type MessageTarget, type NonThreadGuildBasedChannel, type OverwriteResolvable, type Partialize, type PermissionOverwriteResolvable, PermissionsBitField, type PollCreateData, type PresenceResolvable, type RawAPIType, type ReplyOptions, type ResolvedMessagePayload, type RoleColorsEditResolvable, type RoleColorsResolvable, type RoleResolvable, type RoleResolvables, type SKUResolvable, type ScopedCache, type SoundboardSoundResolvable, type StageChannelResolvable, type StageInstanceResolvable, type StickerResolvable, type StructureCreator, type SubscriptionResolvable, type TextBasedChannel, type TextBasedChannelResolvable, type TextChannelResolvable, type ThreadChannel, type ThreadChannelResolvable, type ThreadMemberResolvable, type UserResolvable, type VoiceBasedChannel, type VoiceChannelResolvable, type WebhookMessageCreateOptions, type WebhookMessageEditOptions, type WebhookMessageOptions, type WebhookThreadOptions, type cacheRead, type cachedChannel, type cachedGuild, type cachedMember, type cachedMessage, type cachedPresence, type cachedRole, type cachedUser, type cachedVoiceState, type isPromiseLike, type peekCache, type pickCached, type readCached, type refreshRelations, type scopeCache, type syncOnly, type whenAll, type whenCachedMap }; //# sourceMappingURL=index.d.ts.map