djs-selfbot-v13 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (348) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +132 -0
  3. package/package.json +100 -0
  4. package/src/WebSocket.js +39 -0
  5. package/src/client/BaseClient.js +87 -0
  6. package/src/client/Client.js +1117 -0
  7. package/src/client/WebhookClient.js +61 -0
  8. package/src/client/actions/Action.js +115 -0
  9. package/src/client/actions/ActionsManager.js +72 -0
  10. package/src/client/actions/ApplicationCommandPermissionsUpdate.js +34 -0
  11. package/src/client/actions/AutoModerationActionExecution.js +26 -0
  12. package/src/client/actions/AutoModerationRuleCreate.js +27 -0
  13. package/src/client/actions/AutoModerationRuleDelete.js +31 -0
  14. package/src/client/actions/AutoModerationRuleUpdate.js +29 -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/InteractionCreate.js +115 -0
  45. package/src/client/actions/InviteCreate.js +28 -0
  46. package/src/client/actions/InviteDelete.js +30 -0
  47. package/src/client/actions/MessageCreate.js +50 -0
  48. package/src/client/actions/MessageDelete.js +32 -0
  49. package/src/client/actions/MessageDeleteBulk.js +46 -0
  50. package/src/client/actions/MessageReactionAdd.js +56 -0
  51. package/src/client/actions/MessageReactionRemove.js +45 -0
  52. package/src/client/actions/MessageReactionRemoveAll.js +33 -0
  53. package/src/client/actions/MessageReactionRemoveEmoji.js +28 -0
  54. package/src/client/actions/MessageUpdate.js +26 -0
  55. package/src/client/actions/PresenceUpdate.js +45 -0
  56. package/src/client/actions/StageInstanceCreate.js +28 -0
  57. package/src/client/actions/StageInstanceDelete.js +33 -0
  58. package/src/client/actions/StageInstanceUpdate.js +30 -0
  59. package/src/client/actions/ThreadCreate.js +24 -0
  60. package/src/client/actions/ThreadDelete.js +32 -0
  61. package/src/client/actions/ThreadListSync.js +59 -0
  62. package/src/client/actions/ThreadMemberUpdate.js +30 -0
  63. package/src/client/actions/ThreadMembersUpdate.js +34 -0
  64. package/src/client/actions/TypingStart.js +29 -0
  65. package/src/client/actions/UserUpdate.js +35 -0
  66. package/src/client/actions/VoiceStateUpdate.js +57 -0
  67. package/src/client/actions/WebhooksUpdate.js +20 -0
  68. package/src/client/voice/ClientVoiceManager.js +51 -0
  69. package/src/client/websocket/WebSocketManager.js +412 -0
  70. package/src/client/websocket/WebSocketShard.js +905 -0
  71. package/src/client/websocket/handlers/APPLICATION_COMMAND_AUTOCOMPLETE_RESPONSE.js +23 -0
  72. package/src/client/websocket/handlers/APPLICATION_COMMAND_CREATE.js +18 -0
  73. package/src/client/websocket/handlers/APPLICATION_COMMAND_DELETE.js +20 -0
  74. package/src/client/websocket/handlers/APPLICATION_COMMAND_PERMISSIONS_UPDATE.js +5 -0
  75. package/src/client/websocket/handlers/APPLICATION_COMMAND_UPDATE.js +20 -0
  76. package/src/client/websocket/handlers/AUTO_MODERATION_ACTION_EXECUTION.js +5 -0
  77. package/src/client/websocket/handlers/AUTO_MODERATION_RULE_CREATE.js +5 -0
  78. package/src/client/websocket/handlers/AUTO_MODERATION_RULE_DELETE.js +5 -0
  79. package/src/client/websocket/handlers/AUTO_MODERATION_RULE_UPDATE.js +5 -0
  80. package/src/client/websocket/handlers/CALL_CREATE.js +14 -0
  81. package/src/client/websocket/handlers/CALL_DELETE.js +11 -0
  82. package/src/client/websocket/handlers/CALL_UPDATE.js +11 -0
  83. package/src/client/websocket/handlers/CHANNEL_CREATE.js +5 -0
  84. package/src/client/websocket/handlers/CHANNEL_DELETE.js +5 -0
  85. package/src/client/websocket/handlers/CHANNEL_PINS_UPDATE.js +22 -0
  86. package/src/client/websocket/handlers/CHANNEL_RECIPIENT_ADD.js +16 -0
  87. package/src/client/websocket/handlers/CHANNEL_RECIPIENT_REMOVE.js +16 -0
  88. package/src/client/websocket/handlers/CHANNEL_UPDATE.js +16 -0
  89. package/src/client/websocket/handlers/GUILD_APPLICATION_COMMANDS_UPDATE.js +11 -0
  90. package/src/client/websocket/handlers/GUILD_AUDIT_LOG_ENTRY_CREATE.js +5 -0
  91. package/src/client/websocket/handlers/GUILD_BAN_ADD.js +5 -0
  92. package/src/client/websocket/handlers/GUILD_BAN_REMOVE.js +5 -0
  93. package/src/client/websocket/handlers/GUILD_CREATE.js +46 -0
  94. package/src/client/websocket/handlers/GUILD_DELETE.js +5 -0
  95. package/src/client/websocket/handlers/GUILD_EMOJIS_UPDATE.js +5 -0
  96. package/src/client/websocket/handlers/GUILD_INTEGRATIONS_UPDATE.js +5 -0
  97. package/src/client/websocket/handlers/GUILD_MEMBERS_CHUNK.js +39 -0
  98. package/src/client/websocket/handlers/GUILD_MEMBER_ADD.js +20 -0
  99. package/src/client/websocket/handlers/GUILD_MEMBER_LIST_UPDATE.js +55 -0
  100. package/src/client/websocket/handlers/GUILD_MEMBER_REMOVE.js +5 -0
  101. package/src/client/websocket/handlers/GUILD_MEMBER_UPDATE.js +5 -0
  102. package/src/client/websocket/handlers/GUILD_ROLE_CREATE.js +5 -0
  103. package/src/client/websocket/handlers/GUILD_ROLE_DELETE.js +5 -0
  104. package/src/client/websocket/handlers/GUILD_ROLE_UPDATE.js +5 -0
  105. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_CREATE.js +5 -0
  106. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_DELETE.js +5 -0
  107. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_UPDATE.js +5 -0
  108. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_USER_ADD.js +5 -0
  109. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_USER_REMOVE.js +5 -0
  110. package/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUNDS_UPDATE.js +0 -0
  111. package/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_CREATE.js +0 -0
  112. package/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_DELETE.js +0 -0
  113. package/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_UPDATE.js +0 -0
  114. package/src/client/websocket/handlers/GUILD_STICKERS_UPDATE.js +5 -0
  115. package/src/client/websocket/handlers/GUILD_UPDATE.js +5 -0
  116. package/src/client/websocket/handlers/INTERACTION_CREATE.js +16 -0
  117. package/src/client/websocket/handlers/INTERACTION_FAILURE.js +18 -0
  118. package/src/client/websocket/handlers/INTERACTION_MODAL_CREATE.js +11 -0
  119. package/src/client/websocket/handlers/INTERACTION_SUCCESS.js +30 -0
  120. package/src/client/websocket/handlers/INVITE_CREATE.js +5 -0
  121. package/src/client/websocket/handlers/INVITE_DELETE.js +5 -0
  122. package/src/client/websocket/handlers/MESSAGE_ACK.js +16 -0
  123. package/src/client/websocket/handlers/MESSAGE_CREATE.js +5 -0
  124. package/src/client/websocket/handlers/MESSAGE_DELETE.js +5 -0
  125. package/src/client/websocket/handlers/MESSAGE_DELETE_BULK.js +5 -0
  126. package/src/client/websocket/handlers/MESSAGE_REACTION_ADD.js +5 -0
  127. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE.js +5 -0
  128. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE_ALL.js +5 -0
  129. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE_EMOJI.js +5 -0
  130. package/src/client/websocket/handlers/MESSAGE_UPDATE.js +16 -0
  131. package/src/client/websocket/handlers/PRESENCE_UPDATE.js +5 -0
  132. package/src/client/websocket/handlers/READY.js +170 -0
  133. package/src/client/websocket/handlers/RELATIONSHIP_ADD.js +17 -0
  134. package/src/client/websocket/handlers/RELATIONSHIP_REMOVE.js +15 -0
  135. package/src/client/websocket/handlers/RELATIONSHIP_UPDATE.js +18 -0
  136. package/src/client/websocket/handlers/RESUMED.js +14 -0
  137. package/src/client/websocket/handlers/SOUNDBOARD_SOUNDS.js +0 -0
  138. package/src/client/websocket/handlers/STAGE_INSTANCE_CREATE.js +5 -0
  139. package/src/client/websocket/handlers/STAGE_INSTANCE_DELETE.js +5 -0
  140. package/src/client/websocket/handlers/STAGE_INSTANCE_UPDATE.js +5 -0
  141. package/src/client/websocket/handlers/THREAD_CREATE.js +5 -0
  142. package/src/client/websocket/handlers/THREAD_DELETE.js +5 -0
  143. package/src/client/websocket/handlers/THREAD_LIST_SYNC.js +5 -0
  144. package/src/client/websocket/handlers/THREAD_MEMBERS_UPDATE.js +5 -0
  145. package/src/client/websocket/handlers/THREAD_MEMBER_UPDATE.js +5 -0
  146. package/src/client/websocket/handlers/THREAD_UPDATE.js +16 -0
  147. package/src/client/websocket/handlers/TYPING_START.js +5 -0
  148. package/src/client/websocket/handlers/USER_GUILD_SETTINGS_UPDATE.js +12 -0
  149. package/src/client/websocket/handlers/USER_NOTE_UPDATE.js +5 -0
  150. package/src/client/websocket/handlers/USER_SETTINGS_UPDATE.js +9 -0
  151. package/src/client/websocket/handlers/USER_UPDATE.js +5 -0
  152. package/src/client/websocket/handlers/VOICE_CHANNEL_EFFECT_SEND.js +0 -0
  153. package/src/client/websocket/handlers/VOICE_SERVER_UPDATE.js +6 -0
  154. package/src/client/websocket/handlers/VOICE_STATE_UPDATE.js +5 -0
  155. package/src/client/websocket/handlers/WEBHOOKS_UPDATE.js +5 -0
  156. package/src/client/websocket/handlers/index.js +86 -0
  157. package/src/errors/DJSError.js +61 -0
  158. package/src/errors/Messages.js +227 -0
  159. package/src/errors/index.js +4 -0
  160. package/src/index.js +189 -0
  161. package/src/managers/ApplicationCommandManager.js +267 -0
  162. package/src/managers/ApplicationCommandPermissionsManager.js +425 -0
  163. package/src/managers/AutoModerationRuleManager.js +296 -0
  164. package/src/managers/BaseGuildEmojiManager.js +80 -0
  165. package/src/managers/BaseManager.js +19 -0
  166. package/src/managers/BillingManager.js +66 -0
  167. package/src/managers/CachedManager.js +71 -0
  168. package/src/managers/ChannelManager.js +139 -0
  169. package/src/managers/ClientUserSettingManager.js +490 -0
  170. package/src/managers/DataManager.js +61 -0
  171. package/src/managers/DeveloperPortalManager.js +104 -0
  172. package/src/managers/GuildApplicationCommandManager.js +28 -0
  173. package/src/managers/GuildBanManager.js +204 -0
  174. package/src/managers/GuildChannelManager.js +502 -0
  175. package/src/managers/GuildEmojiManager.js +171 -0
  176. package/src/managers/GuildEmojiRoleManager.js +118 -0
  177. package/src/managers/GuildFolderManager.js +24 -0
  178. package/src/managers/GuildForumThreadManager.js +114 -0
  179. package/src/managers/GuildInviteManager.js +213 -0
  180. package/src/managers/GuildManager.js +304 -0
  181. package/src/managers/GuildMemberManager.js +769 -0
  182. package/src/managers/GuildMemberRoleManager.js +191 -0
  183. package/src/managers/GuildScheduledEventManager.js +296 -0
  184. package/src/managers/GuildSettingManager.js +148 -0
  185. package/src/managers/GuildStickerManager.js +179 -0
  186. package/src/managers/GuildTextThreadManager.js +98 -0
  187. package/src/managers/InteractionManager.js +39 -0
  188. package/src/managers/MessageManager.js +393 -0
  189. package/src/managers/PermissionOverwriteManager.js +166 -0
  190. package/src/managers/PresenceManager.js +58 -0
  191. package/src/managers/ReactionManager.js +67 -0
  192. package/src/managers/ReactionUserManager.js +71 -0
  193. package/src/managers/RelationshipManager.js +258 -0
  194. package/src/managers/RoleManager.js +352 -0
  195. package/src/managers/SessionManager.js +57 -0
  196. package/src/managers/StageInstanceManager.js +162 -0
  197. package/src/managers/ThreadManager.js +207 -0
  198. package/src/managers/ThreadMemberManager.js +186 -0
  199. package/src/managers/UserManager.js +150 -0
  200. package/src/managers/VoiceStateManager.js +37 -0
  201. package/src/rest/APIRequest.js +132 -0
  202. package/src/rest/APIRouter.js +53 -0
  203. package/src/rest/CaptchaSolver.js +132 -0
  204. package/src/rest/DiscordAPIError.js +103 -0
  205. package/src/rest/HTTPError.js +62 -0
  206. package/src/rest/RESTManager.js +82 -0
  207. package/src/rest/RateLimitError.js +55 -0
  208. package/src/rest/RequestHandler.js +430 -0
  209. package/src/sharding/Shard.js +443 -0
  210. package/src/sharding/ShardClientUtil.js +275 -0
  211. package/src/sharding/ShardingManager.js +318 -0
  212. package/src/structures/AnonymousGuild.js +98 -0
  213. package/src/structures/ApplicationCommand.js +1030 -0
  214. package/src/structures/ApplicationRoleConnectionMetadata.js +45 -0
  215. package/src/structures/AutoModerationActionExecution.js +89 -0
  216. package/src/structures/AutoModerationRule.js +294 -0
  217. package/src/structures/AutocompleteInteraction.js +106 -0
  218. package/src/structures/Base.js +43 -0
  219. package/src/structures/BaseCommandInteraction.js +211 -0
  220. package/src/structures/BaseGuild.js +116 -0
  221. package/src/structures/BaseGuildEmoji.js +56 -0
  222. package/src/structures/BaseGuildTextChannel.js +193 -0
  223. package/src/structures/BaseGuildVoiceChannel.js +243 -0
  224. package/src/structures/BaseMessageComponent.js +114 -0
  225. package/src/structures/ButtonInteraction.js +11 -0
  226. package/src/structures/Call.js +58 -0
  227. package/src/structures/CategoryChannel.js +83 -0
  228. package/src/structures/Channel.js +271 -0
  229. package/src/structures/ClientApplication.js +204 -0
  230. package/src/structures/ClientPresence.js +84 -0
  231. package/src/structures/ClientUser.js +634 -0
  232. package/src/structures/CommandInteraction.js +41 -0
  233. package/src/structures/CommandInteractionOptionResolver.js +276 -0
  234. package/src/structures/ContextMenuInteraction.js +65 -0
  235. package/src/structures/DMChannel.js +280 -0
  236. package/src/structures/DeveloperPortalApplication.js +520 -0
  237. package/src/structures/DirectoryChannel.js +20 -0
  238. package/src/structures/Emoji.js +148 -0
  239. package/src/structures/ForumChannel.js +271 -0
  240. package/src/structures/Guild.js +1744 -0
  241. package/src/structures/GuildAuditLogs.js +734 -0
  242. package/src/structures/GuildBan.js +59 -0
  243. package/src/structures/GuildBoost.js +108 -0
  244. package/src/structures/GuildChannel.js +454 -0
  245. package/src/structures/GuildEmoji.js +161 -0
  246. package/src/structures/GuildFolder.js +75 -0
  247. package/src/structures/GuildMember.js +686 -0
  248. package/src/structures/GuildPreview.js +191 -0
  249. package/src/structures/GuildPreviewEmoji.js +27 -0
  250. package/src/structures/GuildScheduledEvent.js +441 -0
  251. package/src/structures/GuildTemplate.js +236 -0
  252. package/src/structures/Integration.js +188 -0
  253. package/src/structures/IntegrationApplication.js +96 -0
  254. package/src/structures/Interaction.js +351 -0
  255. package/src/structures/InteractionCollector.js +248 -0
  256. package/src/structures/InteractionResponse.js +114 -0
  257. package/src/structures/InteractionWebhook.js +43 -0
  258. package/src/structures/Invite.js +375 -0
  259. package/src/structures/InviteGuild.js +23 -0
  260. package/src/structures/InviteStageInstance.js +86 -0
  261. package/src/structures/Message.js +1182 -0
  262. package/src/structures/MessageActionRow.js +103 -0
  263. package/src/structures/MessageAttachment.js +193 -0
  264. package/src/structures/MessageButton.js +231 -0
  265. package/src/structures/MessageCollector.js +146 -0
  266. package/src/structures/MessageComponentInteraction.js +120 -0
  267. package/src/structures/MessageContextMenuInteraction.js +20 -0
  268. package/src/structures/MessageEmbed.js +586 -0
  269. package/src/structures/MessageMentions.js +272 -0
  270. package/src/structures/MessagePayload.js +358 -0
  271. package/src/structures/MessageReaction.js +171 -0
  272. package/src/structures/MessageSelectMenu.js +391 -0
  273. package/src/structures/Modal.js +279 -0
  274. package/src/structures/ModalSubmitFieldsResolver.js +53 -0
  275. package/src/structures/ModalSubmitInteraction.js +119 -0
  276. package/src/structures/NewsChannel.js +32 -0
  277. package/src/structures/OAuth2Guild.js +28 -0
  278. package/src/structures/PartialGroupDMChannel.js +433 -0
  279. package/src/structures/PermissionOverwrites.js +196 -0
  280. package/src/structures/Presence.js +443 -0
  281. package/src/structures/ReactionCollector.js +229 -0
  282. package/src/structures/ReactionEmoji.js +31 -0
  283. package/src/structures/RichPresence.js +722 -0
  284. package/src/structures/Role.js +515 -0
  285. package/src/structures/SelectMenuInteraction.js +170 -0
  286. package/src/structures/Session.js +81 -0
  287. package/src/structures/StageChannel.js +104 -0
  288. package/src/structures/StageInstance.js +208 -0
  289. package/src/structures/Sticker.js +310 -0
  290. package/src/structures/StickerPack.js +95 -0
  291. package/src/structures/StoreChannel.js +56 -0
  292. package/src/structures/Team.js +167 -0
  293. package/src/structures/TeamMember.js +71 -0
  294. package/src/structures/TextChannel.js +33 -0
  295. package/src/structures/TextInputComponent.js +201 -0
  296. package/src/structures/ThreadChannel.js +626 -0
  297. package/src/structures/ThreadMember.js +105 -0
  298. package/src/structures/Typing.js +74 -0
  299. package/src/structures/User.js +737 -0
  300. package/src/structures/UserContextMenuInteraction.js +29 -0
  301. package/src/structures/VoiceChannel.js +110 -0
  302. package/src/structures/VoiceRegion.js +53 -0
  303. package/src/structures/VoiceState.js +306 -0
  304. package/src/structures/WebEmbed.js +387 -0
  305. package/src/structures/Webhook.js +461 -0
  306. package/src/structures/WelcomeChannel.js +60 -0
  307. package/src/structures/WelcomeScreen.js +48 -0
  308. package/src/structures/Widget.js +87 -0
  309. package/src/structures/WidgetMember.js +99 -0
  310. package/src/structures/interfaces/Application.js +190 -0
  311. package/src/structures/interfaces/Collector.js +300 -0
  312. package/src/structures/interfaces/InteractionResponses.js +313 -0
  313. package/src/structures/interfaces/TextBasedChannel.js +566 -0
  314. package/src/util/ActivityFlags.js +44 -0
  315. package/src/util/ApplicationFlags.js +76 -0
  316. package/src/util/BitField.js +170 -0
  317. package/src/util/ChannelFlags.js +45 -0
  318. package/src/util/Constants.js +1938 -0
  319. package/src/util/DataResolver.js +145 -0
  320. package/src/util/Formatters.js +214 -0
  321. package/src/util/GuildMemberFlags.js +43 -0
  322. package/src/util/Intents.js +74 -0
  323. package/src/util/LimitedCollection.js +131 -0
  324. package/src/util/MessageFlags.js +54 -0
  325. package/src/util/Options.js +362 -0
  326. package/src/util/Permissions.js +187 -0
  327. package/src/util/PremiumUsageFlags.js +31 -0
  328. package/src/util/PurchasedFlags.js +31 -0
  329. package/src/util/RemoteAuth.js +514 -0
  330. package/src/util/SnowflakeUtil.js +92 -0
  331. package/src/util/Sweepers.js +466 -0
  332. package/src/util/SystemChannelFlags.js +55 -0
  333. package/src/util/ThreadMemberFlags.js +30 -0
  334. package/src/util/UserFlags.js +104 -0
  335. package/src/util/Util.js +763 -0
  336. package/src/util/Voice.js +1456 -0
  337. package/src/util/arRPC/index.js +229 -0
  338. package/src/util/arRPC/process/detectable.json +1 -0
  339. package/src/util/arRPC/process/index.js +102 -0
  340. package/src/util/arRPC/process/native/index.js +5 -0
  341. package/src/util/arRPC/process/native/linux.js +37 -0
  342. package/src/util/arRPC/process/native/win32.js +25 -0
  343. package/src/util/arRPC/transports/ipc.js +281 -0
  344. package/src/util/arRPC/transports/websocket.js +128 -0
  345. package/typings/enums.d.ts +346 -0
  346. package/typings/index.d.ts +7741 -0
  347. package/typings/index.test-d.ts +0 -0
  348. package/typings/rawDataTypes.d.ts +283 -0
