lolka.js 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (337) hide show
  1. package/LICENSE +191 -0
  2. package/README.md +148 -0
  3. package/package.json +104 -0
  4. package/src/client/Client.js +943 -0
  5. package/src/client/actions/Action.js +151 -0
  6. package/src/client/actions/ActionsManager.js +75 -0
  7. package/src/client/actions/ChannelCreate.js +25 -0
  8. package/src/client/actions/ChannelDelete.js +24 -0
  9. package/src/client/actions/ChannelUpdate.js +42 -0
  10. package/src/client/actions/GuildChannelsPositionUpdate.js +21 -0
  11. package/src/client/actions/GuildEmojiCreate.js +21 -0
  12. package/src/client/actions/GuildEmojiDelete.js +20 -0
  13. package/src/client/actions/GuildEmojiUpdate.js +21 -0
  14. package/src/client/actions/GuildEmojisUpdate.js +34 -0
  15. package/src/client/actions/GuildMemberRemove.js +33 -0
  16. package/src/client/actions/GuildMemberUpdate.js +45 -0
  17. package/src/client/actions/GuildRoleCreate.js +27 -0
  18. package/src/client/actions/GuildRoleDelete.js +30 -0
  19. package/src/client/actions/GuildRolesPositionUpdate.js +21 -0
  20. package/src/client/actions/GuildScheduledEventDelete.js +32 -0
  21. package/src/client/actions/GuildScheduledEventUserAdd.js +33 -0
  22. package/src/client/actions/GuildScheduledEventUserRemove.js +33 -0
  23. package/src/client/actions/GuildSoundboardSoundDelete.js +30 -0
  24. package/src/client/actions/GuildStickerCreate.js +21 -0
  25. package/src/client/actions/GuildStickerDelete.js +20 -0
  26. package/src/client/actions/GuildStickerUpdate.js +21 -0
  27. package/src/client/actions/GuildStickersUpdate.js +34 -0
  28. package/src/client/actions/GuildUpdate.js +34 -0
  29. package/src/client/actions/InteractionCreate.js +110 -0
  30. package/src/client/actions/MessageCreate.js +43 -0
  31. package/src/client/actions/MessageDelete.js +33 -0
  32. package/src/client/actions/MessageDeleteBulk.js +49 -0
  33. package/src/client/actions/MessagePollVoteAdd.js +41 -0
  34. package/src/client/actions/MessagePollVoteRemove.js +39 -0
  35. package/src/client/actions/MessageReactionAdd.js +72 -0
  36. package/src/client/actions/MessageReactionRemove.js +51 -0
  37. package/src/client/actions/MessageReactionRemoveAll.js +34 -0
  38. package/src/client/actions/MessageReactionRemoveEmoji.js +29 -0
  39. package/src/client/actions/MessageUpdate.js +26 -0
  40. package/src/client/actions/StageInstanceCreate.js +29 -0
  41. package/src/client/actions/StageInstanceDelete.js +32 -0
  42. package/src/client/actions/StageInstanceUpdate.js +31 -0
  43. package/src/client/actions/ThreadCreate.js +26 -0
  44. package/src/client/actions/ThreadMembersUpdate.js +49 -0
  45. package/src/client/actions/TypingStart.js +30 -0
  46. package/src/client/actions/UserUpdate.js +37 -0
  47. package/src/client/voice/ClientVoiceManager.js +48 -0
  48. package/src/client/websocket/handlers/APPLICATION_COMMAND_PERMISSIONS_UPDATE.js +30 -0
  49. package/src/client/websocket/handlers/AUTO_MODERATION_ACTION_EXECUTION.js +18 -0
  50. package/src/client/websocket/handlers/AUTO_MODERATION_RULE_CREATE.js +19 -0
  51. package/src/client/websocket/handlers/AUTO_MODERATION_RULE_DELETE.js +22 -0
  52. package/src/client/websocket/handlers/AUTO_MODERATION_RULE_UPDATE.js +21 -0
  53. package/src/client/websocket/handlers/CHANNEL_CREATE.js +5 -0
  54. package/src/client/websocket/handlers/CHANNEL_DELETE.js +5 -0
  55. package/src/client/websocket/handlers/CHANNEL_PINS_UPDATE.js +23 -0
  56. package/src/client/websocket/handlers/CHANNEL_UPDATE.js +17 -0
  57. package/src/client/websocket/handlers/ENTITLEMENT_CREATE.js +15 -0
  58. package/src/client/websocket/handlers/ENTITLEMENT_DELETE.js +19 -0
  59. package/src/client/websocket/handlers/ENTITLEMENT_UPDATE.js +17 -0
  60. package/src/client/websocket/handlers/GUILD_AUDIT_LOG_ENTRY_CREATE.js +20 -0
  61. package/src/client/websocket/handlers/GUILD_BAN_ADD.js +16 -0
  62. package/src/client/websocket/handlers/GUILD_BAN_REMOVE.js +21 -0
  63. package/src/client/websocket/handlers/GUILD_CREATE.js +35 -0
  64. package/src/client/websocket/handlers/GUILD_DELETE.js +37 -0
  65. package/src/client/websocket/handlers/GUILD_EMOJIS_UPDATE.js +5 -0
  66. package/src/client/websocket/handlers/GUILD_INTEGRATIONS_UPDATE.js +16 -0
  67. package/src/client/websocket/handlers/GUILD_MEMBERS_CHUNK.js +41 -0
  68. package/src/client/websocket/handlers/GUILD_MEMBER_ADD.js +18 -0
  69. package/src/client/websocket/handlers/GUILD_MEMBER_REMOVE.js +5 -0
  70. package/src/client/websocket/handlers/GUILD_MEMBER_UPDATE.js +5 -0
  71. package/src/client/websocket/handlers/GUILD_ROLE_CREATE.js +5 -0
  72. package/src/client/websocket/handlers/GUILD_ROLE_DELETE.js +5 -0
  73. package/src/client/websocket/handlers/GUILD_ROLE_UPDATE.js +22 -0
  74. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_CREATE.js +18 -0
  75. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_DELETE.js +5 -0
  76. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_UPDATE.js +20 -0
  77. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_USER_ADD.js +5 -0
  78. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_USER_REMOVE.js +5 -0
  79. package/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUNDS_UPDATE.js +25 -0
  80. package/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_CREATE.js +19 -0
  81. package/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_DELETE.js +5 -0
  82. package/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_UPDATE.js +21 -0
  83. package/src/client/websocket/handlers/GUILD_STICKERS_UPDATE.js +5 -0
  84. package/src/client/websocket/handlers/GUILD_UPDATE.js +5 -0
  85. package/src/client/websocket/handlers/INTERACTION_CREATE.js +5 -0
  86. package/src/client/websocket/handlers/INVITE_CREATE.js +21 -0
  87. package/src/client/websocket/handlers/INVITE_DELETE.js +24 -0
  88. package/src/client/websocket/handlers/MESSAGE_CREATE.js +5 -0
  89. package/src/client/websocket/handlers/MESSAGE_DELETE.js +5 -0
  90. package/src/client/websocket/handlers/MESSAGE_DELETE_BULK.js +5 -0
  91. package/src/client/websocket/handlers/MESSAGE_POLL_VOTE_ADD.js +5 -0
  92. package/src/client/websocket/handlers/MESSAGE_POLL_VOTE_REMOVE.js +5 -0
  93. package/src/client/websocket/handlers/MESSAGE_REACTION_ADD.js +5 -0
  94. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE.js +5 -0
  95. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE_ALL.js +5 -0
  96. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE_EMOJI.js +5 -0
  97. package/src/client/websocket/handlers/MESSAGE_UPDATE.js +17 -0
  98. package/src/client/websocket/handlers/PRESENCE_UPDATE.js +43 -0
  99. package/src/client/websocket/handlers/RATE_LIMITED.js +24 -0
  100. package/src/client/websocket/handlers/READY.js +30 -0
  101. package/src/client/websocket/handlers/SOUNDBOARD_SOUNDS.js +25 -0
  102. package/src/client/websocket/handlers/STAGE_INSTANCE_CREATE.js +5 -0
  103. package/src/client/websocket/handlers/STAGE_INSTANCE_DELETE.js +5 -0
  104. package/src/client/websocket/handlers/STAGE_INSTANCE_UPDATE.js +5 -0
  105. package/src/client/websocket/handlers/SUBSCRIPTION_CREATE.js +15 -0
  106. package/src/client/websocket/handlers/SUBSCRIPTION_DELETE.js +17 -0
  107. package/src/client/websocket/handlers/SUBSCRIPTION_UPDATE.js +17 -0
  108. package/src/client/websocket/handlers/THREAD_CREATE.js +5 -0
  109. package/src/client/websocket/handlers/THREAD_DELETE.js +18 -0
  110. package/src/client/websocket/handlers/THREAD_LIST_SYNC.js +52 -0
  111. package/src/client/websocket/handlers/THREAD_MEMBERS_UPDATE.js +5 -0
  112. package/src/client/websocket/handlers/THREAD_MEMBER_UPDATE.js +26 -0
  113. package/src/client/websocket/handlers/THREAD_UPDATE.js +17 -0
  114. package/src/client/websocket/handlers/TYPING_START.js +5 -0
  115. package/src/client/websocket/handlers/USER_UPDATE.js +5 -0
  116. package/src/client/websocket/handlers/VOICE_CHANNEL_EFFECT_SEND.js +17 -0
  117. package/src/client/websocket/handlers/VOICE_SERVER_UPDATE.js +33 -0
  118. package/src/client/websocket/handlers/VOICE_STATE_UPDATE.js +38 -0
  119. package/src/client/websocket/handlers/WEBHOOKS_UPDATE.js +17 -0
  120. package/src/client/websocket/handlers/index.js +78 -0
  121. package/src/errors/DJSError.js +52 -0
  122. package/src/errors/ErrorCodes.js +280 -0
  123. package/src/errors/Messages.js +159 -0
  124. package/src/errors/index.js +7 -0
  125. package/src/index.js +261 -0
  126. package/src/managers/ApplicationCommandManager.js +305 -0
  127. package/src/managers/ApplicationCommandPermissionsManager.js +452 -0
  128. package/src/managers/ApplicationEmojiManager.js +152 -0
  129. package/src/managers/AutoModerationRuleManager.js +310 -0
  130. package/src/managers/BaseManager.js +21 -0
  131. package/src/managers/CachedManager.js +68 -0
  132. package/src/managers/CategoryChannelChildManager.js +85 -0
  133. package/src/managers/ChannelManager.js +197 -0
  134. package/src/managers/DMMessageManager.js +19 -0
  135. package/src/managers/DataManager.js +66 -0
  136. package/src/managers/EntitlementManager.js +185 -0
  137. package/src/managers/GuildApplicationCommandManager.js +31 -0
  138. package/src/managers/GuildBanManager.js +224 -0
  139. package/src/managers/GuildChannelManager.js +556 -0
  140. package/src/managers/GuildEmojiManager.js +264 -0
  141. package/src/managers/GuildEmojiRoleManager.js +136 -0
  142. package/src/managers/GuildForumThreadManager.js +88 -0
  143. package/src/managers/GuildInviteManager.js +239 -0
  144. package/src/managers/GuildManager.js +268 -0
  145. package/src/managers/GuildMemberManager.js +622 -0
  146. package/src/managers/GuildMemberRoleManager.js +232 -0
  147. package/src/managers/GuildMessageManager.js +35 -0
  148. package/src/managers/GuildScheduledEventManager.js +333 -0
  149. package/src/managers/GuildSoundboardSoundManager.js +226 -0
  150. package/src/managers/GuildStickerManager.js +195 -0
  151. package/src/managers/GuildTextThreadManager.js +95 -0
  152. package/src/managers/MessageManager.js +355 -0
  153. package/src/managers/PartialGroupDMMessageManager.js +19 -0
  154. package/src/managers/PermissionOverwriteManager.js +177 -0
  155. package/src/managers/PollAnswerVoterManager.js +62 -0
  156. package/src/managers/PresenceManager.js +63 -0
  157. package/src/managers/ReactionManager.js +75 -0
  158. package/src/managers/ReactionUserManager.js +85 -0
  159. package/src/managers/RoleManager.js +446 -0
  160. package/src/managers/StageInstanceManager.js +169 -0
  161. package/src/managers/SubscriptionManager.js +86 -0
  162. package/src/managers/ThreadManager.js +213 -0
  163. package/src/managers/ThreadMemberManager.js +197 -0
  164. package/src/managers/UserManager.js +149 -0
  165. package/src/managers/VoiceStateManager.js +64 -0
  166. package/src/sharding/Shard.js +506 -0
  167. package/src/sharding/ShardClientUtil.js +292 -0
  168. package/src/sharding/ShardingManager.js +390 -0
  169. package/src/structures/ActionRow.js +34 -0
  170. package/src/structures/ActivityInstance.js +52 -0
  171. package/src/structures/ActivityLocation.js +65 -0
  172. package/src/structures/AnnouncementChannel.js +29 -0
  173. package/src/structures/AnonymousGuild.js +107 -0
  174. package/src/structures/ApplicationCommand.js +657 -0
  175. package/src/structures/ApplicationEmoji.js +186 -0
  176. package/src/structures/ApplicationRoleConnectionMetadata.js +52 -0
  177. package/src/structures/Attachment.js +181 -0
  178. package/src/structures/AuthorizingIntegrationOwners.js +64 -0
  179. package/src/structures/AutoModerationActionExecution.js +131 -0
  180. package/src/structures/AutoModerationRule.js +317 -0
  181. package/src/structures/AutocompleteInteraction.js +112 -0
  182. package/src/structures/Base.js +45 -0
  183. package/src/structures/BaseChannel.js +188 -0
  184. package/src/structures/BaseGuild.js +134 -0
  185. package/src/structures/BaseGuildEmoji.js +111 -0
  186. package/src/structures/BaseGuildTextChannel.js +225 -0
  187. package/src/structures/BaseGuildVoiceChannel.js +265 -0
  188. package/src/structures/BaseInteraction.js +378 -0
  189. package/src/structures/BaseInvite.js +187 -0
  190. package/src/structures/BaseSelectMenuComponent.js +62 -0
  191. package/src/structures/ButtonComponent.js +72 -0
  192. package/src/structures/ButtonInteraction.js +12 -0
  193. package/src/structures/CategoryChannel.js +50 -0
  194. package/src/structures/ChannelSelectMenuComponent.js +22 -0
  195. package/src/structures/ChannelSelectMenuInteraction.js +36 -0
  196. package/src/structures/ChatInputCommandInteraction.js +45 -0
  197. package/src/structures/ClientApplication.js +463 -0
  198. package/src/structures/ClientPresence.js +89 -0
  199. package/src/structures/ClientUser.js +221 -0
  200. package/src/structures/CommandInteraction.js +188 -0
  201. package/src/structures/CommandInteractionOptionResolver.js +336 -0
  202. package/src/structures/Component.js +62 -0
  203. package/src/structures/ContainerComponent.js +66 -0
  204. package/src/structures/ContextMenuCommandInteraction.js +69 -0
  205. package/src/structures/DMChannel.js +162 -0
  206. package/src/structures/DirectoryChannel.js +40 -0
  207. package/src/structures/Embed.js +254 -0
  208. package/src/structures/Emoji.js +115 -0
  209. package/src/structures/Entitlement.js +199 -0
  210. package/src/structures/FileComponent.js +44 -0
  211. package/src/structures/ForumChannel.js +34 -0
  212. package/src/structures/GroupDMInvite.js +37 -0
  213. package/src/structures/Guild.js +1557 -0
  214. package/src/structures/GuildAuditLogs.js +97 -0
  215. package/src/structures/GuildAuditLogsEntry.js +552 -0
  216. package/src/structures/GuildBan.js +65 -0
  217. package/src/structures/GuildChannel.js +511 -0
  218. package/src/structures/GuildEmoji.js +160 -0
  219. package/src/structures/GuildInvite.js +223 -0
  220. package/src/structures/GuildMember.js +650 -0
  221. package/src/structures/GuildOnboarding.js +71 -0
  222. package/src/structures/GuildOnboardingPrompt.js +88 -0
  223. package/src/structures/GuildOnboardingPromptOption.js +96 -0
  224. package/src/structures/GuildPreview.js +213 -0
  225. package/src/structures/GuildPreviewEmoji.js +30 -0
  226. package/src/structures/GuildScheduledEvent.js +579 -0
  227. package/src/structures/GuildTemplate.js +221 -0
  228. package/src/structures/Integration.js +243 -0
  229. package/src/structures/IntegrationApplication.js +82 -0
  230. package/src/structures/InteractionCallback.js +83 -0
  231. package/src/structures/InteractionCallbackResource.js +57 -0
  232. package/src/structures/InteractionCallbackResponse.js +36 -0
  233. package/src/structures/InteractionCollector.js +256 -0
  234. package/src/structures/InteractionWebhook.js +67 -0
  235. package/src/structures/InviteGuild.js +24 -0
  236. package/src/structures/LabelComponent.js +54 -0
  237. package/src/structures/MediaChannel.js +12 -0
  238. package/src/structures/MediaGalleryComponent.js +34 -0
  239. package/src/structures/MediaGalleryItem.js +56 -0
  240. package/src/structures/MentionableSelectMenuComponent.js +12 -0
  241. package/src/structures/MentionableSelectMenuInteraction.js +76 -0
  242. package/src/structures/Message.js +1203 -0
  243. package/src/structures/MessageCollector.js +157 -0
  244. package/src/structures/MessageComponentInteraction.js +128 -0
  245. package/src/structures/MessageContextMenuCommandInteraction.js +22 -0
  246. package/src/structures/MessageMentions.js +323 -0
  247. package/src/structures/MessagePayload.js +346 -0
  248. package/src/structures/MessageReaction.js +214 -0
  249. package/src/structures/ModalComponentResolver.js +269 -0
  250. package/src/structures/ModalSubmitInteraction.js +274 -0
  251. package/src/structures/OAuth2Guild.js +31 -0
  252. package/src/structures/PartialGroupDMChannel.js +146 -0
  253. package/src/structures/PermissionOverwrites.js +221 -0
  254. package/src/structures/Poll.js +190 -0
  255. package/src/structures/PollAnswer.js +98 -0
  256. package/src/structures/Presence.js +429 -0
  257. package/src/structures/PrimaryEntryPointCommandInteraction.js +12 -0
  258. package/src/structures/ReactionCollector.js +246 -0
  259. package/src/structures/ReactionEmoji.js +33 -0
  260. package/src/structures/Role.js +539 -0
  261. package/src/structures/RoleSelectMenuComponent.js +12 -0
  262. package/src/structures/RoleSelectMenuInteraction.js +36 -0
  263. package/src/structures/SKU.js +59 -0
  264. package/src/structures/SectionComponent.js +46 -0
  265. package/src/structures/SeparatorComponent.js +33 -0
  266. package/src/structures/SoundboardSound.js +220 -0
  267. package/src/structures/StageChannel.js +121 -0
  268. package/src/structures/StageInstance.js +170 -0
  269. package/src/structures/Sticker.js +292 -0
  270. package/src/structures/StickerPack.js +107 -0
  271. package/src/structures/StringSelectMenuComponent.js +22 -0
  272. package/src/structures/StringSelectMenuInteraction.js +23 -0
  273. package/src/structures/Subscription.js +131 -0
  274. package/src/structures/Team.js +129 -0
  275. package/src/structures/TeamMember.js +77 -0
  276. package/src/structures/TextChannel.js +36 -0
  277. package/src/structures/TextDisplayComponent.js +22 -0
  278. package/src/structures/TextInputComponent.js +32 -0
  279. package/src/structures/ThreadChannel.js +662 -0
  280. package/src/structures/ThreadMember.js +124 -0
  281. package/src/structures/ThreadOnlyChannel.js +270 -0
  282. package/src/structures/ThumbnailComponent.js +54 -0
  283. package/src/structures/Typing.js +82 -0
  284. package/src/structures/UnfurledMediaItem.js +36 -0
  285. package/src/structures/User.js +505 -0
  286. package/src/structures/UserContextMenuCommandInteraction.js +32 -0
  287. package/src/structures/UserSelectMenuComponent.js +12 -0
  288. package/src/structures/UserSelectMenuInteraction.js +55 -0
  289. package/src/structures/VoiceChannel.js +123 -0
  290. package/src/structures/VoiceChannelEffect.js +88 -0
  291. package/src/structures/VoiceRegion.js +51 -0
  292. package/src/structures/VoiceState.js +338 -0
  293. package/src/structures/Webhook.js +520 -0
  294. package/src/structures/WelcomeChannel.js +67 -0
  295. package/src/structures/WelcomeScreen.js +54 -0
  296. package/src/structures/Widget.js +107 -0
  297. package/src/structures/WidgetMember.js +114 -0
  298. package/src/structures/interfaces/Application.js +173 -0
  299. package/src/structures/interfaces/Collector.js +368 -0
  300. package/src/structures/interfaces/InteractionResponses.js +385 -0
  301. package/src/structures/interfaces/TextBasedChannel.js +431 -0
  302. package/src/util/APITypes.js +700 -0
  303. package/src/util/ActivityFlagsBitField.js +29 -0
  304. package/src/util/ApplicationFlagsBitField.js +46 -0
  305. package/src/util/AttachmentFlagsBitField.js +29 -0
  306. package/src/util/BitField.js +197 -0
  307. package/src/util/ChannelFlagsBitField.js +46 -0
  308. package/src/util/Channels.js +173 -0
  309. package/src/util/Colors.js +73 -0
  310. package/src/util/Components.js +329 -0
  311. package/src/util/Constants.js +253 -0
  312. package/src/util/DataResolver.js +161 -0
  313. package/src/util/Enums.js +14 -0
  314. package/src/util/Events.js +179 -0
  315. package/src/util/GuildMemberFlagsBitField.js +46 -0
  316. package/src/util/IntentsBitField.js +38 -0
  317. package/src/util/InviteFlagsBitField.js +29 -0
  318. package/src/util/Invites.js +31 -0
  319. package/src/util/LimitedCollection.js +75 -0
  320. package/src/util/LolkaSnowflake.js +47 -0
  321. package/src/util/MessageFlagsBitField.js +46 -0
  322. package/src/util/Options.js +221 -0
  323. package/src/util/Partials.js +51 -0
  324. package/src/util/PermissionsBitField.js +117 -0
  325. package/src/util/RoleFlagsBitField.js +29 -0
  326. package/src/util/SKUFlagsBitField.js +29 -0
  327. package/src/util/ShardEvents.js +27 -0
  328. package/src/util/Status.js +17 -0
  329. package/src/util/Sweepers.js +533 -0
  330. package/src/util/Symbols.js +3 -0
  331. package/src/util/SystemChannelFlagsBitField.js +48 -0
  332. package/src/util/ThreadMemberFlagsBitField.js +36 -0
  333. package/src/util/Transformers.js +124 -0
  334. package/src/util/UserFlagsBitField.js +36 -0
  335. package/src/util/Util.js +609 -0
  336. package/typings/index.d.mts +7512 -0
  337. package/typings/index.d.ts +7512 -0
