@biggy1337/discord-sbjs 1.3.11

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 (373) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +147 -0
  3. package/package.json +80 -0
  4. package/src/WebSocket.js +39 -0
  5. package/src/client/BaseClient.js +110 -0
  6. package/src/client/Client.js +1076 -0
  7. package/src/client/WebhookClient.js +61 -0
  8. package/src/client/actions/Action.js +133 -0
  9. package/src/client/actions/ActionsManager.js +80 -0
  10. package/src/client/actions/ApplicationCommandPermissionsUpdate.js +34 -0
  11. package/src/client/actions/AutoModerationActionExecution.js +27 -0
  12. package/src/client/actions/AutoModerationRuleCreate.js +28 -0
  13. package/src/client/actions/AutoModerationRuleDelete.js +32 -0
  14. package/src/client/actions/AutoModerationRuleUpdate.js +30 -0
  15. package/src/client/actions/ChannelCreate.js +23 -0
  16. package/src/client/actions/ChannelDelete.js +39 -0
  17. package/src/client/actions/ChannelUpdate.js +43 -0
  18. package/src/client/actions/GuildAuditLogEntryCreate.js +29 -0
  19. package/src/client/actions/GuildBanAdd.js +20 -0
  20. package/src/client/actions/GuildBanRemove.js +25 -0
  21. package/src/client/actions/GuildChannelsPositionUpdate.js +21 -0
  22. package/src/client/actions/GuildDelete.js +65 -0
  23. package/src/client/actions/GuildEmojiCreate.js +20 -0
  24. package/src/client/actions/GuildEmojiDelete.js +21 -0
  25. package/src/client/actions/GuildEmojiUpdate.js +20 -0
  26. package/src/client/actions/GuildEmojisUpdate.js +34 -0
  27. package/src/client/actions/GuildIntegrationsUpdate.js +19 -0
  28. package/src/client/actions/GuildMemberRemove.js +33 -0
  29. package/src/client/actions/GuildMemberUpdate.js +44 -0
  30. package/src/client/actions/GuildRoleCreate.js +25 -0
  31. package/src/client/actions/GuildRoleDelete.js +31 -0
  32. package/src/client/actions/GuildRoleUpdate.js +39 -0
  33. package/src/client/actions/GuildRolesPositionUpdate.js +21 -0
  34. package/src/client/actions/GuildScheduledEventCreate.js +27 -0
  35. package/src/client/actions/GuildScheduledEventDelete.js +31 -0
  36. package/src/client/actions/GuildScheduledEventUpdate.js +30 -0
  37. package/src/client/actions/GuildScheduledEventUserAdd.js +32 -0
  38. package/src/client/actions/GuildScheduledEventUserRemove.js +32 -0
  39. package/src/client/actions/GuildStickerCreate.js +20 -0
  40. package/src/client/actions/GuildStickerDelete.js +21 -0
  41. package/src/client/actions/GuildStickerUpdate.js +20 -0
  42. package/src/client/actions/GuildStickersUpdate.js +34 -0
  43. package/src/client/actions/GuildUpdate.js +33 -0
  44. package/src/client/actions/InviteCreate.js +28 -0
  45. package/src/client/actions/InviteDelete.js +30 -0
  46. package/src/client/actions/MessageCreate.js +50 -0
  47. package/src/client/actions/MessageDelete.js +34 -0
  48. package/src/client/actions/MessageDeleteBulk.js +43 -0
  49. package/src/client/actions/MessagePollVoteAdd.js +33 -0
  50. package/src/client/actions/MessagePollVoteRemove.js +33 -0
  51. package/src/client/actions/MessageReactionAdd.js +71 -0
  52. package/src/client/actions/MessageReactionRemove.js +39 -0
  53. package/src/client/actions/MessageReactionRemoveAll.js +36 -0
  54. package/src/client/actions/MessageReactionRemoveEmoji.js +30 -0
  55. package/src/client/actions/MessageUpdate.js +28 -0
  56. package/src/client/actions/PresenceUpdate.js +55 -0
  57. package/src/client/actions/StageInstanceCreate.js +28 -0
  58. package/src/client/actions/StageInstanceDelete.js +33 -0
  59. package/src/client/actions/StageInstanceUpdate.js +30 -0
  60. package/src/client/actions/ThreadCreate.js +24 -0
  61. package/src/client/actions/ThreadDelete.js +32 -0
  62. package/src/client/actions/ThreadListSync.js +60 -0
  63. package/src/client/actions/ThreadMemberUpdate.js +30 -0
  64. package/src/client/actions/ThreadMembersUpdate.js +38 -0
  65. package/src/client/actions/TypingStart.js +31 -0
  66. package/src/client/actions/UserUpdate.js +35 -0
  67. package/src/client/actions/VoiceStateUpdate.js +63 -0
  68. package/src/client/actions/WebhooksUpdate.js +20 -0
  69. package/src/client/voice/ClientVoiceManager.js +162 -0
  70. package/src/client/voice/StreamEventRouter.js +60 -0
  71. package/src/client/voice/VoiceConnection.js +1173 -0
  72. package/src/client/voice/dispatcher/AnnexBDispatcher.js +120 -0
  73. package/src/client/voice/dispatcher/AudioDispatcher.js +145 -0
  74. package/src/client/voice/dispatcher/BaseDispatcher.js +459 -0
  75. package/src/client/voice/dispatcher/VPxDispatcher.js +54 -0
  76. package/src/client/voice/dispatcher/VideoDispatcher.js +68 -0
  77. package/src/client/voice/networking/VoiceUDPClient.js +187 -0
  78. package/src/client/voice/networking/VoiceWebSocket.js +347 -0
  79. package/src/client/voice/player/MediaPlayer.js +321 -0
  80. package/src/client/voice/player/processing/AnnexBNalSplitter.js +244 -0
  81. package/src/client/voice/player/processing/IvfSplitter.js +106 -0
  82. package/src/client/voice/player/processing/PCMInsertSilence.js +37 -0
  83. package/src/client/voice/receiver/PacketHandler.js +260 -0
  84. package/src/client/voice/receiver/Receiver.js +96 -0
  85. package/src/client/voice/receiver/Recorder.js +191 -0
  86. package/src/client/voice/util/Function.js +116 -0
  87. package/src/client/voice/util/PlayInterface.js +122 -0
  88. package/src/client/voice/util/Secretbox.js +64 -0
  89. package/src/client/voice/util/Silence.js +16 -0
  90. package/src/client/voice/util/Socket.js +62 -0
  91. package/src/client/voice/util/VolumeInterface.js +104 -0
  92. package/src/client/websocket/DispatchTable.js +7 -0
  93. package/src/client/websocket/GatewaySendScheduler.js +122 -0
  94. package/src/client/websocket/WebSocketManager.js +439 -0
  95. package/src/client/websocket/WebSocketShard.js +1085 -0
  96. package/src/client/websocket/handlers/APPLICATION_COMMAND_CREATE.js +18 -0
  97. package/src/client/websocket/handlers/APPLICATION_COMMAND_DELETE.js +20 -0
  98. package/src/client/websocket/handlers/APPLICATION_COMMAND_PERMISSIONS_UPDATE.js +5 -0
  99. package/src/client/websocket/handlers/APPLICATION_COMMAND_UPDATE.js +20 -0
  100. package/src/client/websocket/handlers/AUTO_MODERATION_ACTION_EXECUTION.js +5 -0
  101. package/src/client/websocket/handlers/AUTO_MODERATION_RULE_CREATE.js +5 -0
  102. package/src/client/websocket/handlers/AUTO_MODERATION_RULE_DELETE.js +5 -0
  103. package/src/client/websocket/handlers/AUTO_MODERATION_RULE_UPDATE.js +5 -0
  104. package/src/client/websocket/handlers/CALL_CREATE.js +14 -0
  105. package/src/client/websocket/handlers/CALL_DELETE.js +11 -0
  106. package/src/client/websocket/handlers/CALL_UPDATE.js +11 -0
  107. package/src/client/websocket/handlers/CHANNEL_CREATE.js +5 -0
  108. package/src/client/websocket/handlers/CHANNEL_DELETE.js +5 -0
  109. package/src/client/websocket/handlers/CHANNEL_PINS_UPDATE.js +22 -0
  110. package/src/client/websocket/handlers/CHANNEL_RECIPIENT_ADD.js +19 -0
  111. package/src/client/websocket/handlers/CHANNEL_RECIPIENT_REMOVE.js +16 -0
  112. package/src/client/websocket/handlers/CHANNEL_UPDATE.js +16 -0
  113. package/src/client/websocket/handlers/GUILD_AUDIT_LOG_ENTRY_CREATE.js +5 -0
  114. package/src/client/websocket/handlers/GUILD_BAN_ADD.js +5 -0
  115. package/src/client/websocket/handlers/GUILD_BAN_REMOVE.js +5 -0
  116. package/src/client/websocket/handlers/GUILD_CREATE.js +51 -0
  117. package/src/client/websocket/handlers/GUILD_DELETE.js +5 -0
  118. package/src/client/websocket/handlers/GUILD_EMOJIS_UPDATE.js +5 -0
  119. package/src/client/websocket/handlers/GUILD_INTEGRATIONS_UPDATE.js +5 -0
  120. package/src/client/websocket/handlers/GUILD_MEMBERS_CHUNK.js +45 -0
  121. package/src/client/websocket/handlers/GUILD_MEMBER_ADD.js +20 -0
  122. package/src/client/websocket/handlers/GUILD_MEMBER_REMOVE.js +5 -0
  123. package/src/client/websocket/handlers/GUILD_MEMBER_UPDATE.js +5 -0
  124. package/src/client/websocket/handlers/GUILD_ROLE_CREATE.js +5 -0
  125. package/src/client/websocket/handlers/GUILD_ROLE_DELETE.js +5 -0
  126. package/src/client/websocket/handlers/GUILD_ROLE_UPDATE.js +5 -0
  127. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_CREATE.js +5 -0
  128. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_DELETE.js +5 -0
  129. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_UPDATE.js +5 -0
  130. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_USER_ADD.js +5 -0
  131. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_USER_REMOVE.js +5 -0
  132. package/src/client/websocket/handlers/GUILD_STICKERS_UPDATE.js +5 -0
  133. package/src/client/websocket/handlers/GUILD_UPDATE.js +5 -0
  134. package/src/client/websocket/handlers/INTERACTION_MODAL_CREATE.js +12 -0
  135. package/src/client/websocket/handlers/INVITE_CREATE.js +5 -0
  136. package/src/client/websocket/handlers/INVITE_DELETE.js +5 -0
  137. package/src/client/websocket/handlers/MESSAGE_CREATE.js +5 -0
  138. package/src/client/websocket/handlers/MESSAGE_DELETE.js +5 -0
  139. package/src/client/websocket/handlers/MESSAGE_DELETE_BULK.js +5 -0
  140. package/src/client/websocket/handlers/MESSAGE_POLL_VOTE_ADD.js +5 -0
  141. package/src/client/websocket/handlers/MESSAGE_POLL_VOTE_REMOVE.js +5 -0
  142. package/src/client/websocket/handlers/MESSAGE_REACTION_ADD.js +5 -0
  143. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE.js +5 -0
  144. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE_ALL.js +5 -0
  145. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE_EMOJI.js +5 -0
  146. package/src/client/websocket/handlers/MESSAGE_UPDATE.js +16 -0
  147. package/src/client/websocket/handlers/PRESENCE_UPDATE.js +5 -0
  148. package/src/client/websocket/handlers/READY.js +156 -0
  149. package/src/client/websocket/handlers/RELATIONSHIP_ADD.js +19 -0
  150. package/src/client/websocket/handlers/RELATIONSHIP_REMOVE.js +17 -0
  151. package/src/client/websocket/handlers/RELATIONSHIP_UPDATE.js +41 -0
  152. package/src/client/websocket/handlers/RESUMED.js +14 -0
  153. package/src/client/websocket/handlers/STAGE_INSTANCE_CREATE.js +5 -0
  154. package/src/client/websocket/handlers/STAGE_INSTANCE_DELETE.js +5 -0
  155. package/src/client/websocket/handlers/STAGE_INSTANCE_UPDATE.js +5 -0
  156. package/src/client/websocket/handlers/THREAD_CREATE.js +5 -0
  157. package/src/client/websocket/handlers/THREAD_DELETE.js +5 -0
  158. package/src/client/websocket/handlers/THREAD_LIST_SYNC.js +5 -0
  159. package/src/client/websocket/handlers/THREAD_MEMBERS_UPDATE.js +5 -0
  160. package/src/client/websocket/handlers/THREAD_MEMBER_UPDATE.js +5 -0
  161. package/src/client/websocket/handlers/THREAD_UPDATE.js +16 -0
  162. package/src/client/websocket/handlers/TYPING_START.js +5 -0
  163. package/src/client/websocket/handlers/USER_GUILD_SETTINGS_UPDATE.js +6 -0
  164. package/src/client/websocket/handlers/USER_NOTE_UPDATE.js +5 -0
  165. package/src/client/websocket/handlers/USER_REQUIRED_ACTION_UPDATE.js +82 -0
  166. package/src/client/websocket/handlers/USER_SETTINGS_UPDATE.js +5 -0
  167. package/src/client/websocket/handlers/USER_UPDATE.js +5 -0
  168. package/src/client/websocket/handlers/VOICE_CHANNEL_EFFECT_SEND.js +16 -0
  169. package/src/client/websocket/handlers/VOICE_CHANNEL_STATUS_UPDATE.js +12 -0
  170. package/src/client/websocket/handlers/VOICE_SERVER_UPDATE.js +12 -0
  171. package/src/client/websocket/handlers/VOICE_STATE_UPDATE.js +5 -0
  172. package/src/client/websocket/handlers/WEBHOOKS_UPDATE.js +5 -0
  173. package/src/client/websocket/handlers/index.js +84 -0
  174. package/src/errors/DJSError.js +61 -0
  175. package/src/errors/Messages.js +218 -0
  176. package/src/errors/index.js +4 -0
  177. package/src/index.js +172 -0
  178. package/src/managers/ApplicationCommandManager.js +264 -0
  179. package/src/managers/ApplicationCommandPermissionsManager.js +417 -0
  180. package/src/managers/AutoModerationRuleManager.js +296 -0
  181. package/src/managers/BaseGuildEmojiManager.js +80 -0
  182. package/src/managers/BaseManager.js +19 -0
  183. package/src/managers/BillingManager.js +66 -0
  184. package/src/managers/CachedManager.js +72 -0
  185. package/src/managers/ChannelManager.js +148 -0
  186. package/src/managers/ClientUserSettingManager.js +372 -0
  187. package/src/managers/DataManager.js +61 -0
  188. package/src/managers/DeveloperManager.js +265 -0
  189. package/src/managers/GuildBanManager.js +252 -0
  190. package/src/managers/GuildChannelManager.js +488 -0
  191. package/src/managers/GuildEmojiManager.js +171 -0
  192. package/src/managers/GuildEmojiRoleManager.js +118 -0
  193. package/src/managers/GuildForumThreadManager.js +108 -0
  194. package/src/managers/GuildInviteManager.js +213 -0
  195. package/src/managers/GuildManager.js +401 -0
  196. package/src/managers/GuildMemberManager.js +608 -0
  197. package/src/managers/GuildMemberRoleManager.js +195 -0
  198. package/src/managers/GuildScheduledEventManager.js +314 -0
  199. package/src/managers/GuildSettingManager.js +155 -0
  200. package/src/managers/GuildStickerManager.js +179 -0
  201. package/src/managers/GuildTextThreadManager.js +98 -0
  202. package/src/managers/InteractionManager.js +39 -0
  203. package/src/managers/MessageManager.js +457 -0
  204. package/src/managers/PermissionOverwriteManager.js +169 -0
  205. package/src/managers/PresenceManager.js +71 -0
  206. package/src/managers/QuestManager.js +391 -0
  207. package/src/managers/ReactionManager.js +67 -0
  208. package/src/managers/ReactionUserManager.js +73 -0
  209. package/src/managers/RelationshipManager.js +341 -0
  210. package/src/managers/RoleManager.js +448 -0
  211. package/src/managers/SessionManager.js +66 -0
  212. package/src/managers/StageInstanceManager.js +162 -0
  213. package/src/managers/ThreadManager.js +175 -0
  214. package/src/managers/ThreadMemberManager.js +186 -0
  215. package/src/managers/UserManager.js +274 -0
  216. package/src/managers/UserNoteManager.js +53 -0
  217. package/src/managers/VoiceStateManager.js +59 -0
  218. package/src/rest/APIRequest.js +198 -0
  219. package/src/rest/APIRouter.js +94 -0
  220. package/src/rest/DiscordAPIError.js +120 -0
  221. package/src/rest/HTTPError.js +62 -0
  222. package/src/rest/RESTManager.js +203 -0
  223. package/src/rest/RateLimitCoordinator.js +156 -0
  224. package/src/rest/RateLimitError.js +55 -0
  225. package/src/rest/RequestHandler.js +552 -0
  226. package/src/sharding/Shard.js +444 -0
  227. package/src/sharding/ShardClientUtil.js +279 -0
  228. package/src/sharding/ShardingManager.js +319 -0
  229. package/src/structures/AnonymousGuild.js +98 -0
  230. package/src/structures/ApplicationCommand.js +593 -0
  231. package/src/structures/ApplicationRoleConnectionMetadata.js +48 -0
  232. package/src/structures/AutoModerationActionExecution.js +89 -0
  233. package/src/structures/AutoModerationRule.js +294 -0
  234. package/src/structures/AutocompleteInteraction.js +107 -0
  235. package/src/structures/Base.js +43 -0
  236. package/src/structures/BaseCommandInteraction.js +211 -0
  237. package/src/structures/BaseGuild.js +124 -0
  238. package/src/structures/BaseGuildEmoji.js +56 -0
  239. package/src/structures/BaseGuildTextChannel.js +191 -0
  240. package/src/structures/BaseGuildVoiceChannel.js +241 -0
  241. package/src/structures/BaseMessageComponent.js +181 -0
  242. package/src/structures/ButtonInteraction.js +11 -0
  243. package/src/structures/CallState.js +63 -0
  244. package/src/structures/CategoryChannel.js +85 -0
  245. package/src/structures/Channel.js +284 -0
  246. package/src/structures/ClientPresence.js +77 -0
  247. package/src/structures/ClientUser.js +706 -0
  248. package/src/structures/CommandInteraction.js +41 -0
  249. package/src/structures/CommandInteractionOptionResolver.js +276 -0
  250. package/src/structures/ContainerComponent.js +68 -0
  251. package/src/structures/ContextMenuInteraction.js +65 -0
  252. package/src/structures/DMChannel.js +222 -0
  253. package/src/structures/DirectoryChannel.js +20 -0
  254. package/src/structures/Emoji.js +148 -0
  255. package/src/structures/FileComponent.js +49 -0
  256. package/src/structures/ForumChannel.js +31 -0
  257. package/src/structures/GroupDMChannel.js +415 -0
  258. package/src/structures/Guild.js +1804 -0
  259. package/src/structures/GuildAuditLogs.js +746 -0
  260. package/src/structures/GuildBan.js +59 -0
  261. package/src/structures/GuildBoost.js +108 -0
  262. package/src/structures/GuildChannel.js +470 -0
  263. package/src/structures/GuildEmoji.js +161 -0
  264. package/src/structures/GuildMember.js +636 -0
  265. package/src/structures/GuildPreview.js +191 -0
  266. package/src/structures/GuildPreviewEmoji.js +27 -0
  267. package/src/structures/GuildScheduledEvent.js +536 -0
  268. package/src/structures/GuildTemplate.js +236 -0
  269. package/src/structures/Integration.js +188 -0
  270. package/src/structures/IntegrationApplication.js +96 -0
  271. package/src/structures/Interaction.js +290 -0
  272. package/src/structures/InteractionCollector.js +248 -0
  273. package/src/structures/InteractionWebhook.js +43 -0
  274. package/src/structures/Invite.js +358 -0
  275. package/src/structures/InviteGuild.js +23 -0
  276. package/src/structures/InviteStageInstance.js +86 -0
  277. package/src/structures/MediaChannel.js +11 -0
  278. package/src/structures/MediaGalleryComponent.js +41 -0
  279. package/src/structures/MediaGalleryItem.js +47 -0
  280. package/src/structures/Message.js +1272 -0
  281. package/src/structures/MessageActionRow.js +105 -0
  282. package/src/structures/MessageAttachment.js +216 -0
  283. package/src/structures/MessageButton.js +166 -0
  284. package/src/structures/MessageCollector.js +146 -0
  285. package/src/structures/MessageComponentInteraction.js +120 -0
  286. package/src/structures/MessageContextMenuInteraction.js +20 -0
  287. package/src/structures/MessageEmbed.js +596 -0
  288. package/src/structures/MessageMentions.js +273 -0
  289. package/src/structures/MessagePayload.js +354 -0
  290. package/src/structures/MessageReaction.js +181 -0
  291. package/src/structures/MessageSelectMenu.js +141 -0
  292. package/src/structures/Modal.js +161 -0
  293. package/src/structures/ModalSubmitFieldsResolver.js +53 -0
  294. package/src/structures/ModalSubmitInteraction.js +119 -0
  295. package/src/structures/NewsChannel.js +32 -0
  296. package/src/structures/OAuth2Guild.js +28 -0
  297. package/src/structures/PermissionOverwrites.js +198 -0
  298. package/src/structures/Poll.js +108 -0
  299. package/src/structures/PollAnswer.js +88 -0
  300. package/src/structures/Presence.js +1165 -0
  301. package/src/structures/ReactionCollector.js +229 -0
  302. package/src/structures/ReactionEmoji.js +31 -0
  303. package/src/structures/Role.js +590 -0
  304. package/src/structures/SectionComponent.js +48 -0
  305. package/src/structures/SelectMenuInteraction.js +21 -0
  306. package/src/structures/SeparatorComponent.js +48 -0
  307. package/src/structures/Session.js +81 -0
  308. package/src/structures/StageChannel.js +104 -0
  309. package/src/structures/StageInstance.js +208 -0
  310. package/src/structures/Sticker.js +310 -0
  311. package/src/structures/StickerPack.js +95 -0
  312. package/src/structures/StoreChannel.js +56 -0
  313. package/src/structures/Team.js +118 -0
  314. package/src/structures/TeamMember.js +80 -0
  315. package/src/structures/TextChannel.js +33 -0
  316. package/src/structures/TextDisplayComponent.js +40 -0
  317. package/src/structures/TextInputComponent.js +132 -0
  318. package/src/structures/ThreadChannel.js +605 -0
  319. package/src/structures/ThreadMember.js +105 -0
  320. package/src/structures/ThreadOnlyChannel.js +249 -0
  321. package/src/structures/ThumbnailComponent.js +57 -0
  322. package/src/structures/Typing.js +74 -0
  323. package/src/structures/UnfurledMediaItem.js +29 -0
  324. package/src/structures/User.js +992 -0
  325. package/src/structures/UserContextMenuInteraction.js +29 -0
  326. package/src/structures/VoiceChannel.js +110 -0
  327. package/src/structures/VoiceChannelEffect.js +69 -0
  328. package/src/structures/VoiceRegion.js +53 -0
  329. package/src/structures/VoiceState.js +354 -0
  330. package/src/structures/WebEmbed.js +373 -0
  331. package/src/structures/Webhook.js +478 -0
  332. package/src/structures/WelcomeChannel.js +60 -0
  333. package/src/structures/WelcomeScreen.js +48 -0
  334. package/src/structures/Widget.js +87 -0
  335. package/src/structures/WidgetMember.js +100 -0
  336. package/src/structures/interfaces/Application.js +953 -0
  337. package/src/structures/interfaces/Collector.js +301 -0
  338. package/src/structures/interfaces/InteractionResponses.js +313 -0
  339. package/src/structures/interfaces/TextBasedChannel.js +821 -0
  340. package/src/util/APITypes.js +59 -0
  341. package/src/util/ActivityFlags.js +44 -0
  342. package/src/util/ApplicationFlags.js +76 -0
  343. package/src/util/AttachmentFlags.js +38 -0
  344. package/src/util/BitField.js +170 -0
  345. package/src/util/ChannelFlags.js +45 -0
  346. package/src/util/Constants.js +1953 -0
  347. package/src/util/DataResolver.js +162 -0
  348. package/src/util/FastQueue.js +93 -0
  349. package/src/util/FetchUtil.js +77 -0
  350. package/src/util/Formatters.js +228 -0
  351. package/src/util/GuildMemberFlags.js +43 -0
  352. package/src/util/Intents.js +74 -0
  353. package/src/util/InviteFlags.js +34 -0
  354. package/src/util/LimitedCollection.js +131 -0
  355. package/src/util/ListenerUtil.js +12 -0
  356. package/src/util/MessageFlags.js +63 -0
  357. package/src/util/Options.js +431 -0
  358. package/src/util/Permissions.js +202 -0
  359. package/src/util/PremiumUsageFlags.js +31 -0
  360. package/src/util/PurchasedFlags.js +33 -0
  361. package/src/util/RemoteAuth.js +425 -0
  362. package/src/util/RoleFlags.js +37 -0
  363. package/src/util/SnowflakeUtil.js +92 -0
  364. package/src/util/Speaking.js +33 -0
  365. package/src/util/Sweepers.js +493 -0
  366. package/src/util/SystemChannelFlags.js +55 -0
  367. package/src/util/ThreadMemberFlags.js +30 -0
  368. package/src/util/UserFlags.js +104 -0
  369. package/src/util/Util.js +1144 -0
  370. package/typings/enums.d.ts +437 -0
  371. package/typings/index.d.ts +8857 -0
  372. package/typings/index.test-d.ts +0 -0
  373. package/typings/rawDataTypes.d.ts +403 -0