@@ -0,0 +1,1117 @@
1
+ 'use strict';
2
+
3
+ const process = require('node:process');
4
+ const { setInterval, setTimeout } = require('node:timers');
5
+ const { Collection } = require('@discordjs/collection');
6
+ const { getVoiceConnection } = require('@discordjs/voice');
7
+ const chalk = require('chalk');
8
+ const fetch = require('node-fetch');
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, RangeError } = require('../errors');
14
+ const Discord = require('../index');
15
+ const BaseGuildEmojiManager = require('../managers/BaseGuildEmojiManager');
16
+ const BillingManager = require('../managers/BillingManager');
17
+ const ChannelManager = require('../managers/ChannelManager');
18
+ const ClientUserSettingManager = require('../managers/ClientUserSettingManager');
19
+ const DeveloperPortalManager = require('../managers/DeveloperPortalManager');
20
+ const GuildManager = require('../managers/GuildManager');
21
+ const RelationshipManager = require('../managers/RelationshipManager');
22
+ const SessionManager = require('../managers/SessionManager');
23
+ const UserManager = require('../managers/UserManager');
24
+ const VoiceStateManager = require('../managers/VoiceStateManager');
25
+ const ShardClientUtil = require('../sharding/ShardClientUtil');
26
+ const ClientPresence = require('../structures/ClientPresence');
27
+ const GuildPreview = require('../structures/GuildPreview');
28
+ const GuildTemplate = require('../structures/GuildTemplate');
29
+ const Invite = require('../structures/Invite');
30
+ const { CustomStatus } = require('../structures/RichPresence');
31
+ const { Sticker } = require('../structures/Sticker');
32
+ const StickerPack = require('../structures/StickerPack');
33
+ const VoiceRegion = require('../structures/VoiceRegion');
34
+ const Webhook = require('../structures/Webhook');
35
+ const Widget = require('../structures/Widget');
36
+ const { Events, InviteScopes, Status, captchaServices } = require('../util/Constants');
37
+ const DataResolver = require('../util/DataResolver');
38
+ const Intents = require('../util/Intents');
39
+ const Options = require('../util/Options');
40
+ const Permissions = require('../util/Permissions');
41
+ const DiscordAuthWebsocket = require('../util/RemoteAuth');
42
+ const Sweepers = require('../util/Sweepers');
43
+ const { lazy, testImportModule } = require('../util/Util');
44
+ const Message = lazy(() => require('../structures/Message').Message);
45
+
46
+ /**
47
+ * The main hub for interacting with the Discord API, and the starting point for any bot.
48
+ * @extends {BaseClient}
49
+ */
50
+ class Client extends BaseClient {
51
+ /**
52
+ * @param {ClientOptions} options Options for the client
53
+ */
54
+ constructor(options = {}) {
55
+ super(options);
56
+
57
+ const data = require('node:worker_threads').workerData ?? process.env;
58
+ const defaults = Options.createDefault();
59
+
60
+ if (this.options.shards === defaults.shards) {
61
+ if ('SHARDS' in data) {
62
+ this.options.shards = JSON.parse(data.SHARDS);
63
+ }
64
+ }
65
+
66
+ if (this.options.shardCount === defaults.shardCount) {
67
+ if ('SHARD_COUNT' in data) {
68
+ this.options.shardCount = Number(data.SHARD_COUNT);
69
+ } else if (Array.isArray(this.options.shards)) {
70
+ this.options.shardCount = this.options.shards.length;
71
+ }
72
+ }
73
+
74
+ const typeofShards = typeof this.options.shards;
75
+
76
+ if (typeofShards === 'undefined' && typeof this.options.shardCount === 'number') {
77
+ this.options.shards = Array.from({ length: this.options.shardCount }, (_, i) => i);
78
+ }
79
+
80
+ if (typeofShards === 'number') this.options.shards = [this.options.shards];
81
+
82
+ if (Array.isArray(this.options.shards)) {
83
+ this.options.shards = [
84
+ ...new Set(
85
+ this.options.shards.filter(item => !isNaN(item) && item >= 0 && item < Infinity && item === (item | 0)),
86
+ ),
87
+ ];
88
+ }
89
+
90
+ this._validateOptions();
91
+
92
+ /**
93
+ * Functions called when a cache is garbage collected or the Client is destroyed
94
+ * @type {Set<Function>}
95
+ * @private
96
+ */
97
+ this._cleanups = new Set();
98
+
99
+ /**
100
+ * The finalizers used to cleanup items.
101
+ * @type {FinalizationRegistry}
102
+ * @private
103
+ */
104
+ this._finalizers = new FinalizationRegistry(this._finalize.bind(this));
105
+
106
+ /**
107
+ * The WebSocket manager of the client
108
+ * @type {WebSocketManager}
109
+ */
110
+ this.ws = new WebSocketManager(this);
111
+
112
+ /**
113
+ * The action manager of the client
114
+ * @type {ActionsManager}
115
+ * @private
116
+ */
117
+ this.actions = new ActionsManager(this);
118
+
119
+ /**
120
+ * The voice manager of the client
121
+ * @type {ClientVoiceManager}
122
+ */
123
+ this.voice = new ClientVoiceManager(this);
124
+
125
+ /**
126
+ * A manager of the voice states of this client (Support DM / Group DM)
127
+ * @type {VoiceStateManager}
128
+ */
129
+ this.voiceStates = new VoiceStateManager({ client: this });
130
+
131
+ /**
132
+ * Shard helpers for the client (only if the process was spawned from a {@link ShardingManager})
133
+ * @type {?ShardClientUtil}
134
+ */
135
+ this.shard = process.env.SHARDING_MANAGER
136
+ ? ShardClientUtil.singleton(this, process.env.SHARDING_MANAGER_MODE)
137
+ : null;
138
+
139
+ /**
140
+ * All of the {@link User} objects that have been cached at any point, mapped by their ids
141
+ * @type {UserManager}
142
+ */
143
+ this.users = new UserManager(this);
144
+
145
+ // Patch
146
+ /**
147
+ * All of the relationships {@link User}
148
+ * @type {RelationshipManager}
149
+ */
150
+ this.relationships = new RelationshipManager(this);
151
+ /**
152
+ * All of the settings {@link Object}
153
+ * @type {ClientUserSettingManager}
154
+ */
155
+ this.settings = new ClientUserSettingManager(this);
156
+ /**
157
+ * All of the guilds the client is currently handling, mapped by their ids -
158
+ * as long as sharding isn't being used, this will be *every* guild the bot is a member of
159
+ * @type {GuildManager}
160
+ */
161
+ this.guilds = new GuildManager(this);
162
+
163
+ /**
164
+ * Manages the API methods
165
+ * @type {BillingManager}
166
+ */
167
+ this.billing = new BillingManager(this);
168
+
169
+ /**
170
+ * All of the sessions of the client
171
+ * @type {SessionManager}
172
+ */
173
+ this.sessions = new SessionManager(this);
174
+
175
+ /**
176
+ * All of the {@link Channel}s that the client is currently handling, mapped by their ids -
177
+ * as long as sharding isn't being used, this will be *every* channel in *every* guild the bot
178
+ * is a member of. Note that DM channels will not be initially cached, and thus not be present
179
+ * in the Manager without their explicit fetching or use.
180
+ * @type {ChannelManager}
181
+ */
182
+ this.channels = new ChannelManager(this);
183
+
184
+ /**
185
+ * The sweeping functions and their intervals used to periodically sweep caches
186
+ * @type {Sweepers}
187
+ */
188
+ this.sweepers = new Sweepers(this, this.options.sweepers);
189
+
190
+ /**
191
+ * The developer portal manager of the client
192
+ * @type {DeveloperPortalManager}
193
+ */
194
+ this.developerPortal = new DeveloperPortalManager(this);
195
+
196
+ /**
197
+ * The presence of the Client
198
+ * @private
199
+ * @type {ClientPresence}
200
+ */
201
+ this.presence = new ClientPresence(this, this.options.presence);
202
+
203
+ Object.defineProperty(this, 'token', { writable: true });
204
+ if (!this.token && 'DISCORD_TOKEN' in process.env) {
205
+ /**
206
+ * Authorization token for the logged in bot.
207
+ * If present, this defaults to `process.env.DISCORD_TOKEN` when instantiating the client
208
+ * <warn>This should be kept private at all times.</warn>
209
+ * @type {?string}
210
+ */
211
+ this.token = process.env.DISCORD_TOKEN;
212
+ } else {
213
+ this.token = null;
214
+ }
215
+
216
+ this._interactionCache = new Collection();
217
+
218
+ /**
219
+ * User that the client is logged in as
220
+ * @type {?ClientUser}
221
+ */
222
+ this.user = null;
223
+
224
+ /**
225
+ * The application of this bot
226
+ * @type {?ClientApplication}
227
+ */
228
+ this.application = null;
229
+
230
+ /**
231
+ * Time at which the client was last regarded as being in the `READY` state
232
+ * (each time the client disconnects and successfully reconnects, this will be overwritten)
233
+ * @type {?Date}
234
+ */
235
+ this.readyAt = null;
236
+
237
+ /**
238
+ * Password cache
239
+ * @type {?string}
240
+ */
241
+ this.password = this.options.password;
242
+
243
+ this.session_id = null;
244
+
245
+ if (this.options.messageSweepInterval > 0) {
246
+ process.emitWarning(
247
+ 'The message sweeping client options are deprecated, use the global sweepers instead.',
248
+ 'DeprecationWarning',
249
+ );
250
+ this.sweepMessageInterval = setInterval(
251
+ this.sweepMessages.bind(this),
252
+ this.options.messageSweepInterval * 1_000,
253
+ ).unref();
254
+ }
255
+ }
256
+
257
+ /**
258
+ * Session ID
259
+ * @type {?string}
260
+ * @readonly
261
+ */
262
+ get sessionId() {
263
+ return this.session_id;
264
+ }
265
+
266
+ /**
267
+ * All custom emojis that the client has access to, mapped by their ids
268
+ * @type {BaseGuildEmojiManager}
269
+ * @readonly
270
+ */
271
+ get emojis() {
272
+ const emojis = new BaseGuildEmojiManager(this);
273
+ for (const guild of this.guilds.cache.values()) {
274
+ if (guild.available) for (const emoji of guild.emojis.cache.values()) emojis.cache.set(emoji.id, emoji);
275
+ }
276
+ return emojis;
277
+ }
278
+
279
+ /**
280
+ * Timestamp of the time the client was last `READY` at
281
+ * @type {?number}
282
+ * @readonly
283
+ */
284
+ get readyTimestamp() {
285
+ return this.readyAt?.getTime() ?? null;
286
+ }
287
+
288
+ /**
289
+ * How long it has been since the client last entered the `READY` state in milliseconds
290
+ * @type {?number}
291
+ * @readonly
292
+ */
293
+ get uptime() {
294
+ return this.readyAt ? Date.now() - this.readyAt : null;
295
+ }
296
+
297
+ /**
298
+ * @external VoiceConnection
299
+ * @see {@link https://discord.js.org/#/docs/voice/main/class/VoiceConnection}
300
+ */
301
+ /**
302
+ * Get connection to current call
303
+ * @type {?VoiceConnection}
304
+ * @readonly
305
+ */
306
+ get callVoice() {
307
+ return getVoiceConnection(null);
308
+ }
309
+
310
+ /**
311
+ * Logs the client in, establishing a WebSocket connection to Discord.
312
+ * @param {string} [token=this.token] Token of the account to log in with
313
+ * @returns {Promise<string>} Token of the account used
314
+ * @example
315
+ * client.login('my token');
316
+ */
317
+ async login(token = this.token) {
318
+ if (!token || typeof token !== 'string') throw new Error('TOKEN_INVALID');
319
+ this.token = token = token.replace(/^(Bot|Bearer)\s*/i, '');
320
+ this.emit(
321
+ Events.DEBUG,
322
+ `
323
+ Logging on with a user token is unfortunately against the Discord
324
+ \`Terms of Service\` <https://support.discord.com/hc/en-us/articles/115002192352>
325
+ and doing so might potentially get your account banned.
326
+ Use this at your own risk.
327
+ `,
328
+ );
329
+ this.emit(
330
+ Events.DEBUG,
331
+ `Provided token: ${token
332
+ .split('.')
333
+ .map((val, i) => (i > 1 ? val.replace(/./g, '*') : val))
334
+ .join('.')}`,
335
+ );
336
+
337
+ if (this.options.presence) {
338
+ this.options.ws.presence = this.presence._parse(this.options.presence);
339
+ }
340
+
341
+ this.emit(Events.DEBUG, 'Preparing to connect to the gateway...');
342
+
343
+ try {
344
+ await this.ws.connect();
345
+ return this.token;
346
+ } catch (error) {
347
+ this.destroy();
348
+ throw error;
349
+ }
350
+ }
351
+
352
+ /**
353
+ * Login Discord with Username and Password
354
+ * @param {string} username Email or Phone Number
355
+ * @param {?string} password Password
356
+ * @param {?string} mfaCode 2FA Code / Backup Code
357
+ * @returns {Promise<string>}
358
+ */
359
+ async normalLogin(username, password = this.password, mfaCode) {
360
+ if (!username || !password || typeof username !== 'string' || typeof password !== 'string') {
361
+ throw new Error('NORMAL_LOGIN');
362
+ }
363
+ this.emit(
364
+ Events.DEBUG,
365
+ `Connecting to Discord with:
366
+ username: ${username}
367
+ password: ${password.replace(/./g, '*')}`,
368
+ );
369
+ const data = await this.api.auth.login.post({
370
+ data: {
371
+ login: username,
372
+ password: password,
373
+ undelete: false,
374
+ captcha_key: null,
375
+ login_source: null,
376
+ gift_code_sku_id: null,
377
+ },
378
+ auth: false,
379
+ });
380
+ this.password = password;
381
+ if (!data.token && data.ticket && data.mfa) {
382
+ this.emit(Events.DEBUG, `Using 2FA Code: ${mfaCode}`);
383
+ const normal2fa = /(\d{6})/g;
384
+ const backupCode = /([a-z0-9]{4})-([a-z0-9]{4})/g;
385
+ if (!mfaCode || typeof mfaCode !== 'string') {
386
+ throw new Error('LOGIN_FAILED_2FA');
387
+ }
388
+ if (normal2fa.test(mfaCode) || backupCode.test(mfaCode)) {
389
+ const data2 = await this.api.auth.mfa.totp.post({
390
+ data: {
391
+ code: mfaCode,
392
+ ticket: data.ticket,
393
+ login_source: null,
394
+ gift_code_sku_id: null,
395
+ },
396
+ auth: false,
397
+ });
398
+ return this.login(data2.token);
399
+ } else {
400
+ throw new Error('LOGIN_FAILED_2FA');
401
+ }
402
+ } else if (data.token) {
403
+ return this.login(data.token);
404
+ } else {
405
+ throw new Error('LOGIN_FAILED_UNKNOWN');
406
+ }
407
+ }
408
+
409
+ /**
410
+ * Switch the user
411
+ * @param {string} token User Token
412
+ * @returns {Promise<string>}
413
+ */
414
+ switchUser(token) {
415
+ this._clearCache(this.emojis.cache);
416
+ this._clearCache(this.guilds.cache);
417
+ this._clearCache(this.channels.cache);
418
+ this._clearCache(this.users.cache);
419
+ this._clearCache(this.relationships.cache);
420
+ this._clearCache(this.sessions.cache);
421
+ this._clearCache(this.voiceStates.cache);
422
+ this.ws.status = Status.IDLE;
423
+ return this.login(token);
424
+ }
425
+
426
+ /**
427
+ * Sign in with the QR code on your phone.
428
+ * @param {DiscordAuthWebsocketOptions} options Options
429
+ * @returns {DiscordAuthWebsocket}
430
+ * @example
431
+ * client.QRLogin();
432
+ */
433
+ QRLogin(options = {}) {
434
+ const QR = new DiscordAuthWebsocket({ ...options, autoLogin: true });
435
+ this.emit(Events.DEBUG, `Preparing to connect to the gateway (QR Login)`, QR);
436
+ return QR.connect(this);
437
+ }
438
+
439
+ /**
440
+ * Implement `remoteAuth`, like using your phone to scan a QR code
441
+ * @param {string} url URL from QR code
442
+ * @returns {Promise<void>}
443
+ */
444
+ async remoteAuth(url) {
445
+ if (!this.isReady()) throw new Error('CLIENT_NOT_READY', 'Remote Auth');
446
+ // Step 1: Parse URL
447
+ url = new URL(url);
448
+ if (
449
+ !['discordapp.com', 'discord.com'].includes(url.hostname) ||
450
+ !url.pathname.startsWith('/ra/') ||
451
+ url.pathname.length <= 4
452
+ ) {
453
+ throw new Error('INVALID_REMOTE_AUTH_URL');
454
+ }
455
+ const hash = url.pathname.replace('/ra/', '');
456
+ // Step 2: Post > Get handshake_token
457
+ const res = await this.api.users['@me']['remote-auth'].post({
458
+ data: {
459
+ fingerprint: hash,
460
+ },
461
+ });
462
+ const handshake_token = res.handshake_token;
463
+ // Step 3: Post
464
+ return this.api.users['@me']['remote-auth'].finish.post({ data: { handshake_token, temporary_token: false } });
465
+ // Cancel
466
+ // this.api.users['@me']['remote-auth'].cancel.post({ data: { handshake_token } });
467
+ }
468
+
469
+ /**
470
+ * Create a new token based on the current token
471
+ * @returns {Promise<string>} New Discord Token
472
+ */
473
+ createToken() {
474
+ return new Promise(resolve => {
475
+ // Step 1: Create DiscordAuthWebsocket
476
+ const QR = new DiscordAuthWebsocket({
477
+ hiddenLog: true,
478
+ generateQR: false,
479
+ autoLogin: false,
480
+ debug: false,
481
+ failIfError: false,
482
+ userAgent: this.options.http.headers['User-Agent'],
483
+ wsProperties: this.options.ws.properties,
484
+ });
485
+ // Step 2: Add event
486
+ QR.once('ready', async (_, url) => {
487
+ await this.remoteAuth(url, true);
488
+ }).once('finish', (user, token) => {
489
+ resolve(token);
490
+ });
491
+ // Step 3: Connect
492
+ QR.connect();
493
+ });
494
+ }
495
+
496
+ /**
497
+ * Emitted whenever clientOptions.checkUpdate = false
498
+ * @event Client#update
499
+ * @param {string} oldVersion Current version
500
+ * @param {string} newVersion Latest version
501
+ */
502
+
503
+ /**
504
+ * Check for updates
505
+ * @returns {Promise<Client>}
506
+ */
507
+ async checkUpdate() {
508
+ const res_ = await (
509
+ await fetch(`https://registry.npmjs.com/${encodeURIComponent('djs-selfbot-v13')}`)
510
+ ).json();
511
+ try {
512
+ const latest_tag = res_['dist-tags'].latest;
513
+ this.emit('update', Discord.version, latest_tag);
514
+ this.emit('debug', `${chalk.greenBright('[OK]')} Check Update success`);
515
+ } catch {
516
+ this.emit('debug', `${chalk.redBright('[Fail]')} Check Update error`);
517
+ this.emit('update', Discord.version, false);
518
+ }
519
+ return this;
520
+ }
521
+
522
+ /**
523
+ * Returns whether the client has logged in, indicative of being able to access
524
+ * properties such as `user` and `application`.
525
+ * @returns {boolean}
526
+ */
527
+ isReady() {
528
+ return this.ws.status === Status.READY;
529
+ }
530
+
531
+ /**
532
+ * Logs out, terminates the connection to Discord, and destroys the client.
533
+ * @returns {void}
534
+ */
535
+ destroy() {
536
+ super.destroy();
537
+
538
+ for (const fn of this._cleanups) fn();
539
+ this._cleanups.clear();
540
+
541
+ if (this.sweepMessageInterval) clearInterval(this.sweepMessageInterval);
542
+
543
+ this.sweepers.destroy();
544
+ this.ws.destroy();
545
+ this.token = null;
546
+ this.password = null;
547
+ }
548
+
549
+ /**
550
+ * Logs out, terminates the connection to Discord, destroys the client and destroys the token.
551
+ * @returns {Promise<void>}
552
+ */
553
+ async logout() {
554
+ await this.api.auth.logout.post({
555
+ data: {
556
+ provider: null,
557
+ voip_provider: null,
558
+ },
559
+ });
560
+ await this.destroy();
561
+ }
562
+
563
+ /**
564
+ * Options used when fetching an invite from Discord.
565
+ * @typedef {Object} ClientFetchInviteOptions
566
+ * @property {Snowflake} [guildScheduledEventId] The id of the guild scheduled event to include with
567
+ * the invite
568
+ */
569
+
570
+ /**
571
+ * Obtains an invite from Discord.
572
+ * @param {InviteResolvable} invite Invite code or URL
573
+ * @param {ClientFetchInviteOptions} [options] Options for fetching the invite
574
+ * @returns {Promise<Invite>}
575
+ * @example
576
+ * client.fetchInvite('https://discord.gg/djs')
577
+ * .then(invite => console.log(`Obtained invite with code: ${invite.code}`))
578
+ * .catch(console.error);
579
+ */
580
+ async fetchInvite(invite, options) {
581
+ const code = DataResolver.resolveInviteCode(invite);
582
+ const data = await this.api.invites(code).get({
583
+ query: { with_counts: true, with_expiration: true, guild_scheduled_event_id: options?.guildScheduledEventId },
584
+ });
585
+ return new Invite(this, data);
586
+ }
587
+
588
+ /**
589
+ * Join this Guild using this invite (fast)
590
+ * @param {InviteResolvable} invite Invite code or URL
591
+ * @returns {Promise<void>}
592
+ * @example
593
+ * await client.acceptInvite('https://discord.gg/genshinimpact')
594
+ */
595
+ async acceptInvite(invite) {
596
+ const code = DataResolver.resolveInviteCode(invite);
597
+ if (!code) throw new Error('INVITE_RESOLVE_CODE');
598
+ if (invite instanceof Invite) {
599
+ await invite.acceptInvite();
600
+ } else {
601
+ await this.api.invites(code).post({
602
+ headers: {
603
+ 'X-Context-Properties': 'eyJsb2NhdGlvbiI6Ik1hcmtkb3duIExpbmsifQ==', // Markdown Link
604
+ },
605
+ data: {
606
+ session_id: this.session_id,
607
+ },
608
+ });
609
+ }
610
+ }
611
+
612
+ /**
613
+ * Automatically Redeem Nitro from raw message.
614
+ * @param {Message} message Discord Message
615
+ * @private
616
+ */
617
+ async autoRedeemNitro(message) {
618
+ if (!(message instanceof Message())) return;
619
+ if (!message.content) return;
620
+ const allLinks =
621
+ message.content.match(/(discord.gift|discord.com|discordapp.com\/gifts)\/(\w{16,25})/gm) ||
622
+ message.content.match(/(discord\.gift\/|discord\.com\/gifts\/|discordapp\.com\/gifts\/)(\w+)/gm);
623
+ if (!allLinks) return;
624
+ for (const link of allLinks) {
625
+ await this.redeemNitro(link, message.channel);
626
+ }
627
+ }
628
+
629
+ /**
630
+ * Redeem nitro from code or url.
631
+ * @param {string} nitro Nitro url or code
632
+ * @param {TextChannelResolvable} channel Channel that the code was sent in
633
+ * @param {Snowflake} [paymentSourceId] Payment source id
634
+ * @returns {Promise<any>}
635
+ */
636
+ redeemNitro(nitro, channel, paymentSourceId) {
637
+ if (typeof nitro !== 'string') throw new Error('INVALID_NITRO');
638
+ const nitroCode =
639
+ nitro.match(/(discord.gift|discord.com|discordapp.com\/gifts)\/(\w{16,25})/) ||
640
+ nitro.match(/(discord\.gift\/|discord\.com\/gifts\/|discordapp\.com\/gifts\/)(\w+)/);
641
+ if (!nitroCode) return false;
642
+ const code = nitroCode[2];
643
+ channel = this.channels.resolveId(channel);
644
+ return this.api.entitlements['gift-codes'](code).redeem.post({
645
+ auth: true,
646
+ data: { channel_id: channel || null, payment_source_id: paymentSourceId || null },
647
+ });
648
+ }
649
+
650
+ /**
651
+ * Obtains a template from Discord.
652
+ * @param {GuildTemplateResolvable} template Template code or URL
653
+ * @returns {Promise<GuildTemplate>}
654
+ * @example
655
+ * client.fetchGuildTemplate('https://discord.new/FKvmczH2HyUf')
656
+ * .then(template => console.log(`Obtained template with code: ${template.code}`))
657
+ * .catch(console.error);
658
+ */
659
+ async fetchGuildTemplate(template) {
660
+ const code = DataResolver.resolveGuildTemplateCode(template);
661
+ const data = await this.api.guilds.templates(code).get();
662
+ return new GuildTemplate(this, data);
663
+ }
664
+
665
+ /**
666
+ * Obtains a webhook from Discord.
667
+ * @param {Snowflake} id The webhook's id
668
+ * @param {string} [token] Token for the webhook
669
+ * @returns {Promise<Webhook>}
670
+ * @example
671
+ * client.fetchWebhook('id', 'token')
672
+ * .then(webhook => console.log(`Obtained webhook with name: ${webhook.name}`))
673
+ * .catch(console.error);
674
+ */
675
+ async fetchWebhook(id, token) {
676
+ const data = await this.api.webhooks(id, token).get();
677
+ return new Webhook(this, { token, ...data });
678
+ }
679
+
680
+ /**
681
+ * Obtains the available voice regions from Discord.
682
+ * @returns {Promise<Collection<string, VoiceRegion>>}
683
+ * @example
684
+ * client.fetchVoiceRegions()
685
+ * .then(regions => console.log(`Available regions are: ${regions.map(region => region.name).join(', ')}`))
686
+ * .catch(console.error);
687
+ */
688
+ async fetchVoiceRegions() {
689
+ const apiRegions = await this.api.voice.regions.get();
690
+ const regions = new Collection();
691
+ for (const region of apiRegions) regions.set(region.id, new VoiceRegion(region));
692
+ return regions;
693
+ }
694
+
695
+ /**
696
+ * Obtains a sticker from Discord.
697
+ * @param {Snowflake} id The sticker's id
698
+ * @returns {Promise<Sticker>}
699
+ * @example
700
+ * client.fetchSticker('id')
701
+ * .then(sticker => console.log(`Obtained sticker with name: ${sticker.name}`))
702
+ * .catch(console.error);
703
+ */
704
+ async fetchSticker(id) {
705
+ const data = await this.api.stickers(id).get();
706
+ return new Sticker(this, data);
707
+ }
708
+
709
+ /**
710
+ * Obtains the list of sticker packs available to Nitro subscribers from Discord.
711
+ * @returns {Promise<Collection<Snowflake, StickerPack>>}
712
+ * @example
713
+ * client.fetchPremiumStickerPacks()
714
+ * .then(packs => console.log(`Available sticker packs are: ${packs.map(pack => pack.name).join(', ')}`))
715
+ * .catch(console.error);
716
+ */
717
+ async fetchPremiumStickerPacks() {
718
+ const data = await this.api('sticker-packs').get();
719
+ return new Collection(data.sticker_packs.map(p => [p.id, new StickerPack(this, p)]));
720
+ }
721
+ /**
722
+ * A last ditch cleanup function for garbage collection.
723
+ * @param {Function} options.cleanup The function called to GC
724
+ * @param {string} [options.message] The message to send after a successful GC
725
+ * @param {string} [options.name] The name of the item being GCed
726
+ * @private
727
+ */
728
+ _finalize({ cleanup, message, name }) {
729
+ try {
730
+ cleanup();
731
+ this._cleanups.delete(cleanup);
732
+ if (message) {
733
+ this.emit(Events.DEBUG, message);
734
+ }
735
+ } catch {
736
+ this.emit(Events.DEBUG, `Garbage collection failed on ${name ?? 'an unknown item'}.`);
737
+ }
738
+ }
739
+
740
+ /**
741
+ * Clear a cache
742
+ * @param {Collection} cache The cache to clear
743
+ * @returns {number} The number of removed entries
744
+ * @private
745
+ */
746
+ _clearCache(cache) {
747
+ return cache.sweep(() => true);
748
+ }
749
+
750
+ /**
751
+ * Sweeps all text-based channels' messages and removes the ones older than the max message lifetime.
752
+ * If the message has been edited, the time of the edit is used rather than the time of the original message.
753
+ * @param {number} [lifetime=this.options.messageCacheLifetime] Messages that are older than this (in seconds)
754
+ * will be removed from the caches. The default is based on {@link ClientOptions#messageCacheLifetime}
755
+ * @returns {number} Amount of messages that were removed from the caches,
756
+ * or -1 if the message cache lifetime is unlimited
757
+ * @example
758
+ * // Remove all messages older than 1800 seconds from the messages cache
759
+ * const amount = client.sweepMessages(1800);
760
+ * console.log(`Successfully removed ${amount} messages from the cache.`);
761
+ */
762
+ sweepMessages(lifetime = this.options.messageCacheLifetime) {
763
+ if (typeof lifetime !== 'number' || isNaN(lifetime)) {
764
+ throw new TypeError('INVALID_TYPE', 'lifetime', 'number');
765
+ }
766
+ if (lifetime <= 0) {
767
+ this.emit(Events.DEBUG, "Didn't sweep messages - lifetime is unlimited");
768
+ return -1;
769
+ }
770
+
771
+ const messages = this.sweepers.sweepMessages(Sweepers.outdatedMessageSweepFilter(lifetime)());
772
+ this.emit(Events.DEBUG, `Swept ${messages} messages older than ${lifetime} seconds`);
773
+ return messages;
774
+ }
775
+
776
+ /**
777
+ * Obtains a guild preview from Discord, available for all guilds the bot is in and all Discoverable guilds.
778
+ * @param {GuildResolvable} guild The guild to fetch the preview for
779
+ * @returns {Promise<GuildPreview>}
780
+ */
781
+ async fetchGuildPreview(guild) {
782
+ const id = this.guilds.resolveId(guild);
783
+ if (!id) throw new TypeError('INVALID_TYPE', 'guild', 'GuildResolvable');
784
+ const data = await this.api.guilds(id).preview.get();
785
+ return new GuildPreview(this, data);
786
+ }
787
+
788
+ /**
789
+ * Obtains the widget data of a guild from Discord, available for guilds with the widget enabled.
790
+ * @param {GuildResolvable} guild The guild to fetch the widget data for
791
+ * @returns {Promise<Widget>}
792
+ */
793
+ async fetchGuildWidget(guild) {
794
+ const id = this.guilds.resolveId(guild);
795
+ if (!id) throw new TypeError('INVALID_TYPE', 'guild', 'GuildResolvable');
796
+ const data = await this.api.guilds(id, 'widget.json').get();
797
+ return new Widget(this, data);
798
+ }
799
+
800
+ /**
801
+ * Options for {@link Client#generateInvite}.
802
+ * @typedef {Object} InviteGenerationOptions
803
+ * @property {InviteScope[]} scopes Scopes that should be requested
804
+ * @property {PermissionResolvable} [permissions] Permissions to request
805
+ * @property {GuildResolvable} [guild] Guild to preselect
806
+ * @property {boolean} [disableGuildSelect] Whether to disable the guild selection
807
+ */
808
+
809
+ /**
810
+ * Generates a link that can be used to invite the bot to a guild.
811
+ * @param {InviteGenerationOptions} [options={}] Options for the invite
812
+ * @returns {string}
813
+ * @example
814
+ * const link = client.generateInvite({
815
+ * scopes: ['applications.commands'],
816
+ * });
817
+ * console.log(`Generated application invite link: ${link}`);
818
+ * @example
819
+ * const link = client.generateInvite({
820
+ * permissions: [
821
+ * Permissions.FLAGS.SEND_MESSAGES,
822
+ * Permissions.FLAGS.MANAGE_GUILD,
823
+ * Permissions.FLAGS.MENTION_EVERYONE,
824
+ * ],
825
+ * scopes: ['bot'],
826
+ * });
827
+ * console.log(`Generated bot invite link: ${link}`);
828
+ */
829
+ generateInvite(options = {}) {
830
+ if (typeof options !== 'object') throw new TypeError('INVALID_TYPE', 'options', 'object', true);
831
+ if (!this.application) throw new Error('CLIENT_NOT_READY', 'generate an invite link');
832
+
833
+ const query = new URLSearchParams({
834
+ client_id: this.application.id,
835
+ });
836
+
837
+ const { scopes } = options;
838
+ if (typeof scopes === 'undefined') {
839
+ throw new TypeError('INVITE_MISSING_SCOPES');
840
+ }
841
+ if (!Array.isArray(scopes)) {
842
+ throw new TypeError('INVALID_TYPE', 'scopes', 'Array of Invite Scopes', true);
843
+ }
844
+ if (!scopes.some(scope => ['bot', 'applications.commands'].includes(scope))) {
845
+ throw new TypeError('INVITE_MISSING_SCOPES');
846
+ }
847
+ const invalidScope = scopes.find(scope => !InviteScopes.includes(scope));
848
+ if (invalidScope) {
849
+ throw new TypeError('INVALID_ELEMENT', 'Array', 'scopes', invalidScope);
850
+ }
851
+ query.set('scope', scopes.join(' '));
852
+
853
+ if (options.permissions) {
854
+ const permissions = Permissions.resolve(options.permissions);
855
+ if (permissions) query.set('permissions', permissions);
856
+ }
857
+
858
+ if (options.disableGuildSelect) {
859
+ query.set('disable_guild_select', true);
860
+ }
861
+
862
+ if (options.guild) {
863
+ const guildId = this.guilds.resolveId(options.guild);
864
+ if (!guildId) throw new TypeError('INVALID_TYPE', 'options.guild', 'GuildResolvable');
865
+ query.set('guild_id', guildId);
866
+ }
867
+
868
+ return `${this.options.http.api}${this.api.oauth2.authorize}?${query}`;
869
+ }
870
+
871
+ toJSON() {
872
+ return super.toJSON({
873
+ readyAt: false,
874
+ });
875
+ }
876
+
877
+ /**
878
+ * Calls {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval} on a script
879
+ * with the client as `this`.
880
+ * @param {string} script Script to eval
881
+ * @returns {*}
882
+ * @private
883
+ */
884
+ _eval(script) {
885
+ return eval(script);
886
+ }
887
+
888
+ /**
889
+ * Sets the client's presence. (Sync Setting).
890
+ * @param {Client} client Discord Client
891
+ * @private
892
+ */
893
+ customStatusAuto(client) {
894
+ client = client ?? this;
895
+ if (!client.user) return;
896
+ const custom_status = new CustomStatus();
897
+ if (!client.settings.rawSetting.custom_status?.text && !client.settings.rawSetting.custom_status?.emoji_name) {
898
+ client.user.setPresence({
899
+ activities: this.presence.activities.filter(a => a.type !== 'CUSTOM'),
900
+ status: client.settings.rawSetting.status ?? 'invisible',
901
+ });
902
+ } else {
903
+ custom_status.setEmoji({
904
+ name: client.settings.rawSetting.custom_status?.emoji_name,
905
+ id: client.settings.rawSetting.custom_status?.emoji_id,
906
+ });
907
+ custom_status.setState(client.settings.rawSetting.custom_status?.text);
908
+ client.user.setPresence({
909
+ activities: [custom_status.toJSON(), ...this.presence.activities.filter(a => a.type !== 'CUSTOM')],
910
+ status: client.settings.rawSetting.status ?? 'invisible',
911
+ });
912
+ }
913
+ }
914
+
915
+ /**
916
+ * @typedef {Object} OAuth2AuthorizeOptions
917
+ * @property {string} [guild_id] Guild ID
918
+ * @property {PermissionResolvable} [permissions] Permissions
919
+ * @property {boolean} [authorize] Whether to authorize or not
920
+ * @property {string} [code] 2FA Code
921
+ * @property {string} [webhook_channel_id] Webhook Channel ID
922
+ */
923
+
924
+ /**
925
+ * Authorize an application.
926
+ * @param {string} url Discord Auth URL
927
+ * @param {OAuth2AuthorizeOptions} options Oauth2 options
928
+ * @returns {Promise<Object>}
929
+ * @example
930
+ * client.authorizeURL(`https://discord.com/api/oauth2/authorize?client_id=botID&permissions=8&scope=applications.commands%20bot`, {
931
+ guild_id: "guildID",
932
+ permissions: "62221393", // your permissions
933
+ authorize: true
934
+ })
935
+ */
936
+ authorizeURL(url, options = { authorize: true, permissions: '0' }) {
937
+ const pathnameAPI = /\/api\/(v\d{1,2}\/)?oauth2\/authorize/;
938
+ const pathnameURL = /\/oauth2\/authorize/;
939
+ const url_ = new URL(url);
940
+ if (
941
+ !['discord.com', 'canary.discord.com', 'ptb.discord.com'].includes(url_.hostname) ||
942
+ (!pathnameAPI.test(url_.pathname) && !pathnameURL.test(url_.pathname))
943
+ ) {
944
+ throw new Error('INVALID_URL', url);
945
+ }
946
+ const searchParams = Object.fromEntries(url_.searchParams);
947
+ options.permissions = `${Permissions.resolve(searchParams.permissions || options.permissions) || 0}`;
948
+ delete searchParams.permissions;
949
+ return this.api.oauth2.authorize.post({
950
+ query: searchParams,
951
+ data: options,
952
+ });
953
+ }
954
+
955
+ /**
956
+ * Makes waiting time for Client.
957
+ * @param {number} miliseconds Sleeping time as milliseconds.
958
+ * @returns {Promise<void> | null}
959
+ */
960
+ sleep(miliseconds) {
961
+ return typeof miliseconds === 'number' ? new Promise(r => setTimeout(r, miliseconds).unref()) : null;
962
+ }
963
+
964
+ /**
965
+ * Validates the client options.
966
+ * @param {ClientOptions} [options=this.options] Options to validate
967
+ * @private
968
+ */
969
+ _validateOptions(options = this.options) {
970
+ if (typeof options.intents === 'undefined') {
971
+ throw new TypeError('CLIENT_MISSING_INTENTS');
972
+ } else {
973
+ options.intents = Intents.resolve(options.intents);
974
+ }
975
+ if (options && typeof options.checkUpdate !== 'boolean') {
976
+ throw new TypeError('CLIENT_INVALID_OPTION', 'checkUpdate', 'a boolean');
977
+ }
978
+ if (options && typeof options.syncStatus !== 'boolean') {
979
+ throw new TypeError('CLIENT_INVALID_OPTION', 'syncStatus', 'a boolean');
980
+ }
981
+ if (options && typeof options.autoRedeemNitro !== 'boolean') {
982
+ throw new TypeError('CLIENT_INVALID_OPTION', 'autoRedeemNitro', 'a boolean');
983
+ }
984
+ if (options && options.captchaService && !captchaServices.includes(options.captchaService)) {
985
+ throw new TypeError('CLIENT_INVALID_OPTION', 'captchaService', captchaServices.join(', '));
986
+ }
987
+ // Parse captcha key
988
+ if (options && captchaServices.includes(options.captchaService) && options.captchaService !== 'custom') {
989
+ if (typeof options.captchaKey !== 'string') {
990
+ throw new TypeError('CLIENT_INVALID_OPTION', 'captchaKey', 'a string');
991
+ }
992
+ switch (options.captchaService) {
993
+ case '2captcha':
994
+ if (options.captchaKey.length !== 32) {
995
+ throw new TypeError('CLIENT_INVALID_OPTION', 'captchaKey', 'a 32 character string');
996
+ }
997
+ break;
998
+ case 'capmonster':
999
+ if (options.captchaKey.length !== 32) {
1000
+ throw new TypeError('CLIENT_INVALID_OPTION', 'captchaKey', 'a 32 character string');
1001
+ }
1002
+ break;
1003
+ case 'nopecha': {
1004
+ if (options.captchaKey.length !== 16) {
1005
+ throw new TypeError('CLIENT_INVALID_OPTION', 'captchaKey', 'a 16 character string');
1006
+ }
1007
+ break;
1008
+ }
1009
+ }
1010
+ }
1011
+ if (typeof options.captchaRetryLimit !== 'number' || isNaN(options.captchaRetryLimit)) {
1012
+ throw new TypeError('CLIENT_INVALID_OPTION', 'captchaRetryLimit', 'a number');
1013
+ }
1014
+ if (options && typeof options.captchaSolver !== 'function') {
1015
+ throw new TypeError('CLIENT_INVALID_OPTION', 'captchaSolver', 'a function');
1016
+ }
1017
+ if (options && typeof options.captchaWithProxy !== 'boolean') {
1018
+ throw new TypeError('CLIENT_INVALID_OPTION', 'captchaWithProxy', 'a boolean');
1019
+ }
1020
+ if (options && typeof options.DMSync !== 'boolean') {
1021
+ throw new TypeError('CLIENT_INVALID_OPTION', 'DMSync', 'a boolean');
1022
+ }
1023
+ if (options && typeof options.patchVoice !== 'boolean') {
1024
+ throw new TypeError('CLIENT_INVALID_OPTION', 'patchVoice', 'a boolean');
1025
+ }
1026
+ if (options && options.password && typeof options.password !== 'string') {
1027
+ throw new TypeError('CLIENT_INVALID_OPTION', 'password', 'a string');
1028
+ }
1029
+ if (options && options.usingNewAttachmentAPI && typeof options.usingNewAttachmentAPI !== 'boolean') {
1030
+ throw new TypeError('CLIENT_INVALID_OPTION', 'usingNewAttachmentAPI', 'a boolean');
1031
+ }
1032
+ if (options && options.interactionTimeout && typeof options.interactionTimeout !== 'number') {
1033
+ throw new TypeError('CLIENT_INVALID_OPTION', 'interactionTimeout', 'a number');
1034
+ }
1035
+ if (options && typeof options.proxy !== 'string') {
1036
+ throw new TypeError('CLIENT_INVALID_OPTION', 'proxy', 'a string');
1037
+ } else if (
1038
+ options &&
1039
+ options.proxy &&
1040
+ typeof options.proxy === 'string' &&
1041
+ testImportModule('proxy-agent') === false
1042
+ ) {
1043
+ throw new Error('MISSING_MODULE', 'proxy-agent', 'npm install proxy-agent');
1044
+ }
1045
+ if (typeof options.shardCount !== 'number' || isNaN(options.shardCount) || options.shardCount < 1) {
1046
+ throw new TypeError('CLIENT_INVALID_OPTION', 'shardCount', 'a number greater than or equal to 1');
1047
+ }
1048
+ if (options.shards && !(options.shards === 'auto' || Array.isArray(options.shards))) {
1049
+ throw new TypeError('CLIENT_INVALID_OPTION', 'shards', "'auto', a number or array of numbers");
1050
+ }
1051
+ if (options.shards && !options.shards.length) throw new RangeError('CLIENT_INVALID_PROVIDED_SHARDS');
1052
+ if (typeof options.makeCache !== 'function') {
1053
+ throw new TypeError('CLIENT_INVALID_OPTION', 'makeCache', 'a function');
1054
+ }
1055
+ if (typeof options.messageCacheLifetime !== 'number' || isNaN(options.messageCacheLifetime)) {
1056
+ throw new TypeError('CLIENT_INVALID_OPTION', 'The messageCacheLifetime', 'a number');
1057
+ }
1058
+ if (typeof options.messageSweepInterval !== 'number' || isNaN(options.messageSweepInterval)) {
1059
+ throw new TypeError('CLIENT_INVALID_OPTION', 'messageSweepInterval', 'a number');
1060
+ }
1061
+ if (typeof options.sweepers !== 'object' || options.sweepers === null) {
1062
+ throw new TypeError('CLIENT_INVALID_OPTION', 'sweepers', 'an object');
1063
+ }
1064
+ if (typeof options.invalidRequestWarningInterval !== 'number' || isNaN(options.invalidRequestWarningInterval)) {
1065
+ throw new TypeError('CLIENT_INVALID_OPTION', 'invalidRequestWarningInterval', 'a number');
1066
+ }
1067
+ if (!Array.isArray(options.partials)) {
1068
+ throw new TypeError('CLIENT_INVALID_OPTION', 'partials', 'an Array');
1069
+ }
1070
+ if (typeof options.waitGuildTimeout !== 'number' || isNaN(options.waitGuildTimeout)) {
1071
+ throw new TypeError('CLIENT_INVALID_OPTION', 'waitGuildTimeout', 'a number');
1072
+ }
1073
+ if (typeof options.messageCreateEventGuildTimeout !== 'number' || isNaN(options.messageCreateEventGuildTimeout)) {
1074
+ throw new TypeError('CLIENT_INVALID_OPTION', 'messageCreateEventGuildTimeout', 'a number');
1075
+ }
1076
+ if (typeof options.restWsBridgeTimeout !== 'number' || isNaN(options.restWsBridgeTimeout)) {
1077
+ throw new TypeError('CLIENT_INVALID_OPTION', 'restWsBridgeTimeout', 'a number');
1078
+ }
1079
+ if (typeof options.restRequestTimeout !== 'number' || isNaN(options.restRequestTimeout)) {
1080
+ throw new TypeError('CLIENT_INVALID_OPTION', 'restRequestTimeout', 'a number');
1081
+ }
1082
+ if (typeof options.restGlobalRateLimit !== 'number' || isNaN(options.restGlobalRateLimit)) {
1083
+ throw new TypeError('CLIENT_INVALID_OPTION', 'restGlobalRateLimit', 'a number');
1084
+ }
1085
+ if (typeof options.restSweepInterval !== 'number' || isNaN(options.restSweepInterval)) {
1086
+ throw new TypeError('CLIENT_INVALID_OPTION', 'restSweepInterval', 'a number');
1087
+ }
1088
+ if (typeof options.retryLimit !== 'number' || isNaN(options.retryLimit)) {
1089
+ throw new TypeError('CLIENT_INVALID_OPTION', 'retryLimit', 'a number');
1090
+ }
1091
+ if (typeof options.failIfNotExists !== 'boolean') {
1092
+ throw new TypeError('CLIENT_INVALID_OPTION', 'failIfNotExists', 'a boolean');
1093
+ }
1094
+ if (!Array.isArray(options.userAgentSuffix)) {
1095
+ throw new TypeError('CLIENT_INVALID_OPTION', 'userAgentSuffix', 'an array of strings');
1096
+ }
1097
+ if (
1098
+ typeof options.rejectOnRateLimit !== 'undefined' &&
1099
+ !(typeof options.rejectOnRateLimit === 'function' || Array.isArray(options.rejectOnRateLimit))
1100
+ ) {
1101
+ throw new TypeError('CLIENT_INVALID_OPTION', 'rejectOnRateLimit', 'an array or a function');
1102
+ }
1103
+ }
1104
+ }
1105
+
1106
+ module.exports = Client;
1107
+
1108
+ /**
1109
+ * Emitted for general warnings.
1110
+ * @event Client#warn
1111
+ * @param {string} info The warning
1112
+ */
1113
+
1114
+ /**
1115
+ * @external Collection
1116
+ * @see {@link https://discord.js.org/docs/packages/collection/stable/Collection:Class}
1117
+ */