@@ -0,0 +1,943 @@
1
+ 'use strict';
2
+
3
+ const process = require('node:process');
4
+ const { clearTimeout, setImmediate, setTimeout } = require('node:timers');
5
+ const { Collection } = require('@discordjs/collection');
6
+ const { REST, RESTEvents, makeURLSearchParams } = require('@discordjs/rest');
7
+ const { WebSocketManager, WebSocketShardEvents, WebSocketShardStatus } = require('@discordjs/ws');
8
+ const { AsyncEventEmitter } = require('@vladfrangu/async_event_emitter');
9
+ const { GatewayDispatchEvents, GatewayIntentBits, OAuth2Scopes, Routes } = require('discord-api-types/v10');
10
+ const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors/index.js');
11
+ const { ChannelManager } = require('../managers/ChannelManager.js');
12
+ const { GuildManager } = require('../managers/GuildManager.js');
13
+ const { UserManager } = require('../managers/UserManager.js');
14
+ const { ShardClientUtil } = require('../sharding/ShardClientUtil.js');
15
+ const { ClientPresence } = require('../structures/ClientPresence.js');
16
+ const { GuildPreview } = require('../structures/GuildPreview.js');
17
+ const { GuildTemplate } = require('../structures/GuildTemplate.js');
18
+ const { SoundboardSound } = require('../structures/SoundboardSound.js');
19
+ const { Sticker } = require('../structures/Sticker.js');
20
+ const { StickerPack } = require('../structures/StickerPack.js');
21
+ const { VoiceRegion } = require('../structures/VoiceRegion.js');
22
+ const { Webhook } = require('../structures/Webhook.js');
23
+ const { Widget } = require('../structures/Widget.js');
24
+ const { resolveInviteCode, resolveGuildTemplateCode } = require('../util/DataResolver.js');
25
+ const { Events } = require('../util/Events.js');
26
+ const { IntentsBitField } = require('../util/IntentsBitField.js');
27
+ const { createInvite } = require('../util/Invites.js');
28
+ const { Options } = require('../util/Options.js');
29
+ const { PermissionsBitField } = require('../util/PermissionsBitField.js');
30
+ const { Status } = require('../util/Status.js');
31
+ const { Sweepers } = require('../util/Sweepers.js');
32
+ const { flatten } = require('../util/Util.js');
33
+ const { ActionsManager } = require('./actions/ActionsManager.js');
34
+ const { ClientVoiceManager } = require('./voice/ClientVoiceManager.js');
35
+ const { PacketHandlers } = require('./websocket/handlers/index.js');
36
+
37
+ const WaitingForGuildEvents = [GatewayDispatchEvents.GuildCreate, GatewayDispatchEvents.GuildDelete];
38
+ const BeforeReadyWhitelist = [
39
+ GatewayDispatchEvents.Ready,
40
+ GatewayDispatchEvents.Resumed,
41
+ GatewayDispatchEvents.GuildCreate,
42
+ GatewayDispatchEvents.GuildDelete,
43
+ GatewayDispatchEvents.GuildMembersChunk,
44
+ GatewayDispatchEvents.GuildMemberAdd,
45
+ GatewayDispatchEvents.GuildMemberRemove,
46
+ ];
47
+
48
+ /**
49
+ * The main hub for interacting with the Discord API, and the starting point for any bot.
50
+ *
51
+ * @extends {AsyncEventEmitter}
52
+ */
53
+ class Client extends AsyncEventEmitter {
54
+ /**
55
+ * @param {ClientOptions} options Options for the client
56
+ */
57
+ constructor(options) {
58
+ super();
59
+
60
+ if (typeof options !== 'object' || options === null) {
61
+ throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true);
62
+ }
63
+
64
+ const defaultOptions = Options.createDefault();
65
+ /**
66
+ * The options the client was instantiated with
67
+ *
68
+ * @type {ClientOptions}
69
+ */
70
+ this.options = {
71
+ ...defaultOptions,
72
+ ...options,
73
+ presence: {
74
+ ...defaultOptions.presence,
75
+ ...options.presence,
76
+ },
77
+ sweepers: {
78
+ ...defaultOptions.sweepers,
79
+ ...options.sweepers,
80
+ },
81
+ ws: {
82
+ ...defaultOptions.ws,
83
+ ...options.ws,
84
+ },
85
+ rest: {
86
+ ...defaultOptions.rest,
87
+ ...options.rest,
88
+ userAgentAppendix: options.rest?.userAgentAppendix
89
+ ? `${Options.userAgentAppendix} ${options.rest.userAgentAppendix}`
90
+ : Options.userAgentAppendix,
91
+ },
92
+ };
93
+
94
+ /**
95
+ * The REST manager of the client
96
+ *
97
+ * @type {REST}
98
+ */
99
+ this.rest = new REST(this.options.rest);
100
+
101
+ this.rest.on(RESTEvents.Debug, message => this.emit(Events.Debug, message));
102
+
103
+ const data = require('node:worker_threads').workerData ?? process.env;
104
+
105
+ if (this.options.ws.shardIds === defaultOptions.ws.shardIds && 'SHARDS' in data) {
106
+ const shards = JSON.parse(data.SHARDS);
107
+ this.options.ws.shardIds = Array.isArray(shards) ? shards : [shards];
108
+ }
109
+
110
+ if (this.options.ws.shardCount === defaultOptions.ws.shardCount && 'SHARD_COUNT' in data) {
111
+ this.options.ws.shardCount = Number(data.SHARD_COUNT);
112
+ }
113
+
114
+ /**
115
+ * The presence of the Client
116
+ *
117
+ * @private
118
+ * @type {ClientPresence}
119
+ */
120
+ this.presence = new ClientPresence(this, this.options.ws.initialPresence ?? this.options.presence);
121
+
122
+ this._validateOptions();
123
+
124
+ /**
125
+ * The current status of this Client
126
+ *
127
+ * @type {Status}
128
+ * @private
129
+ */
130
+ this.status = Status.Idle;
131
+
132
+ /**
133
+ * A set of guild ids this Client expects to receive
134
+ *
135
+ * @name Client#expectedGuilds
136
+ * @type {Set<string>}
137
+ * @private
138
+ */
139
+ Object.defineProperty(this, 'expectedGuilds', { value: new Set(), writable: true });
140
+
141
+ /**
142
+ * The ready timeout
143
+ *
144
+ * @name Client#readyTimeout
145
+ * @type {?NodeJS.Timeout}
146
+ * @private
147
+ */
148
+ Object.defineProperty(this, 'readyTimeout', { value: null, writable: true });
149
+
150
+ /**
151
+ * The action manager of the client
152
+ *
153
+ * @type {ActionsManager}
154
+ * @private
155
+ */
156
+ this.actions = new ActionsManager(this);
157
+
158
+ /**
159
+ * The user manager of this client
160
+ *
161
+ * @type {UserManager}
162
+ */
163
+ this.users = new UserManager(this);
164
+
165
+ /**
166
+ * A manager of all the guilds the client is currently handling -
167
+ * as long as sharding isn't being used, this will be *every* guild the bot is a member of
168
+ *
169
+ * @type {GuildManager}
170
+ */
171
+ this.guilds = new GuildManager(this);
172
+
173
+ /**
174
+ * All of the {@link BaseChannel}s that the client is currently handling -
175
+ * as long as sharding isn't being used, this will be *every* channel in *every* guild the bot
176
+ * is a member of. Note that DM channels will not be initially cached, and thus not be present
177
+ * in the Manager without their explicit fetching or use.
178
+ *
179
+ * @type {ChannelManager}
180
+ */
181
+ this.channels = new ChannelManager(this);
182
+
183
+ /**
184
+ * The sweeping functions and their intervals used to periodically sweep caches
185
+ *
186
+ * @type {Sweepers}
187
+ */
188
+ this.sweepers = new Sweepers(this, this.options.sweepers);
189
+
190
+ Object.defineProperty(this, 'token', { writable: true });
191
+ if (!this.token && 'DISCORD_TOKEN' in process.env) {
192
+ /**
193
+ * Authorization token for the logged in bot.
194
+ * If present, this defaults to `process.env.DISCORD_TOKEN` when instantiating the client
195
+ * <warn>This should be kept private at all times.</warn>
196
+ *
197
+ * @type {?string}
198
+ */
199
+ this.token = process.env.DISCORD_TOKEN;
200
+ } else if (this.options.ws.token) {
201
+ this.token = this.options.ws.token;
202
+ } else {
203
+ this.token = null;
204
+ }
205
+
206
+ const wsOptions = {
207
+ ...this.options.ws,
208
+ intents: this.options.intents.bitfield,
209
+ fetchGatewayInformation: () => this.rest.get(Routes.gatewayBot()),
210
+ // Explicitly nulled to always be set using `setToken` in `login`
211
+ token: null,
212
+ };
213
+
214
+ /**
215
+ * The WebSocket manager of the client
216
+ *
217
+ * @type {WebSocketManager}
218
+ */
219
+ this.ws = new WebSocketManager(wsOptions);
220
+
221
+ /**
222
+ * Shard helpers for the client (only if the process was spawned from a {@link ShardingManager})
223
+ *
224
+ * @type {?ShardClientUtil}
225
+ */
226
+ this.shard = process.env.SHARDING_MANAGER
227
+ ? ShardClientUtil.singleton(this, process.env.SHARDING_MANAGER_MODE)
228
+ : null;
229
+
230
+ /**
231
+ * The voice manager of the client
232
+ *
233
+ * @type {ClientVoiceManager}
234
+ */
235
+ this.voice = new ClientVoiceManager(this);
236
+
237
+ /**
238
+ * User that the client is logged in as
239
+ *
240
+ * @type {?ClientUser}
241
+ */
242
+ this.user = null;
243
+
244
+ /**
245
+ * The application of this bot
246
+ *
247
+ * @type {?ClientApplication}
248
+ */
249
+ this.application = null;
250
+
251
+ /**
252
+ * The latencies of the WebSocketShard connections
253
+ *
254
+ * @type {Collection<number, number>}
255
+ */
256
+ this.pings = new Collection();
257
+
258
+ /**
259
+ * The last time a ping was sent (a timestamp) for each WebSocketShard connection
260
+ *
261
+ * @type {Collection<number, number>}
262
+ */
263
+ this.lastPingTimestamps = new Collection();
264
+
265
+ /**
266
+ * Timestamp of the time the client was last {@link Status.Ready} at
267
+ *
268
+ * @type {?number}
269
+ */
270
+ this.readyTimestamp = null;
271
+
272
+ /**
273
+ * An array of queued events before this Client became ready
274
+ *
275
+ * @type {Object[]}
276
+ * @private
277
+ * @name Client#incomingPacketQueue
278
+ */
279
+ Object.defineProperty(this, 'incomingPacketQueue', { value: [] });
280
+
281
+ this._attachEvents();
282
+ }
283
+
284
+ /**
285
+ * Time at which the client was last regarded as being in the {@link Status.Ready} state
286
+ * (each time the client disconnects and successfully reconnects, this will be overwritten)
287
+ *
288
+ * @type {?Date}
289
+ * @readonly
290
+ */
291
+ get readyAt() {
292
+ return this.readyTimestamp && new Date(this.readyTimestamp);
293
+ }
294
+
295
+ /**
296
+ * How long it has been since the client last entered the {@link Status.Ready} state in milliseconds
297
+ *
298
+ * @type {?number}
299
+ * @readonly
300
+ */
301
+ get uptime() {
302
+ return this.readyTimestamp && Date.now() - this.readyTimestamp;
303
+ }
304
+
305
+ /**
306
+ * Logs the client in, establishing a WebSocket connection to Discord.
307
+ *
308
+ * @param {string} [token=this.token] Token of the account to log in with
309
+ * @returns {Promise<string>} Token of the account used
310
+ * @example
311
+ * client.login('my token');
312
+ */
313
+ async login(token = this.token) {
314
+ if (!token || typeof token !== 'string') throw new DiscordjsError(ErrorCodes.TokenInvalid);
315
+ this.token = token.replace(/^bot\s*/i, '');
316
+
317
+ this.rest.setToken(this.token);
318
+
319
+ this.emit(Events.Debug, `Provided token: ${this._censoredToken}`);
320
+ this.emit(Events.Debug, 'Preparing to connect to the gateway...');
321
+
322
+ this.ws.setToken(this.token);
323
+
324
+ try {
325
+ await this.ws.connect();
326
+ return this.token;
327
+ } catch (error) {
328
+ await this.destroy();
329
+ throw error;
330
+ }
331
+ }
332
+
333
+ /**
334
+ * Checks if the client can be marked as ready
335
+ *
336
+ * @private
337
+ */
338
+ async _checkReady() {
339
+ // Step 0. Clear the ready timeout, if it exists
340
+ if (this.readyTimeout) {
341
+ clearTimeout(this.readyTimeout);
342
+ this.readyTimeout = null;
343
+ }
344
+
345
+ // Step 1. If we don't have any other guilds pending, we are ready
346
+ if (
347
+ !this.expectedGuilds.size &&
348
+ (await this.ws.fetchStatus()).every(status => status === WebSocketShardStatus.Ready)
349
+ ) {
350
+ this.emit(Events.Debug, 'Client received all its guilds. Marking as fully ready.');
351
+
352
+ this._triggerClientReady();
353
+ return;
354
+ }
355
+
356
+ const hasGuildsIntent = this.options.intents.has(GatewayIntentBits.Guilds);
357
+ // Step 2. Create a timeout that will mark the client as ready if there are still unavailable guilds
358
+ // * The timeout is 15 seconds by default
359
+ // * This can be optionally changed in the client options via the `waitGuildTimeout` option
360
+ // * a timeout time of zero will skip this timeout, which potentially could cause the Client to miss guilds.
361
+
362
+ this.readyTimeout = setTimeout(
363
+ () => {
364
+ this.emit(
365
+ Events.Debug,
366
+ `${
367
+ hasGuildsIntent
368
+ ? `Client did not receive any guild packets in ${this.options.waitGuildTimeout} ms.`
369
+ : 'Client will not receive anymore guild packets.'
370
+ }\nUnavailable guild count: ${this.expectedGuilds.size}`,
371
+ );
372
+
373
+ this.readyTimeout = null;
374
+
375
+ this._triggerClientReady();
376
+ },
377
+ hasGuildsIntent ? this.options.waitGuildTimeout : 0,
378
+ ).unref();
379
+ }
380
+
381
+ /**
382
+ * Attaches event handlers to the WebSocketShardManager from `@discordjs/ws`.
383
+ *
384
+ * @private
385
+ */
386
+ _attachEvents() {
387
+ this.ws.on(WebSocketShardEvents.Debug, (message, shardId) =>
388
+ this.emit(Events.Debug, `[WS => ${typeof shardId === 'number' ? `Shard ${shardId}` : 'Manager'}] ${message}`),
389
+ );
390
+ this.ws.on(WebSocketShardEvents.Dispatch, this._handlePacket.bind(this));
391
+
392
+ this.ws.on(WebSocketShardEvents.HeartbeatComplete, ({ heartbeatAt, latency }, shardId) => {
393
+ this.emit(Events.Debug, `[WS => Shard ${shardId}] Heartbeat acknowledged, latency of ${latency}ms.`);
394
+ this.lastPingTimestamps.set(shardId, heartbeatAt);
395
+ this.pings.set(shardId, latency);
396
+ });
397
+ }
398
+
399
+ /**
400
+ * Processes a packet and queues it if this WebSocketManager is not ready.
401
+ *
402
+ * @param {GatewayDispatchPayload} packet The packet to be handled
403
+ * @param {number} shardId The shardId that received this packet
404
+ * @private
405
+ */
406
+ async _handlePacket(packet, shardId) {
407
+ if (this.status !== Status.Ready && !BeforeReadyWhitelist.includes(packet.t)) {
408
+ this.incomingPacketQueue.push({ packet, shardId });
409
+ } else {
410
+ if (this.incomingPacketQueue.length) {
411
+ const item = this.incomingPacketQueue.shift();
412
+ setImmediate(async () => {
413
+ await this._handlePacket(item.packet, item.shardId);
414
+ }).unref();
415
+ }
416
+
417
+ if (PacketHandlers[packet.t]) {
418
+ PacketHandlers[packet.t](this, packet, shardId);
419
+ }
420
+
421
+ if (packet.t === GatewayDispatchEvents.Ready) {
422
+ await this._checkReady();
423
+ } else if (this.status === Status.WaitingForGuilds && WaitingForGuildEvents.includes(packet.t)) {
424
+ this.expectedGuilds.delete(packet.d.id);
425
+ await this._checkReady();
426
+ }
427
+ }
428
+ }
429
+
430
+ /**
431
+ * Broadcasts a packet to every shard of this client handles.
432
+ *
433
+ * @param {Object} packet The packet to send
434
+ * @private
435
+ */
436
+ async _broadcast(packet) {
437
+ const shardIds = await this.ws.getShardIds();
438
+ return Promise.all(shardIds.map(shardId => this.ws.send(shardId, packet)));
439
+ }
440
+
441
+ /**
442
+ * Causes the client to be marked as ready and emits the ready event.
443
+ *
444
+ * @private
445
+ */
446
+ _triggerClientReady() {
447
+ this.status = Status.Ready;
448
+
449
+ this.readyTimestamp = Date.now();
450
+
451
+ /**
452
+ * Emitted when the client becomes ready to start working.
453
+ *
454
+ * @event Client#clientReady
455
+ * @param {Client} client The client
456
+ */
457
+ this.emit(Events.ClientReady, this);
458
+ }
459
+
460
+ /**
461
+ * Returns whether the client has logged in, indicative of being able to access
462
+ * properties such as `user` and `application`.
463
+ *
464
+ * @returns {boolean}
465
+ */
466
+ isReady() {
467
+ return this.status === Status.Ready;
468
+ }
469
+
470
+ /**
471
+ * The average ping of all WebSocketShards
472
+ *
473
+ * @type {?number}
474
+ * @readonly
475
+ */
476
+ get ping() {
477
+ return this.pings.size ? this.pings.reduce((a, b) => a + b, 0) / this.pings.size : null;
478
+ }
479
+
480
+ /**
481
+ * Options used for deleting a webhook.
482
+ *
483
+ * @typedef {Object} WebhookDeleteOptions
484
+ * @property {string} [token] Token of the webhook
485
+ * @property {string} [reason] The reason for deleting the webhook
486
+ */
487
+
488
+ /**
489
+ * Deletes a webhook.
490
+ *
491
+ * @param {Snowflake} id The webhook's id
492
+ * @param {WebhookDeleteOptions} [options] Options for deleting the webhook
493
+ * @returns {Promise<void>}
494
+ */
495
+ async deleteWebhook(id, { token, reason } = {}) {
496
+ await this.rest.delete(Routes.webhook(id, token), { auth: !token, reason });
497
+ }
498
+
499
+ /**
500
+ * Increments max listeners by one, if they are not zero.
501
+ *
502
+ * @private
503
+ */
504
+ incrementMaxListeners() {
505
+ const maxListeners = this.getMaxListeners();
506
+ if (maxListeners !== 0) {
507
+ this.setMaxListeners(maxListeners + 1);
508
+ }
509
+ }
510
+
511
+ /**
512
+ * Decrements max listeners by one, if they are not zero.
513
+ *
514
+ * @private
515
+ */
516
+ decrementMaxListeners() {
517
+ const maxListeners = this.getMaxListeners();
518
+ if (maxListeners !== 0) {
519
+ this.setMaxListeners(maxListeners - 1);
520
+ }
521
+ }
522
+
523
+ /**
524
+ * Destroys all assets used by the client.
525
+ *
526
+ * @returns {Promise<void>}
527
+ */
528
+ async destroy() {
529
+ this.rest.clearHashSweeper();
530
+ this.rest.clearHandlerSweeper();
531
+
532
+ this.sweepers.destroy();
533
+ await this.ws.destroy();
534
+ this.token = null;
535
+ this.rest.setToken(null);
536
+ }
537
+
538
+ /**
539
+ * Options used when fetching an invite from Discord.
540
+ *
541
+ * @typedef {Object} ClientFetchInviteOptions
542
+ * @property {boolean} [withCounts] Whether to include approximate member counts
543
+ * @property {Snowflake} [guildScheduledEventId] The id of the guild scheduled event to include with
544
+ * the invite
545
+ */
546
+
547
+ /**
548
+ * Obtains an invite from Discord.
549
+ *
550
+ * @param {InviteResolvable} invite Invite code or URL
551
+ * @param {ClientFetchInviteOptions} [options] Options for fetching the invite
552
+ * @returns {Promise<Invite>}
553
+ * @example
554
+ * client.fetchInvite('https://discord.gg/djs')
555
+ * .then(invite => console.log(`Obtained invite with code: ${invite.code}`))
556
+ * .catch(console.error);
557
+ */
558
+ async fetchInvite(invite, { withCounts, guildScheduledEventId } = {}) {
559
+ const code = resolveInviteCode(invite);
560
+
561
+ const query = makeURLSearchParams({
562
+ with_counts: withCounts,
563
+ guild_scheduled_event_id: guildScheduledEventId,
564
+ });
565
+
566
+ const data = await this.rest.get(Routes.invite(code), { query });
567
+ return createInvite(this, data);
568
+ }
569
+
570
+ /**
571
+ * Obtains a template from Discord.
572
+ *
573
+ * @param {GuildTemplateResolvable} template Template code or URL
574
+ * @returns {Promise<GuildTemplate>}
575
+ * @example
576
+ * client.fetchGuildTemplate('https://discord.new/FKvmczH2HyUf')
577
+ * .then(template => console.log(`Obtained template with code: ${template.code}`))
578
+ * .catch(console.error);
579
+ */
580
+ async fetchGuildTemplate(template) {
581
+ const code = resolveGuildTemplateCode(template);
582
+ const data = await this.rest.get(Routes.template(code));
583
+ return new GuildTemplate(this, data);
584
+ }
585
+
586
+ /**
587
+ * Obtains a webhook from Discord.
588
+ *
589
+ * @param {Snowflake} id The webhook's id
590
+ * @param {string} [token] Token for the webhook
591
+ * @returns {Promise<Webhook>}
592
+ * @example
593
+ * client.fetchWebhook('id', 'token')
594
+ * .then(webhook => console.log(`Obtained webhook with name: ${webhook.name}`))
595
+ * .catch(console.error);
596
+ */
597
+ async fetchWebhook(id, token) {
598
+ const data = await this.rest.get(Routes.webhook(id, token), { auth: token === undefined });
599
+ return new Webhook(this, { token, ...data });
600
+ }
601
+
602
+ /**
603
+ * Obtains the available voice regions from Discord.
604
+ *
605
+ * @returns {Promise<Collection<string, VoiceRegion>>}
606
+ * @example
607
+ * client.fetchVoiceRegions()
608
+ * .then(regions => console.log(`Available regions are: ${regions.map(region => region.name).join(', ')}`))
609
+ * .catch(console.error);
610
+ */
611
+ async fetchVoiceRegions() {
612
+ const apiRegions = await this.rest.get(Routes.voiceRegions());
613
+ const regions = new Collection();
614
+ for (const region of apiRegions) regions.set(region.id, new VoiceRegion(region));
615
+ return regions;
616
+ }
617
+
618
+ /**
619
+ * Obtains a sticker from Discord.
620
+ *
621
+ * @param {Snowflake} id The sticker's id
622
+ * @returns {Promise<Sticker>}
623
+ * @example
624
+ * client.fetchSticker('id')
625
+ * .then(sticker => console.log(`Obtained sticker with name: ${sticker.name}`))
626
+ * .catch(console.error);
627
+ */
628
+ async fetchSticker(id) {
629
+ const data = await this.rest.get(Routes.sticker(id));
630
+ return new Sticker(this, data);
631
+ }
632
+
633
+ /**
634
+ * Options for fetching sticker packs.
635
+ *
636
+ * @typedef {Object} StickerPackFetchOptions
637
+ * @property {Snowflake} [packId] The id of the sticker pack to fetch
638
+ */
639
+
640
+ /**
641
+ * Obtains the list of available sticker packs.
642
+ *
643
+ * @param {StickerPackFetchOptions} [options={}] Options for fetching sticker packs
644
+ * @returns {Promise<Collection<Snowflake, StickerPack>|StickerPack>}
645
+ * A collection of sticker packs, or a single sticker pack if a packId was provided
646
+ * @example
647
+ * client.fetchStickerPacks()
648
+ * .then(packs => console.log(`Available sticker packs are: ${packs.map(pack => pack.name).join(', ')}`))
649
+ * .catch(console.error);
650
+ * @example
651
+ * client.fetchStickerPacks({ packId: '751604115435421716' })
652
+ * .then(pack => console.log(`Sticker pack name: ${pack.name}`))
653
+ * .catch(console.error);
654
+ */
655
+ async fetchStickerPacks({ packId } = {}) {
656
+ if (packId) {
657
+ const innerData = await this.rest.get(Routes.stickerPack(packId));
658
+ return new StickerPack(this, innerData);
659
+ }
660
+
661
+ const data = await this.rest.get(Routes.stickerPacks());
662
+ return new Collection(data.sticker_packs.map(stickerPack => [stickerPack.id, new StickerPack(this, stickerPack)]));
663
+ }
664
+
665
+ /**
666
+ * Obtains the list of default soundboard sounds.
667
+ *
668
+ * @returns {Promise<Collection<string, SoundboardSound>>}
669
+ * @example
670
+ * client.fetchDefaultSoundboardSounds()
671
+ * .then(sounds => console.log(`Available soundboard sounds are: ${sounds.map(sound => sound.name).join(', ')}`))
672
+ * .catch(console.error);
673
+ */
674
+ async fetchDefaultSoundboardSounds() {
675
+ const data = await this.rest.get(Routes.soundboardDefaultSounds());
676
+ return new Collection(data.map(sound => [sound.sound_id, new SoundboardSound(this, sound)]));
677
+ }
678
+
679
+ /**
680
+ * Obtains a guild preview from Discord, available for all guilds the bot is in and all Discoverable guilds.
681
+ *
682
+ * @param {GuildResolvable} guild The guild to fetch the preview for
683
+ * @returns {Promise<GuildPreview>}
684
+ */
685
+ async fetchGuildPreview(guild) {
686
+ const id = this.guilds.resolveId(guild);
687
+ if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'guild', 'GuildResolvable');
688
+ const data = await this.rest.get(Routes.guildPreview(id));
689
+ return new GuildPreview(this, data);
690
+ }
691
+
692
+ /**
693
+ * Obtains the widget data of a guild from Discord, available for guilds with the widget enabled.
694
+ *
695
+ * @param {GuildResolvable} guild The guild to fetch the widget data for
696
+ * @returns {Promise<Widget>}
697
+ */
698
+ async fetchGuildWidget(guild) {
699
+ const id = this.guilds.resolveId(guild);
700
+ if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'guild', 'GuildResolvable');
701
+ const data = await this.rest.get(Routes.guildWidgetJSON(id));
702
+ return new Widget(this, data);
703
+ }
704
+
705
+ /**
706
+ * Options for {@link Client#generateInvite}.
707
+ *
708
+ * @typedef {Object} InviteGenerationOptions
709
+ * @property {OAuth2Scopes[]} scopes Scopes that should be requested
710
+ * @property {PermissionResolvable} [permissions] Permissions to request
711
+ * @property {GuildResolvable} [guild] Guild to preselect
712
+ * @property {boolean} [disableGuildSelect] Whether to disable the guild selection
713
+ */
714
+
715
+ /**
716
+ * Generates a link that can be used to invite the bot to a guild.
717
+ *
718
+ * @param {InviteGenerationOptions} [options={}] Options for the invite
719
+ * @returns {string}
720
+ * @example
721
+ * const link = client.generateInvite({
722
+ * scopes: [OAuth2Scopes.ApplicationsCommands],
723
+ * });
724
+ * console.log(`Generated application invite link: ${link}`);
725
+ * @example
726
+ * const link = client.generateInvite({
727
+ * permissions: [
728
+ * PermissionFlagsBits.SendMessages,
729
+ * PermissionFlagsBits.ManageGuild,
730
+ * PermissionFlagsBits.MentionEveryone,
731
+ * ],
732
+ * scopes: [OAuth2Scopes.Bot],
733
+ * });
734
+ * console.log(`Generated bot invite link: ${link}`);
735
+ */
736
+ generateInvite(options = {}) {
737
+ if (typeof options !== 'object') throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true);
738
+ if (!this.application) throw new DiscordjsError(ErrorCodes.ClientNotReady, 'generate an invite link');
739
+
740
+ const { scopes } = options;
741
+ if (scopes === undefined) {
742
+ throw new DiscordjsTypeError(ErrorCodes.InvalidMissingScopes);
743
+ }
744
+
745
+ if (!Array.isArray(scopes)) {
746
+ throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'scopes', 'Array of Invite Scopes', true);
747
+ }
748
+
749
+ if (!scopes.some(scope => [OAuth2Scopes.Bot, OAuth2Scopes.ApplicationsCommands].includes(scope))) {
750
+ throw new DiscordjsTypeError(ErrorCodes.InvalidMissingScopes);
751
+ }
752
+
753
+ if (!scopes.includes(OAuth2Scopes.Bot) && options.permissions) {
754
+ throw new DiscordjsTypeError(ErrorCodes.InvalidScopesWithPermissions);
755
+ }
756
+
757
+ const validScopes = Object.values(OAuth2Scopes);
758
+ const invalidScope = scopes.find(scope => !validScopes.includes(scope));
759
+ if (invalidScope) {
760
+ throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array', 'scopes', invalidScope);
761
+ }
762
+
763
+ const query = makeURLSearchParams({
764
+ client_id: this.application.id,
765
+ scope: scopes.join(' '),
766
+ disable_guild_select: options.disableGuildSelect,
767
+ });
768
+
769
+ if (options.permissions) {
770
+ const permissions = PermissionsBitField.resolve(options.permissions);
771
+ if (permissions) query.set('permissions', permissions.toString());
772
+ }
773
+
774
+ if (options.guild) {
775
+ const guildId = this.guilds.resolveId(options.guild);
776
+ if (!guildId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options.guild', 'GuildResolvable');
777
+ query.set('guild_id', guildId);
778
+ }
779
+
780
+ return `${this.options.rest.api}${Routes.oauth2Authorization()}?${query}`;
781
+ }
782
+
783
+ toJSON() {
784
+ return flatten(this, { actions: false, presence: false });
785
+ }
786
+
787
+ /**
788
+ * Partially censored client token for debug logging purposes.
789
+ *
790
+ * @type {?string}
791
+ * @readonly
792
+ * @private
793
+ */
794
+ get _censoredToken() {
795
+ if (!this.token) return null;
796
+
797
+ return this.token
798
+ .split('.')
799
+ .map((val, index) => (index > 1 ? val.replaceAll(/./g, '*') : val))
800
+ .join('.');
801
+ }
802
+
803
+ /**
804
+ * Calls {@link https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/eval} on a script
805
+ * with the client as `this`.
806
+ *
807
+ * @param {string} script Script to eval
808
+ * @returns {*}
809
+ * @private
810
+ */
811
+ _eval(script) {
812
+ // eslint-disable-next-line no-eval
813
+ return eval(script);
814
+ }
815
+
816
+ /**
817
+ * Validates the client options.
818
+ *
819
+ * @param {ClientOptions} [options=this.options] Options to validate
820
+ * @private
821
+ */
822
+ _validateOptions(options = this.options) {
823
+ if (options.intents === undefined && options.ws?.intents === undefined) {
824
+ throw new DiscordjsTypeError(ErrorCodes.ClientMissingIntents);
825
+ } else {
826
+ options.intents = new IntentsBitField(options.intents ?? options.ws.intents).freeze();
827
+ }
828
+
829
+ if (typeof options.sweepers !== 'object' || options.sweepers === null) {
830
+ throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'sweepers', 'an object');
831
+ }
832
+
833
+ if (!Array.isArray(options.partials)) {
834
+ throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'partials', 'an Array');
835
+ }
836
+
837
+ if (typeof options.waitGuildTimeout !== 'number' || Number.isNaN(options.waitGuildTimeout)) {
838
+ throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'waitGuildTimeout', 'a number');
839
+ }
840
+
841
+ if (typeof options.failIfNotExists !== 'boolean') {
842
+ throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'failIfNotExists', 'a boolean');
843
+ }
844
+
845
+ if (typeof options.enforceNonce !== 'boolean') {
846
+ throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'enforceNonce', 'a boolean');
847
+ }
848
+
849
+ if (
850
+ (typeof options.allowedMentions !== 'object' && options.allowedMentions !== undefined) ||
851
+ options.allowedMentions === null
852
+ ) {
853
+ throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'allowedMentions', 'an object');
854
+ }
855
+
856
+ if (typeof options.ws !== 'object' || options.ws === null) {
857
+ throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'ws', 'an object');
858
+ }
859
+
860
+ if (
861
+ (typeof options.presence !== 'object' || options.presence === null) &&
862
+ options.ws.initialPresence === undefined
863
+ ) {
864
+ throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'presence', 'an object');
865
+ } else {
866
+ options.ws.initialPresence = options.ws.initialPresence ?? this.presence._parse(this.options.presence);
867
+ }
868
+
869
+ if (typeof options.rest !== 'object' || options.rest === null) {
870
+ throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'rest', 'an object');
871
+ }
872
+
873
+ if (typeof options.jsonTransformer !== 'function') {
874
+ throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'jsonTransformer', 'a function');
875
+ }
876
+ }
877
+
878
+ async [Symbol.asyncDispose]() {
879
+ await this.destroy();
880
+ }
881
+ }
882
+
883
+ exports.Client = Client;
884
+
885
+ /**
886
+ * @class SnowflakeUtil
887
+ * @classdesc Utility for working with lolka snowflake ids (epoch 2025-01-01T00:00:00.000Z, 14-bit
888
+ * time shift).
889
+ * @hideconstructor
890
+ */
891
+
892
+ /**
893
+ * A {@link https://docs.x.com/resources/fundamentals/x-ids Twitter snowflake},
894
+ * except the epoch is 2015-01-01T00:00:00.000Z.
895
+ *
896
+ * If we have a snowflake '266241948824764416' we can represent it as binary:
897
+ * ```
898
+ * 64 22 17 12 0
899
+ * 000000111011000111100001101001000101000000 00001 00000 000000000000
900
+ * number of milliseconds since Discord epoch worker pid increment
901
+ * ```
902
+ *
903
+ * @typedef {string} Snowflake
904
+ */
905
+
906
+ /**
907
+ * Emitted for general debugging information.
908
+ *
909
+ * @event Client#debug
910
+ * @param {string} info The debug information
911
+ */
912
+
913
+ /**
914
+ * Emitted for general warnings.
915
+ *
916
+ * @event Client#warn
917
+ * @param {string} info The warning
918
+ */
919
+
920
+ /**
921
+ * @external Collection
922
+ * @see {@link https://discord.js.org/docs/packages/collection/stable/Collection:Class}
923
+ */
924
+
925
+ /**
926
+ * @external REST
927
+ * @see {@link https://discord.js.org/docs/packages/rest/stable/REST:Class}
928
+ */
929
+
930
+ /**
931
+ * @external ImageURLOptions
932
+ * @see {@link https://discord.js.org/docs/packages/rest/stable/ImageURLOptions:Interface}
933
+ */
934
+
935
+ /**
936
+ * @external EmojiURLOptions
937
+ * @see {@link https://discord.js.org/docs/packages/rest/stable/EmojiURLOptions:TypeAlias}
938
+ */
939
+
940
+ /**
941
+ * @external BaseImageURLOptions
942
+ * @see {@link https://discord.js.org/docs/packages/rest/stable/BaseImageURLOptions:Interface}
943
+ */