@@ -0,0 +1,1076 @@
1
+ /* eslint-disable no-unreachable */
2
+ 'use strict';
3
+
4
+ const process = require('node:process');
5
+ const { setInterval } = require('node:timers');
6
+ const { setTimeout } = require('node:timers');
7
+ const { Collection } = require('@discordjs/collection');
8
+ const { authenticator } = require('otplib');
9
+ const BaseClient = require('./BaseClient');
10
+ const ActionsManager = require('./actions/ActionsManager');
11
+ const ClientVoiceManager = require('./voice/ClientVoiceManager');
12
+ const WebSocketManager = require('./websocket/WebSocketManager');
13
+ const { Error, TypeError } = require('../errors');
14
+ const BaseGuildEmojiManager = require('../managers/BaseGuildEmojiManager');
15
+ const BillingManager = require('../managers/BillingManager');
16
+ const ChannelManager = require('../managers/ChannelManager');
17
+ const ClientUserSettingManager = require('../managers/ClientUserSettingManager');
18
+ const DeveloperManager = require('../managers/DeveloperManager');
19
+ const GuildManager = require('../managers/GuildManager');
20
+ const PresenceManager = require('../managers/PresenceManager');
21
+ const QuestManager = require('../managers/QuestManager');
22
+ const RelationshipManager = require('../managers/RelationshipManager');
23
+ const SessionManager = require('../managers/SessionManager');
24
+ const UserManager = require('../managers/UserManager');
25
+ const UserNoteManager = require('../managers/UserNoteManager');
26
+ const VoiceStateManager = require('../managers/VoiceStateManager');
27
+ const ShardClientUtil = require('../sharding/ShardClientUtil');
28
+ const ClientPresence = require('../structures/ClientPresence');
29
+ const GuildPreview = require('../structures/GuildPreview');
30
+ const GuildTemplate = require('../structures/GuildTemplate');
31
+ const Invite = require('../structures/Invite');
32
+ const { Sticker } = require('../structures/Sticker');
33
+ const StickerPack = require('../structures/StickerPack');
34
+ const VoiceRegion = require('../structures/VoiceRegion');
35
+ const Webhook = require('../structures/Webhook');
36
+ const Widget = require('../structures/Widget');
37
+ const Application = require('../structures/interfaces/Application');
38
+ const { Events, Status } = require('../util/Constants');
39
+ const DataResolver = require('../util/DataResolver');
40
+ const Intents = require('../util/Intents');
41
+ const DiscordAuthWebsocket = require('../util/RemoteAuth');
42
+ const Sweepers = require('../util/Sweepers');
43
+ const TOKEN_PREFIX_REGEX = /^(Bot|Bearer)\s*/i;
44
+ const INVITE_ROUTE_FALLBACK_STATUSES = new Set([404, 405, 501]);
45
+ const INVITE_NOT_FOUND_API_CODE = 10006;
46
+
47
+ function getRequestStatus(error) {
48
+ if (typeof error?.httpStatus === 'number') return error.httpStatus;
49
+ if (typeof error?.code === 'number') return error.code;
50
+ return null;
51
+ }
52
+
53
+ function shouldFallbackToLegacyInviteRoute(error, inviteCode) {
54
+ if (!error) return false;
55
+
56
+ if (error.name === 'DiscordAPIError' && error.code === INVITE_NOT_FOUND_API_CODE) {
57
+ return false;
58
+ }
59
+
60
+ const status = getRequestStatus(error);
61
+ if (!INVITE_ROUTE_FALLBACK_STATUSES.has(status)) return false;
62
+
63
+ if (typeof error.path !== 'string' || error.path.length === 0) return true;
64
+ return error.path.startsWith(`/invites/${inviteCode}`);
65
+ }
66
+
67
+ /**
68
+ * The main hub for interacting with the Discord API, and the starting point for any bot.
69
+ * @extends {BaseClient}
70
+ */
71
+ class Client extends BaseClient {
72
+ /**
73
+ * @param {ClientOptions} [options] Options for the client
74
+ */
75
+ constructor(options) {
76
+ super(options);
77
+
78
+ this._validateOptions();
79
+
80
+ /**
81
+ * Functions called when a cache is garbage collected or the Client is destroyed
82
+ * @type {Set<Function>}
83
+ * @private
84
+ */
85
+ this._cleanups = new Set();
86
+
87
+ /**
88
+ * The finalizers used to cleanup items.
89
+ * @type {FinalizationRegistry}
90
+ * @private
91
+ */
92
+ this._finalizers = new FinalizationRegistry(this._finalize.bind(this));
93
+
94
+ /**
95
+ * The WebSocket manager of the client
96
+ * @type {WebSocketManager}
97
+ */
98
+ this.ws = new WebSocketManager(this);
99
+
100
+ /**
101
+ * The action manager of the client
102
+ * @type {ActionsManager}
103
+ * @private
104
+ */
105
+ this.actions = new ActionsManager(this);
106
+
107
+ /**
108
+ * The voice manager of the client
109
+ * @type {ClientVoiceManager}
110
+ */
111
+ this.voice = new ClientVoiceManager(this);
112
+
113
+ /**
114
+ * A manager of the voice states of this client (Support DM / Group DM)
115
+ * @type {VoiceStateManager}
116
+ */
117
+ this.voiceStates = new VoiceStateManager({ client: this });
118
+
119
+ /**
120
+ * Shard helpers for the client (only if the process was spawned from a {@link ShardingManager})
121
+ * @type {?ShardClientUtil}
122
+ */
123
+ this.shard = process.env.SHARDING_MANAGER
124
+ ? ShardClientUtil.singleton(this, process.env.SHARDING_MANAGER_MODE)
125
+ : null;
126
+
127
+ /**
128
+ * The user manager of this client
129
+ * @type {UserManager}
130
+ */
131
+ this.users = new UserManager(this);
132
+
133
+ /**
134
+ * A manager of all the guilds the client is currently handling -
135
+ * as long as sharding isn't being used, this will be *every* guild the bot is a member of
136
+ * @type {GuildManager}
137
+ */
138
+ this.guilds = new GuildManager(this);
139
+
140
+ /**
141
+ * All of the {@link Channel}s that the client is currently handling -
142
+ * as long as sharding isn't being used, this will be *every* channel in *every* guild the bot
143
+ * is a member of. Note that DM channels will not be initially cached, and thus not be present
144
+ * in the Manager without their explicit fetching or use.
145
+ * @type {ChannelManager}
146
+ */
147
+ this.channels = new ChannelManager(this);
148
+
149
+ /**
150
+ * The sweeping functions and their intervals used to periodically sweep caches
151
+ * @type {Sweepers}
152
+ */
153
+ this.sweepers = new Sweepers(this, this.options.sweepers);
154
+
155
+ /**
156
+ * The presence of the Client
157
+ * @private
158
+ * @type {ClientPresence}
159
+ */
160
+ this.presence = new ClientPresence(this, this.options.presence);
161
+
162
+ /**
163
+ * A manager of the presences belonging to this client
164
+ * @type {PresenceManager}
165
+ */
166
+ this.presences = new PresenceManager(this);
167
+
168
+ /**
169
+ * All of the note that have been cached at any point, mapped by their ids
170
+ * @type {UserManager}
171
+ */
172
+ this.notes = new UserNoteManager(this);
173
+
174
+ /**
175
+ * All of the relationships {@link User}
176
+ * @type {RelationshipManager}
177
+ */
178
+ this.relationships = new RelationshipManager(this);
179
+
180
+ /**
181
+ * Manages the API methods
182
+ * @type {BillingManager}
183
+ */
184
+ this.billing = new BillingManager(this);
185
+
186
+ /**
187
+ * Manages developer applications
188
+ * @type {DeveloperManager}
189
+ */
190
+ this.developers = new DeveloperManager(this);
191
+
192
+ /**
193
+ * Manages quest-related API methods
194
+ * @type {QuestManager}
195
+ */
196
+ this.quests = new QuestManager(this);
197
+
198
+ /**
199
+ * All of the sessions of the client
200
+ * @type {SessionManager}
201
+ */
202
+ this.sessions = new SessionManager(this);
203
+
204
+ /**
205
+ * All of the settings {@link Object}
206
+ * @type {ClientUserSettingManager}
207
+ */
208
+ this.settings = new ClientUserSettingManager(this);
209
+
210
+ this._emojiCacheDirty = true;
211
+ this._emojiManager = null;
212
+ this._invalidateEmojiCache = () => {
213
+ this._emojiCacheDirty = true;
214
+ };
215
+ this.on(Events.GUILD_CREATE, this._invalidateEmojiCache);
216
+ this.on(Events.GUILD_DELETE, this._invalidateEmojiCache);
217
+ this.on(Events.GUILD_EMOJI_CREATE, this._invalidateEmojiCache);
218
+ this.on(Events.GUILD_EMOJI_DELETE, this._invalidateEmojiCache);
219
+ this.on(Events.GUILD_EMOJI_UPDATE, this._invalidateEmojiCache);
220
+ this.on(Events.GUILD_EMOJIS_UPDATE, this._invalidateEmojiCache);
221
+ this.on(Events.GUILD_UNAVAILABLE, this._invalidateEmojiCache);
222
+
223
+ Object.defineProperty(this, 'token', { writable: true });
224
+ if (!this.token && 'DISCORD_TOKEN' in process.env) {
225
+ /**
226
+ * Authorization token for the logged in bot.
227
+ * If present, this defaults to `process.env.DISCORD_TOKEN` when instantiating the client
228
+ * <warn>This should be kept private at all times.</warn>
229
+ * @type {?string}
230
+ */
231
+ this.token = process.env.DISCORD_TOKEN;
232
+ } else {
233
+ this.token = null;
234
+ }
235
+
236
+ /**
237
+ * User that the client is logged in as
238
+ * @type {?ClientUser}
239
+ */
240
+ this.user = null;
241
+
242
+ /**
243
+ * Time at which the client was last regarded as being in the `READY` state
244
+ * (each time the client disconnects and successfully reconnects, this will be overwritten)
245
+ * @type {?Date}
246
+ */
247
+ this.readyAt = null;
248
+
249
+ /**
250
+ * The authenticator used for TOTP
251
+ * @type {Object}
252
+ */
253
+ this.authenticator = authenticator;
254
+
255
+ this.authenticator.options = {
256
+ step: 30,
257
+ digits: 6,
258
+ algorithm: 'sha1',
259
+ };
260
+
261
+ if (this.options.messageSweepInterval > 0) {
262
+ process.emitWarning(
263
+ 'The message sweeping client options are deprecated, use the global sweepers instead.',
264
+ 'DeprecationWarning',
265
+ );
266
+ this.sweepMessageInterval = setInterval(
267
+ this.sweepMessages.bind(this),
268
+ this.options.messageSweepInterval * 1_000,
269
+ ).unref();
270
+ }
271
+ }
272
+
273
+ /**
274
+ * A manager of all the custom emojis that the client has access to
275
+ * @type {BaseGuildEmojiManager}
276
+ * @readonly
277
+ */
278
+ get emojis() {
279
+ if (this._emojiCacheDirty || !this._emojiManager) {
280
+ this._emojiManager = this._buildEmojiCache();
281
+ this._emojiCacheDirty = false;
282
+ }
283
+ return this._emojiManager;
284
+ }
285
+
286
+ _buildEmojiCache() {
287
+ const emojis = new BaseGuildEmojiManager(this);
288
+ for (const guild of this.guilds.cache.values()) {
289
+ if (!guild.available) continue;
290
+ for (const emoji of guild.emojis.cache.values()) {
291
+ emojis.cache.set(emoji.id, emoji);
292
+ }
293
+ }
294
+ return emojis;
295
+ }
296
+
297
+ /**
298
+ * Timestamp of the time the client was last `READY` at
299
+ * @type {?number}
300
+ * @readonly
301
+ */
302
+ get readyTimestamp() {
303
+ return this.readyAt?.getTime() ?? null;
304
+ }
305
+
306
+ /**
307
+ * How long it has been since the client last entered the `READY` state in milliseconds
308
+ * @type {?number}
309
+ * @readonly
310
+ */
311
+ get uptime() {
312
+ return this.readyAt ? Date.now() - this.readyAt : null;
313
+ }
314
+
315
+ /**
316
+ * Logs the client in, establishing a WebSocket connection to Discord.
317
+ * @param {string} [token=this.token] Token of the account to log in with
318
+ * @returns {Promise<string>} Token of the account used
319
+ * @example
320
+ * client.login('my token');
321
+ */
322
+ async login(token = this.token) {
323
+ if (!token || typeof token !== 'string') throw new Error('TOKEN_INVALID');
324
+ this.token = token = token.replace(TOKEN_PREFIX_REGEX, '');
325
+ this.emit(
326
+ Events.DEBUG,
327
+ `
328
+ Logging on with a user token is unfortunately against the Discord
329
+ \`Terms of Service\` <https://support.discord.com/hc/en-us/articles/115002192352>
330
+ and doing so might potentially get your account banned.
331
+ Use this at your own risk.`,
332
+ );
333
+ this.emit(
334
+ Events.DEBUG,
335
+ `Provided token: ${token
336
+ .split('.')
337
+ .map((val, i) => (i > 1 ? val.replace(/./g, '*') : val))
338
+ .join('.')}`,
339
+ );
340
+
341
+ if (this.options.presence) {
342
+ this.options.ws.presence = this.presence._parse(this.options.presence);
343
+ }
344
+
345
+ this.emit(Events.DEBUG, 'Preparing to connect to the gateway...');
346
+
347
+ try {
348
+ await this.ws.connect();
349
+ return this.token;
350
+ } catch (error) {
351
+ this.destroy();
352
+ throw error;
353
+ }
354
+ }
355
+
356
+ QRLogin() {
357
+ const ws = new DiscordAuthWebsocket();
358
+ ws.once('ready', () => ws.generateQR());
359
+ return ws.connect(this);
360
+ }
361
+
362
+ /**
363
+ * Logs the client in, establishing a WebSocket connection to Discord.
364
+ * @param {string} email The email associated with the account
365
+ * @param {string} password The password assicated with the account
366
+ * @returns {string | null} Token of the account used
367
+ *
368
+ * @example
369
+ * client.passLogin("test@gmail.com", "SuperSecretPa$$word", 1234)
370
+ * @deprecated This method will not be updated until I find the most convenient way to implement MFA.
371
+ */
372
+ async passLogin(email, password) {
373
+ const initial = await this.api.auth.login.post({
374
+ auth: false,
375
+ versioned: true,
376
+ data: { gift_code_sku_id: null, login_source: null, undelete: false, login: email, password },
377
+ });
378
+
379
+ if ('token' in initial) {
380
+ return this.login(initial.token);
381
+ } else if ('ticket' in initial) {
382
+ if (!this.options.TOTPKey) throw new Error('TOTPKEY_MISSING');
383
+ const otp = this.authenticator.generate(this.options.TOTPKey);
384
+ const totp = await this.api.auth.mfa.totp.post({
385
+ auth: false,
386
+ versioned: true,
387
+ data: { gift_code_sku_id: null, login_source: null, code: otp, ticket: initial.ticket },
388
+ });
389
+ if ('token' in totp) {
390
+ return this.login(totp.token);
391
+ }
392
+ }
393
+
394
+ return null;
395
+ }
396
+
397
+ /**
398
+ * Returns whether the client has logged in, indicative of being able to access
399
+ * properties such as `user` and `application`.
400
+ * @returns {boolean}
401
+ */
402
+ isReady() {
403
+ return !this.ws.destroyed && this.ws.status === Status.READY;
404
+ }
405
+
406
+ /**
407
+ * Logs out, terminates the connection to Discord, and destroys the client.
408
+ * @returns {void}
409
+ */
410
+ destroy() {
411
+ super.destroy();
412
+
413
+ if (this._invalidateEmojiCache) {
414
+ this.off(Events.GUILD_CREATE, this._invalidateEmojiCache);
415
+ this.off(Events.GUILD_DELETE, this._invalidateEmojiCache);
416
+ this.off(Events.GUILD_EMOJI_CREATE, this._invalidateEmojiCache);
417
+ this.off(Events.GUILD_EMOJI_DELETE, this._invalidateEmojiCache);
418
+ this.off(Events.GUILD_EMOJI_UPDATE, this._invalidateEmojiCache);
419
+ this.off(Events.GUILD_EMOJIS_UPDATE, this._invalidateEmojiCache);
420
+ this.off(Events.GUILD_UNAVAILABLE, this._invalidateEmojiCache);
421
+ }
422
+
423
+ for (const fn of this._cleanups) fn();
424
+ this._cleanups.clear();
425
+
426
+ if (this.sweepMessageInterval) clearInterval(this.sweepMessageInterval);
427
+
428
+ this.sweepers.destroy();
429
+ this.ws.destroy();
430
+ this._emojiManager = null;
431
+ this._emojiCacheDirty = true;
432
+ this.token = null;
433
+ }
434
+
435
+ /**
436
+ * Logs out, terminates the connection to Discord, destroys the client and destroys the token.
437
+ * @returns {Promise<void>}
438
+ */
439
+ async logout() {
440
+ await this.api.auth.logout.post({
441
+ data: {
442
+ provider: null,
443
+ voip_provider: null,
444
+ },
445
+ });
446
+ return this.destroy();
447
+ }
448
+
449
+ /**
450
+ * Options used when fetching an invite from Discord.
451
+ * @typedef {Object} ClientFetchInviteOptions
452
+ * @property {Snowflake} [guildScheduledEventId] The id of the guild scheduled event to include with
453
+ * the invite
454
+ */
455
+
456
+ /**
457
+ * Obtains an invite from Discord.
458
+ * @param {InviteResolvable} invite Invite code or URL
459
+ * @param {ClientFetchInviteOptions} [options] Options for fetching the invite
460
+ * @returns {Promise<Invite>}
461
+ * @example
462
+ * client.fetchInvite('https://discord.gg/djs')
463
+ * .then(invite => console.log(`Obtained invite with code: ${invite.code}`))
464
+ * .catch(console.error);
465
+ */
466
+ async fetchInvite(invite, options) {
467
+ const code = DataResolver.resolveInviteCode(invite);
468
+ const query = { with_counts: true, guild_scheduled_event_id: options?.guildScheduledEventId };
469
+
470
+ try {
471
+ const data = await this.api.invites(code).get({ query });
472
+ return new Invite(this, data);
473
+ } catch (error) {
474
+ if (!shouldFallbackToLegacyInviteRoute(error, code)) throw error;
475
+ const data = await this.api.invite(code).get({ query });
476
+ return new Invite(this, data);
477
+ }
478
+ }
479
+
480
+ /**
481
+ * Obtains a template from Discord.
482
+ * @param {GuildTemplateResolvable} template Template code or URL
483
+ * @returns {Promise<GuildTemplate>}
484
+ * @example
485
+ * client.fetchGuildTemplate('https://discord.new/FKvmczH2HyUf')
486
+ * .then(template => console.log(`Obtained template with code: ${template.code}`))
487
+ * .catch(console.error);
488
+ */
489
+ async fetchGuildTemplate(template) {
490
+ const code = DataResolver.resolveGuildTemplateCode(template);
491
+ const data = await this.api.guilds.templates(code).get();
492
+ return new GuildTemplate(this, data);
493
+ }
494
+
495
+ /**
496
+ * Obtains a webhook from Discord.
497
+ * @param {Snowflake} id The webhook's id
498
+ * @param {string} [token] Token for the webhook
499
+ * @returns {Promise<Webhook>}
500
+ * @example
501
+ * client.fetchWebhook('id', 'token')
502
+ * .then(webhook => console.log(`Obtained webhook with name: ${webhook.name}`))
503
+ * .catch(console.error);
504
+ */
505
+ async fetchWebhook(id, token) {
506
+ const data = await this.api.webhooks(id, token).get();
507
+ return new Webhook(this, { token, ...data });
508
+ }
509
+
510
+ /**
511
+ * Obtains the available voice regions from Discord.
512
+ * @returns {Promise<Collection<string, VoiceRegion>>}
513
+ * @example
514
+ * client.fetchVoiceRegions()
515
+ * .then(regions => console.log(`Available regions are: ${regions.map(region => region.name).join(', ')}`))
516
+ * .catch(console.error);
517
+ */
518
+ async fetchVoiceRegions() {
519
+ const apiRegions = await this.api.voice.regions.get();
520
+ const regions = new Collection();
521
+ for (const region of apiRegions) regions.set(region.id, new VoiceRegion(region));
522
+ return regions;
523
+ }
524
+
525
+ /**
526
+ * Requests a sync of guild data with Discord. Only works for user accounts.
527
+ * @param {Guild[]|Collection<Snowflake, Guild>} [guilds=this.guilds] Guilds to sync
528
+ * @returns {void}
529
+ */
530
+ syncGuilds(guilds = this.guilds) {
531
+ if (this.user?.bot) return;
532
+ // Avoid rebuilding arrays if already mapped once
533
+ const ids = guilds instanceof Collection ? guilds.map((_, id) => id) : guilds.map(g => g.id);
534
+ this.ws.send({
535
+ op: 12,
536
+ d: ids,
537
+ });
538
+ }
539
+
540
+ /**
541
+ * Obtains a user from Discord, or the user cache if it's already available.
542
+ * @param {UserResolvable} user The user to fetch
543
+ * @param {BaseFetchOptions} [options] Additional options for this fetch
544
+ * @returns {Promise<User>}
545
+ */
546
+ fetchUser(user, options = {}) {
547
+ return this.users.fetch(user, options);
548
+ }
549
+
550
+ /**
551
+ * Obtains a sticker from Discord.
552
+ * @param {Snowflake} id The sticker's id
553
+ * @returns {Promise<Sticker>}
554
+ * @example
555
+ * client.fetchSticker('id')
556
+ * .then(sticker => console.log(`Obtained sticker with name: ${sticker.name}`))
557
+ * .catch(console.error);
558
+ */
559
+ async fetchSticker(id) {
560
+ const data = await this.api.stickers(id).get();
561
+ return new Sticker(this, data);
562
+ }
563
+
564
+ /**
565
+ * Fetches a user using a bot token.
566
+ * @param {UserResolvable} user The user to fetch
567
+ * @param {string} botToken The bot token to use for the request
568
+ * @returns {Promise<User>}
569
+ * @example
570
+ * client.fetchUserWithBot('123456789012345678', 'Bot YOUR_BOT_TOKEN')
571
+ * .then(user => console.log(`Fetched user: ${user.displayName}`))
572
+ * .catch(console.error);
573
+ */
574
+ async fetchUserWithBot(user, botToken) {
575
+ const id = this.users.resolveId(user);
576
+ if (!id) throw new TypeError('INVALID_TYPE', 'user', 'UserResolvable');
577
+
578
+ // Clean the token (remove Bot prefix if present)
579
+ const cleanToken = botToken.replace(/^(Bot|Bearer)\s*/i, '');
580
+
581
+ // Make the API request with the provided bot token
582
+ const data = await this.api.users(id).get({
583
+ auth: false,
584
+ headers: {
585
+ Authorization: `Bot ${cleanToken}`,
586
+ },
587
+ });
588
+
589
+ // Create and return the User object
590
+ const User = require('../structures/User');
591
+ return new User(this, data);
592
+ }
593
+
594
+ /**
595
+ * Obtains the list of sticker packs available to Nitro subscribers from Discord.
596
+ * @returns {Promise<Collection<Snowflake, StickerPack>>}
597
+ * @example
598
+ * client.fetchPremiumStickerPacks()
599
+ * .then(packs => console.log(`Available sticker packs are: ${packs.map(pack => pack.name).join(', ')}`))
600
+ * .catch(console.error);
601
+ */
602
+ async fetchPremiumStickerPacks() {
603
+ const data = await this.api('sticker-packs').get();
604
+ return new Collection(data.sticker_packs.map(p => [p.id, new StickerPack(this, p)]));
605
+ }
606
+ /**
607
+ * A last ditch cleanup function for garbage collection.
608
+ * @param {Function} options.cleanup The function called to GC
609
+ * @param {string} [options.message] The message to send after a successful GC
610
+ * @param {string} [options.name] The name of the item being GCed
611
+ * @private
612
+ */
613
+ _finalize({ cleanup, message, name }) {
614
+ try {
615
+ cleanup();
616
+ this._cleanups.delete(cleanup);
617
+ if (message) {
618
+ this.emit(Events.DEBUG, message);
619
+ }
620
+ } catch {
621
+ this.emit(Events.DEBUG, `Garbage collection failed on ${name ?? 'an unknown item'}.`);
622
+ }
623
+ }
624
+
625
+ /**
626
+ * Sweeps all text-based channels' messages and removes the ones older than the max message lifetime.
627
+ * If the message has been edited, the time of the edit is used rather than the time of the original message.
628
+ * @param {number} [lifetime=this.options.messageCacheLifetime] Messages that are older than this (in seconds)
629
+ * will be removed from the caches. The default is based on {@link ClientOptions#messageCacheLifetime}
630
+ * @returns {number} Amount of messages that were removed from the caches,
631
+ * or -1 if the message cache lifetime is unlimited
632
+ * @example
633
+ * // Remove all messages older than 1800 seconds from the messages cache
634
+ * const amount = client.sweepMessages(1800);
635
+ * console.log(`Successfully removed ${amount} messages from the cache.`);
636
+ */
637
+ sweepMessages(lifetime = this.options.messageCacheLifetime) {
638
+ if (typeof lifetime !== 'number' || isNaN(lifetime)) {
639
+ throw new TypeError('INVALID_TYPE', 'lifetime', 'number');
640
+ }
641
+ if (lifetime <= 0) {
642
+ this.emit(Events.DEBUG, "Didn't sweep messages - lifetime is unlimited");
643
+ return -1;
644
+ }
645
+
646
+ const messages = this.sweepers.sweepMessages(Sweepers.outdatedMessageSweepFilter(lifetime)());
647
+ this.emit(Events.DEBUG, `Swept ${messages} messages older than ${lifetime} seconds`);
648
+ return messages;
649
+ }
650
+
651
+ /**
652
+ * Obtains a guild preview from Discord, available for all guilds the bot is in and all Discoverable guilds.
653
+ * @param {GuildResolvable} guild The guild to fetch the preview for
654
+ * @returns {Promise<GuildPreview>}
655
+ */
656
+ async fetchGuildPreview(guild) {
657
+ const id = this.guilds.resolveId(guild);
658
+ if (!id) throw new TypeError('INVALID_TYPE', 'guild', 'GuildResolvable');
659
+ const data = await this.api.guilds(id).preview.get();
660
+ return new GuildPreview(this, data);
661
+ }
662
+
663
+ /**
664
+ * Obtains the widget data of a guild from Discord, available for guilds with the widget enabled.
665
+ * @param {GuildResolvable} guild The guild to fetch the widget data for
666
+ * @returns {Promise<Widget>}
667
+ */
668
+ async fetchGuildWidget(guild) {
669
+ const id = this.guilds.resolveId(guild);
670
+ if (!id) throw new TypeError('INVALID_TYPE', 'guild', 'GuildResolvable');
671
+ const data = await this.api.guilds(id, 'widget.json').get();
672
+ return new Widget(this, data);
673
+ }
674
+
675
+ /**
676
+ * Refresh the Discord CDN links with hashes so they can be usable.
677
+ * @param {...string} urls Discord CDN URLs
678
+ * @returns {Promise<Array<{ original: string, refreshed: string }>>}
679
+ */
680
+ async refreshAttachmentURL(...urls) {
681
+ // Clean up the URLs
682
+ urls = urls.map(url => {
683
+ const urlObject = new URL(url);
684
+ // Clean query
685
+ urlObject.search = '';
686
+ return urlObject.toString();
687
+ });
688
+ const data = await this.api.attachments('refresh-urls').post({
689
+ data: { attachment_urls: urls },
690
+ });
691
+ /**
692
+ {
693
+ "refreshed_urls": [
694
+ {
695
+ "original": "url",
696
+ "refreshed": "url with hash"
697
+ }
698
+ ]
699
+ }
700
+ */
701
+ return data.refreshed_urls;
702
+ }
703
+
704
+ /**
705
+ * Options for {@link Client#generateInvite}.
706
+ * @typedef {Object} InviteGenerationOptions
707
+ * @property {InviteScope[]} scopes Scopes that should be requested
708
+ * @property {PermissionResolvable} [permissions] Permissions to request
709
+ * @property {GuildResolvable} [guild] Guild to preselect
710
+ * @property {boolean} [disableGuildSelect] Whether to disable the guild selection
711
+ */
712
+
713
+ /**
714
+ * The sleep function in JavaScript returns a promise that resolves after a specified timeout.
715
+ * @param {number} timeout - The timeout parameter is the amount of time, in milliseconds, that the sleep
716
+ * function will wait before resolving the promise and continuing execution.
717
+ * @returns {void} The `sleep` function is returning a Promise.
718
+ */
719
+ sleep(timeout) {
720
+ return new Promise(r => setTimeout(r, timeout));
721
+ }
722
+
723
+ toJSON() {
724
+ return super.toJSON({
725
+ readyAt: false,
726
+ });
727
+ }
728
+
729
+ /**
730
+ * The current session id of the shard
731
+ * @type {?string}
732
+ */
733
+ get sessionId() {
734
+ return this.ws.shards.first()?.sessionId;
735
+ }
736
+
737
+ /**
738
+ * Options for {@link Client#acceptInvite}.
739
+ * @typedef {Object} AcceptInviteOptions
740
+ * @property {boolean} [bypassOnboarding=true] Whether to bypass onboarding
741
+ * @property {boolean} [bypassVerify=true] Whether to bypass rule screening
742
+ */
743
+
744
+ /**
745
+ * Join this Guild / GroupDMChannel using this invite
746
+ * @param {InviteResolvable} invite Invite code or URL
747
+ * @param {AcceptInviteOptions} [options] Options
748
+ * @returns {Promise<Guild|DMChannel|GroupDMChannel>}
749
+ * @example
750
+ * await client.acceptInvite('https://discord.gg/genshinimpact', { bypassOnboarding: true, bypassVerify: true })
751
+ */
752
+ async acceptInvite(invite, options = { bypassOnboarding: true, bypassVerify: true }) {
753
+ // ! throw new Error('METHOD_WARNING');
754
+ const code = DataResolver.resolveInviteCode(invite);
755
+ if (!code) throw new Error('INVITE_RESOLVE_CODE');
756
+ const i = await this.fetchInvite(code);
757
+ if (i.guild?.id && this.guilds.cache.has(i.guild?.id)) return this.guilds.cache.get(i.guild?.id);
758
+ if (this.channels.cache.has(i.channelId)) return this.channels.cache.get(i.channelId);
759
+ const data = await this.api.invites(code).post({
760
+ DiscordContext: { location: 'Markdown Link' },
761
+ data: {
762
+ session_id: this.sessionId,
763
+ },
764
+ });
765
+ this.emit(Events.DEBUG, `[Invite > Guild ${i.guild?.id}] Joined`);
766
+ // Guild
767
+ if (i.guild?.id) {
768
+ const guild = this.guilds.cache.get(i.guild?.id);
769
+ if (i.flags.has('GUEST')) {
770
+ this.emit(Events.DEBUG, `[Invite > Guild ${i.guild?.id}] Guest invite`);
771
+ return guild;
772
+ }
773
+ if (options.bypassOnboarding) {
774
+ const onboardingData = await this.api.guilds[i.guild?.id].onboarding.get();
775
+ // Onboarding
776
+ if (onboardingData.enabled) {
777
+ const prompts = onboardingData.prompts.filter(o => o.in_onboarding);
778
+ if (prompts.length) {
779
+ const onboarding_prompts_seen = {};
780
+ const onboarding_responses = [];
781
+ const onboarding_responses_seen = {};
782
+
783
+ const currentDate = Date.now();
784
+
785
+ prompts.forEach(prompt => {
786
+ onboarding_prompts_seen[prompt.id] = currentDate;
787
+ if (prompt.required) onboarding_responses.push(prompt.options[0].id);
788
+ prompt.options.forEach(option => {
789
+ onboarding_responses_seen[option.id] = currentDate;
790
+ });
791
+ });
792
+
793
+ await this.api.guilds[i.guild?.id]['onboarding-responses'].post({
794
+ data: {
795
+ onboarding_prompts_seen,
796
+ onboarding_responses,
797
+ onboarding_responses_seen,
798
+ },
799
+ });
800
+ this.emit(Events.DEBUG, `[Invite > Guild ${i.guild?.id}] Bypassed onboarding`);
801
+ }
802
+ }
803
+ }
804
+ // Read rule
805
+ if (data.show_verification_form && options.bypassVerify) {
806
+ // Check Guild
807
+ if (i.guild.verificationLevel == 'VERY_HIGH' && !this.user.phone) {
808
+ this.emit(Events.DEBUG, `[Invite > Guild ${i.guild?.id}] Cannot bypass verify (Phone required)`);
809
+ return this.guilds.cache.get(i.guild?.id);
810
+ }
811
+ if (i.guild.verificationLevel !== 'NONE' && !this.user.email) {
812
+ this.emit(Events.DEBUG, `[Invite > Guild ${i.guild?.id}] Cannot bypass verify (Email required)`);
813
+ return this.guilds.cache.get(i.guild?.id);
814
+ }
815
+ const guildRoute = this.api.guilds[i.guild?.id];
816
+ const getForm = await guildRoute['member-verification']
817
+ .get({ query: { with_guild: false, invite_code: code } })
818
+ .catch(() => {});
819
+ if (getForm && getForm.form_fields[0]) {
820
+ const form = { ...getForm.form_fields[0], response: true };
821
+ await guildRoute.requests['@me'].put({ data: { form_fields: [form], version: getForm.version } });
822
+ this.emit(Events.DEBUG, `[Invite > Guild ${i.guild?.id}] Bypassed verify`);
823
+ }
824
+ }
825
+ return guild;
826
+ } else {
827
+ const channelId = i.channelId || data.channel?.id;
828
+ if (!channelId) return null;
829
+ if (this.channels.cache.has(channelId)) return this.channels.cache.get(channelId);
830
+ if (data.channel) return this.channels._add(data.channel);
831
+ return null;
832
+ }
833
+ }
834
+
835
+ /**
836
+ * Redeem nitro from code or url.
837
+ * @param {string} nitro Nitro url or code
838
+ * @param {TextChannelResolvable} [channel] Channel that the code was sent in
839
+ * @param {Snowflake} [paymentSourceId] Payment source id
840
+ * @returns {Promise<any>}
841
+ */
842
+ redeemNitro(nitro, channel, paymentSourceId) {
843
+ if (typeof nitro !== 'string') throw new Error('INVALID_NITRO');
844
+ const nitroCode =
845
+ nitro.match(/(discord.gift|discord.com|discordapp.com\/gifts)\/(\w{16,25})/) ||
846
+ nitro.match(/(discord\.gift\/|discord\.com\/gifts\/|discordapp\.com\/gifts\/)(\w+)/);
847
+ if (!nitroCode) return false;
848
+ const code = nitroCode[2];
849
+ channel = this.channels.resolveId(channel);
850
+ return this.api.entitlements['gift-codes'](code).redeem.post({
851
+ auth: true,
852
+ data: { channel_id: channel || null, payment_source_id: paymentSourceId || null },
853
+ });
854
+ }
855
+
856
+ /**
857
+ * @typedef {Object} OAuth2AuthorizeOptions
858
+ * @property {string} [guild_id] Guild ID
859
+ * @property {string} [permissions] Permissions
860
+ * @property {boolean} [authorize] Whether to authorize or not
861
+ * @property {string} [code] 2FA Code
862
+ * @property {string} [webhook_channel_id] Webhook Channel ID
863
+ */
864
+
865
+ /**
866
+ * Authorize an application.
867
+ * @param {string} urlOAuth2 Discord Auth URL
868
+ * @param {OAuth2AuthorizeOptions} [options] Oauth2 options
869
+ * @returns {Promise<{ location: string }>}
870
+ * @example
871
+ * client.authorizeURL(`https://discord.com/api/oauth2/authorize?client_id=botID&permissions=8&scope=applications.commands%20bot`, {
872
+ guild_id: "guildID",
873
+ })
874
+ */
875
+ authorizeURL(urlOAuth2, options = {}) {
876
+ // ! throw new Error('METHOD_WARNING');
877
+ const url = new URL(urlOAuth2);
878
+ if (!/^https:\/\/(?:canary\.|ptb\.)?discord\.com(?:\/api(?:\/v\d{1,2})?)?\/oauth2\/authorize\?/.test(urlOAuth2)) {
879
+ throw new Error('INVALID_URL', urlOAuth2);
880
+ }
881
+ const searchParams = Object.fromEntries(url.searchParams);
882
+ // Assign options
883
+ options = {
884
+ authorize: true,
885
+ permissions: '0',
886
+ integration_type: 0,
887
+ location_context: {
888
+ guild_id: '10000',
889
+ channel_id: '10000',
890
+ channel_type: 10000,
891
+ },
892
+ ...searchParams,
893
+ ...options,
894
+ };
895
+ delete searchParams.permissions;
896
+ delete searchParams.integration_type;
897
+ delete searchParams.guild_id;
898
+ return this.api.oauth2.authorize.post({
899
+ query: searchParams,
900
+ data: options,
901
+ });
902
+ }
903
+
904
+ /**
905
+ * Install User Apps
906
+ * @param {Snowflake} applicationId Discord Application id
907
+ * @param {string[]|string} [scopes=['applications.commands']] OAuth scopes to request when installing
908
+ * @returns {Promise<boolean>}
909
+ */
910
+ async installUserApps(applicationId, scopes = ['applications.commands']) {
911
+ const scope = typeof scopes === 'string' ? scopes : scopes.join(' ');
912
+ await this.api.oauth2.authorize.post({
913
+ query: {
914
+ client_id: applicationId,
915
+ scope,
916
+ },
917
+ data: {
918
+ permissions: '0',
919
+ authorize: true,
920
+ integration_type: 1,
921
+ dm_settings: {
922
+ allow_mobile_push: false,
923
+ },
924
+ },
925
+ });
926
+
927
+ return true;
928
+ }
929
+
930
+ /**
931
+ * Uninstall a previously authorized user application.
932
+ * @param {Snowflake} applicationId Discord Application id
933
+ * @returns {Promise<boolean>}
934
+ */
935
+ async unInstallUserApp(applicationId) {
936
+ const authorizations = await this.api.oauth2.tokens.get();
937
+ const authorization = authorizations.find(token => token.application?.id === applicationId);
938
+ if (!authorization) return false;
939
+ await this.api.oauth2.tokens(authorization.id).delete();
940
+ return true;
941
+ }
942
+
943
+ /**
944
+ * Deauthorizes an application or token.
945
+ * @param {Snowflake} id - The ID of the Discord Application or Token.
946
+ * @param {'application' | 'token'} [type='application'] - The type of the ID provided. Defaults to 'application'.
947
+ * @returns {Promise<void>} A promise that resolves when the deauthorization is complete.
948
+ */
949
+ deauthorize(id, type = 'application') {
950
+ if (type === 'application') {
951
+ return this.api.oauth2.tokens
952
+ .get()
953
+ .then(data => data.find(o => o.application.id == id))
954
+ .then(o => this.api.oauth2.tokens(o.id).delete());
955
+ } else {
956
+ return this.api.oauth2.tokens(id).delete();
957
+ }
958
+ }
959
+
960
+ /**
961
+ * @typedef {Object} AuthorizedApplicationData
962
+ * @property {Application} application - The application object.
963
+ * @property {Snowflake} authorizedApplicationId - The ID of the OAuth2 token.
964
+ * @property {string[]} scopes - The scopes that were granted to this token.
965
+ * @property {function(): Promise<void>} deauthorize - Function to revoke this token.
966
+ */
967
+
968
+ /**
969
+ * Retrieves the list of authorized applications (OAuth2 tokens).
970
+ * @returns {Promise<Collection<Snowflake, AuthorizedApplicationData>>}
971
+ */
972
+ authorizedApplications() {
973
+ return this.api.oauth2.tokens.get().then(data => {
974
+ const results = new Collection();
975
+ for (const o of data) {
976
+ const application = new Application(this, o.application);
977
+ const data = {
978
+ application,
979
+ authorizedApplicationId: o.id,
980
+ scopes: o.scopes,
981
+ deauthorize: () => this.deauthorize(o.id, 'token'),
982
+ };
983
+ results.set(o.application.id, data);
984
+ }
985
+ return results;
986
+ });
987
+ }
988
+
989
+ /**
990
+ * Calls {@link https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/eval} on a script
991
+ * with the client as `this`.
992
+ * @param {string} script Script to eval
993
+ * @returns {*}
994
+ * @private
995
+ */
996
+ _eval(script) {
997
+ return eval(script);
998
+ }
999
+
1000
+ /**
1001
+ * Validates the client options.
1002
+ * @param {ClientOptions} [options=this.options] Options to validate
1003
+ * @private
1004
+ */
1005
+ _validateOptions(options = this.options) {
1006
+ if (typeof options.makeCache !== 'function') {
1007
+ throw new TypeError('CLIENT_INVALID_OPTION', 'makeCache', 'a function');
1008
+ }
1009
+ if (typeof options.messageCacheLifetime !== 'number' || isNaN(options.messageCacheLifetime)) {
1010
+ throw new TypeError('CLIENT_INVALID_OPTION', 'The messageCacheLifetime', 'a number');
1011
+ }
1012
+ if (typeof options.messageSweepInterval !== 'number' || isNaN(options.messageSweepInterval)) {
1013
+ throw new TypeError('CLIENT_INVALID_OPTION', 'messageSweepInterval', 'a number');
1014
+ }
1015
+ if (typeof options.sweepers !== 'object' || options.sweepers === null) {
1016
+ throw new TypeError('CLIENT_INVALID_OPTION', 'sweepers', 'an object');
1017
+ }
1018
+ if (typeof options.invalidRequestWarningInterval !== 'number' || isNaN(options.invalidRequestWarningInterval)) {
1019
+ throw new TypeError('CLIENT_INVALID_OPTION', 'invalidRequestWarningInterval', 'a number');
1020
+ }
1021
+ if (!Array.isArray(options.partials)) {
1022
+ throw new TypeError('CLIENT_INVALID_OPTION', 'partials', 'an Array');
1023
+ }
1024
+ if (typeof options.DMChannelVoiceStatusSync !== 'number' || isNaN(options.DMChannelVoiceStatusSync)) {
1025
+ throw new TypeError('CLIENT_INVALID_OPTION', 'DMChannelVoiceStatusSync', 'a number');
1026
+ }
1027
+ if (typeof options.waitGuildTimeout !== 'number' || isNaN(options.waitGuildTimeout)) {
1028
+ throw new TypeError('CLIENT_INVALID_OPTION', 'waitGuildTimeout', 'a number');
1029
+ }
1030
+ if (typeof options.restWsBridgeTimeout !== 'number' || isNaN(options.restWsBridgeTimeout)) {
1031
+ throw new TypeError('CLIENT_INVALID_OPTION', 'restWsBridgeTimeout', 'a number');
1032
+ }
1033
+ if (typeof options.restRequestTimeout !== 'number' || isNaN(options.restRequestTimeout)) {
1034
+ throw new TypeError('CLIENT_INVALID_OPTION', 'restRequestTimeout', 'a number');
1035
+ }
1036
+ if (typeof options.restGlobalRateLimit !== 'number' || isNaN(options.restGlobalRateLimit)) {
1037
+ throw new TypeError('CLIENT_INVALID_OPTION', 'restGlobalRateLimit', 'a number');
1038
+ }
1039
+ if (typeof options.restSweepInterval !== 'number' || isNaN(options.restSweepInterval)) {
1040
+ throw new TypeError('CLIENT_INVALID_OPTION', 'restSweepInterval', 'a number');
1041
+ }
1042
+ if (typeof options.retryLimit !== 'number' || isNaN(options.retryLimit)) {
1043
+ throw new TypeError('CLIENT_INVALID_OPTION', 'retryLimit', 'a number');
1044
+ }
1045
+ if (typeof options.failIfNotExists !== 'boolean') {
1046
+ throw new TypeError('CLIENT_INVALID_OPTION', 'failIfNotExists', 'a boolean');
1047
+ }
1048
+ if (
1049
+ typeof options.rejectOnRateLimit !== 'undefined' &&
1050
+ !(typeof options.rejectOnRateLimit === 'function' || Array.isArray(options.rejectOnRateLimit))
1051
+ ) {
1052
+ throw new TypeError('CLIENT_INVALID_OPTION', 'rejectOnRateLimit', 'an array or a function');
1053
+ }
1054
+ if (typeof options.TOTPKey === 'string') {
1055
+ // Convert to base32 if not already
1056
+ options.TOTPKey = options.TOTPKey.replace(/ +/g, '').toUpperCase();
1057
+ }
1058
+ // Hardcode
1059
+ this.options.shardCount = 1;
1060
+ this.options.shards = [0];
1061
+ this.options.intents = Intents.ALL;
1062
+ }
1063
+ }
1064
+
1065
+ module.exports = Client;
1066
+
1067
+ /**
1068
+ * Emitted for general warnings.
1069
+ * @event Client#warn
1070
+ * @param {string} info The warning
1071
+ */
1072
+
1073
+ /**
1074
+ * @external Collection
1075
+ * @see {@link https://discord.js.org/docs/packages/collection/stable/Collection:Class}
1076
+ */