discord.js-selfbots-v13 0.0.1-security → 3.3.0

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of discord.js-selfbots-v13 might be problematic. Click here for more details.

Files changed (343) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +127 -5
  3. package/package.json +101 -6
  4. package/src/WebSocket.js +39 -0
  5. package/src/client/BaseClient.js +87 -0
  6. package/src/client/Client.js +1154 -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 +34 -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 +908 -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_STICKERS_UPDATE.js +5 -0
  111. package/src/client/websocket/handlers/GUILD_UPDATE.js +5 -0
  112. package/src/client/websocket/handlers/INTERACTION_CREATE.js +16 -0
  113. package/src/client/websocket/handlers/INTERACTION_FAILURE.js +18 -0
  114. package/src/client/websocket/handlers/INTERACTION_MODAL_CREATE.js +11 -0
  115. package/src/client/websocket/handlers/INTERACTION_SUCCESS.js +30 -0
  116. package/src/client/websocket/handlers/INVITE_CREATE.js +5 -0
  117. package/src/client/websocket/handlers/INVITE_DELETE.js +5 -0
  118. package/src/client/websocket/handlers/MESSAGE_ACK.js +16 -0
  119. package/src/client/websocket/handlers/MESSAGE_CREATE.js +5 -0
  120. package/src/client/websocket/handlers/MESSAGE_DELETE.js +5 -0
  121. package/src/client/websocket/handlers/MESSAGE_DELETE_BULK.js +5 -0
  122. package/src/client/websocket/handlers/MESSAGE_REACTION_ADD.js +5 -0
  123. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE.js +5 -0
  124. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE_ALL.js +5 -0
  125. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE_EMOJI.js +5 -0
  126. package/src/client/websocket/handlers/MESSAGE_UPDATE.js +16 -0
  127. package/src/client/websocket/handlers/PRESENCE_UPDATE.js +5 -0
  128. package/src/client/websocket/handlers/READY.js +172 -0
  129. package/src/client/websocket/handlers/RELATIONSHIP_ADD.js +17 -0
  130. package/src/client/websocket/handlers/RELATIONSHIP_REMOVE.js +15 -0
  131. package/src/client/websocket/handlers/RELATIONSHIP_UPDATE.js +18 -0
  132. package/src/client/websocket/handlers/RESUMED.js +14 -0
  133. package/src/client/websocket/handlers/STAGE_INSTANCE_CREATE.js +5 -0
  134. package/src/client/websocket/handlers/STAGE_INSTANCE_DELETE.js +5 -0
  135. package/src/client/websocket/handlers/STAGE_INSTANCE_UPDATE.js +5 -0
  136. package/src/client/websocket/handlers/THREAD_CREATE.js +5 -0
  137. package/src/client/websocket/handlers/THREAD_DELETE.js +5 -0
  138. package/src/client/websocket/handlers/THREAD_LIST_SYNC.js +5 -0
  139. package/src/client/websocket/handlers/THREAD_MEMBERS_UPDATE.js +5 -0
  140. package/src/client/websocket/handlers/THREAD_MEMBER_UPDATE.js +5 -0
  141. package/src/client/websocket/handlers/THREAD_UPDATE.js +16 -0
  142. package/src/client/websocket/handlers/TYPING_START.js +5 -0
  143. package/src/client/websocket/handlers/USER_GUILD_SETTINGS_UPDATE.js +12 -0
  144. package/src/client/websocket/handlers/USER_NOTE_UPDATE.js +5 -0
  145. package/src/client/websocket/handlers/USER_SETTINGS_UPDATE.js +9 -0
  146. package/src/client/websocket/handlers/USER_UPDATE.js +5 -0
  147. package/src/client/websocket/handlers/VOICE_SERVER_UPDATE.js +6 -0
  148. package/src/client/websocket/handlers/VOICE_STATE_UPDATE.js +5 -0
  149. package/src/client/websocket/handlers/WEBHOOKS_UPDATE.js +5 -0
  150. package/src/client/websocket/handlers/index.js +86 -0
  151. package/src/errors/DJSError.js +61 -0
  152. package/src/errors/Messages.js +227 -0
  153. package/src/errors/index.js +4 -0
  154. package/src/index.js +190 -0
  155. package/src/main.js +1 -0
  156. package/src/managers/ApplicationCommandManager.js +267 -0
  157. package/src/managers/ApplicationCommandPermissionsManager.js +425 -0
  158. package/src/managers/AutoModerationRuleManager.js +296 -0
  159. package/src/managers/BaseGuildEmojiManager.js +80 -0
  160. package/src/managers/BaseManager.js +19 -0
  161. package/src/managers/BillingManager.js +66 -0
  162. package/src/managers/CachedManager.js +71 -0
  163. package/src/managers/ChannelManager.js +139 -0
  164. package/src/managers/ClientUserSettingManager.js +490 -0
  165. package/src/managers/DataManager.js +61 -0
  166. package/src/managers/DeveloperPortalManager.js +104 -0
  167. package/src/managers/GuildApplicationCommandManager.js +28 -0
  168. package/src/managers/GuildBanManager.js +204 -0
  169. package/src/managers/GuildChannelManager.js +502 -0
  170. package/src/managers/GuildEmojiManager.js +171 -0
  171. package/src/managers/GuildEmojiRoleManager.js +118 -0
  172. package/src/managers/GuildFolderManager.js +24 -0
  173. package/src/managers/GuildForumThreadManager.js +114 -0
  174. package/src/managers/GuildInviteManager.js +213 -0
  175. package/src/managers/GuildManager.js +304 -0
  176. package/src/managers/GuildMemberManager.js +724 -0
  177. package/src/managers/GuildMemberRoleManager.js +191 -0
  178. package/src/managers/GuildScheduledEventManager.js +296 -0
  179. package/src/managers/GuildSettingManager.js +148 -0
  180. package/src/managers/GuildStickerManager.js +179 -0
  181. package/src/managers/GuildTextThreadManager.js +98 -0
  182. package/src/managers/InteractionManager.js +39 -0
  183. package/src/managers/MessageManager.js +393 -0
  184. package/src/managers/PermissionOverwriteManager.js +166 -0
  185. package/src/managers/PresenceManager.js +58 -0
  186. package/src/managers/ReactionManager.js +67 -0
  187. package/src/managers/ReactionUserManager.js +71 -0
  188. package/src/managers/RelationshipManager.js +258 -0
  189. package/src/managers/RoleManager.js +352 -0
  190. package/src/managers/SessionManager.js +57 -0
  191. package/src/managers/StageInstanceManager.js +162 -0
  192. package/src/managers/ThreadManager.js +207 -0
  193. package/src/managers/ThreadMemberManager.js +186 -0
  194. package/src/managers/UserManager.js +150 -0
  195. package/src/managers/VoiceStateManager.js +37 -0
  196. package/src/rest/APIRequest.js +136 -0
  197. package/src/rest/APIRouter.js +53 -0
  198. package/src/rest/CaptchaSolver.js +78 -0
  199. package/src/rest/DiscordAPIError.js +103 -0
  200. package/src/rest/HTTPError.js +62 -0
  201. package/src/rest/RESTManager.js +81 -0
  202. package/src/rest/RateLimitError.js +55 -0
  203. package/src/rest/RequestHandler.js +446 -0
  204. package/src/sharding/Shard.js +443 -0
  205. package/src/sharding/ShardClientUtil.js +275 -0
  206. package/src/sharding/ShardingManager.js +318 -0
  207. package/src/structures/AnonymousGuild.js +98 -0
  208. package/src/structures/ApplicationCommand.js +1028 -0
  209. package/src/structures/ApplicationRoleConnectionMetadata.js +45 -0
  210. package/src/structures/AutoModerationActionExecution.js +89 -0
  211. package/src/structures/AutoModerationRule.js +294 -0
  212. package/src/structures/AutocompleteInteraction.js +106 -0
  213. package/src/structures/Base.js +43 -0
  214. package/src/structures/BaseCommandInteraction.js +211 -0
  215. package/src/structures/BaseGuild.js +116 -0
  216. package/src/structures/BaseGuildEmoji.js +56 -0
  217. package/src/structures/BaseGuildTextChannel.js +193 -0
  218. package/src/structures/BaseGuildVoiceChannel.js +243 -0
  219. package/src/structures/BaseMessageComponent.js +114 -0
  220. package/src/structures/ButtonInteraction.js +11 -0
  221. package/src/structures/Call.js +58 -0
  222. package/src/structures/CategoryChannel.js +83 -0
  223. package/src/structures/Channel.js +271 -0
  224. package/src/structures/ClientApplication.js +204 -0
  225. package/src/structures/ClientPresence.js +84 -0
  226. package/src/structures/ClientUser.js +624 -0
  227. package/src/structures/CommandInteraction.js +41 -0
  228. package/src/structures/CommandInteractionOptionResolver.js +276 -0
  229. package/src/structures/ContextMenuInteraction.js +65 -0
  230. package/src/structures/DMChannel.js +280 -0
  231. package/src/structures/DeveloperPortalApplication.js +520 -0
  232. package/src/structures/DirectoryChannel.js +20 -0
  233. package/src/structures/Emoji.js +148 -0
  234. package/src/structures/ForumChannel.js +271 -0
  235. package/src/structures/Guild.js +1744 -0
  236. package/src/structures/GuildAuditLogs.js +734 -0
  237. package/src/structures/GuildBan.js +59 -0
  238. package/src/structures/GuildBoost.js +108 -0
  239. package/src/structures/GuildChannel.js +454 -0
  240. package/src/structures/GuildEmoji.js +161 -0
  241. package/src/structures/GuildFolder.js +75 -0
  242. package/src/structures/GuildMember.js +686 -0
  243. package/src/structures/GuildPreview.js +191 -0
  244. package/src/structures/GuildPreviewEmoji.js +27 -0
  245. package/src/structures/GuildScheduledEvent.js +441 -0
  246. package/src/structures/GuildTemplate.js +236 -0
  247. package/src/structures/Integration.js +188 -0
  248. package/src/structures/IntegrationApplication.js +96 -0
  249. package/src/structures/Interaction.js +351 -0
  250. package/src/structures/InteractionCollector.js +248 -0
  251. package/src/structures/InteractionResponse.js +114 -0
  252. package/src/structures/InteractionWebhook.js +43 -0
  253. package/src/structures/Invite.js +375 -0
  254. package/src/structures/InviteGuild.js +23 -0
  255. package/src/structures/InviteStageInstance.js +86 -0
  256. package/src/structures/Message.js +1188 -0
  257. package/src/structures/MessageActionRow.js +103 -0
  258. package/src/structures/MessageAttachment.js +193 -0
  259. package/src/structures/MessageButton.js +231 -0
  260. package/src/structures/MessageCollector.js +146 -0
  261. package/src/structures/MessageComponentInteraction.js +120 -0
  262. package/src/structures/MessageContextMenuInteraction.js +20 -0
  263. package/src/structures/MessageEmbed.js +586 -0
  264. package/src/structures/MessageMentions.js +272 -0
  265. package/src/structures/MessagePayload.js +358 -0
  266. package/src/structures/MessageReaction.js +171 -0
  267. package/src/structures/MessageSelectMenu.js +391 -0
  268. package/src/structures/Modal.js +279 -0
  269. package/src/structures/ModalSubmitFieldsResolver.js +53 -0
  270. package/src/structures/ModalSubmitInteraction.js +119 -0
  271. package/src/structures/NewsChannel.js +32 -0
  272. package/src/structures/OAuth2Guild.js +28 -0
  273. package/src/structures/PartialGroupDMChannel.js +430 -0
  274. package/src/structures/PermissionOverwrites.js +196 -0
  275. package/src/structures/Presence.js +441 -0
  276. package/src/structures/ReactionCollector.js +229 -0
  277. package/src/structures/ReactionEmoji.js +31 -0
  278. package/src/structures/RichPresence.js +722 -0
  279. package/src/structures/Role.js +515 -0
  280. package/src/structures/SelectMenuInteraction.js +170 -0
  281. package/src/structures/Session.js +81 -0
  282. package/src/structures/StageChannel.js +104 -0
  283. package/src/structures/StageInstance.js +208 -0
  284. package/src/structures/Sticker.js +310 -0
  285. package/src/structures/StickerPack.js +95 -0
  286. package/src/structures/StoreChannel.js +56 -0
  287. package/src/structures/Team.js +167 -0
  288. package/src/structures/TeamMember.js +71 -0
  289. package/src/structures/TextChannel.js +33 -0
  290. package/src/structures/TextInputComponent.js +201 -0
  291. package/src/structures/ThreadChannel.js +626 -0
  292. package/src/structures/ThreadMember.js +105 -0
  293. package/src/structures/Typing.js +74 -0
  294. package/src/structures/User.js +697 -0
  295. package/src/structures/UserContextMenuInteraction.js +29 -0
  296. package/src/structures/VoiceChannel.js +110 -0
  297. package/src/structures/VoiceRegion.js +53 -0
  298. package/src/structures/VoiceState.js +306 -0
  299. package/src/structures/WebEmbed.js +401 -0
  300. package/src/structures/Webhook.js +461 -0
  301. package/src/structures/WelcomeChannel.js +60 -0
  302. package/src/structures/WelcomeScreen.js +48 -0
  303. package/src/structures/Widget.js +87 -0
  304. package/src/structures/WidgetMember.js +99 -0
  305. package/src/structures/interfaces/Application.js +190 -0
  306. package/src/structures/interfaces/Collector.js +300 -0
  307. package/src/structures/interfaces/InteractionResponses.js +313 -0
  308. package/src/structures/interfaces/TextBasedChannel.js +566 -0
  309. package/src/util/ActivityFlags.js +44 -0
  310. package/src/util/ApplicationFlags.js +74 -0
  311. package/src/util/BitField.js +170 -0
  312. package/src/util/ChannelFlags.js +45 -0
  313. package/src/util/Constants.js +1917 -0
  314. package/src/util/DataResolver.js +145 -0
  315. package/src/util/Formatters.js +214 -0
  316. package/src/util/GuildMemberFlags.js +43 -0
  317. package/src/util/Intents.js +74 -0
  318. package/src/util/LimitedCollection.js +131 -0
  319. package/src/util/MessageFlags.js +54 -0
  320. package/src/util/Options.js +360 -0
  321. package/src/util/Permissions.js +187 -0
  322. package/src/util/PremiumUsageFlags.js +31 -0
  323. package/src/util/PurchasedFlags.js +31 -0
  324. package/src/util/RemoteAuth.js +522 -0
  325. package/src/util/SnowflakeUtil.js +92 -0
  326. package/src/util/Sweepers.js +466 -0
  327. package/src/util/SystemChannelFlags.js +55 -0
  328. package/src/util/ThreadMemberFlags.js +30 -0
  329. package/src/util/UserFlags.js +104 -0
  330. package/src/util/Util.js +741 -0
  331. package/src/util/Voice.js +1456 -0
  332. package/src/util/arRPC/index.js +229 -0
  333. package/src/util/arRPC/process/detectable.json +1 -0
  334. package/src/util/arRPC/process/index.js +102 -0
  335. package/src/util/arRPC/process/native/index.js +5 -0
  336. package/src/util/arRPC/process/native/linux.js +37 -0
  337. package/src/util/arRPC/process/native/win32.js +25 -0
  338. package/src/util/arRPC/transports/ipc.js +281 -0
  339. package/src/util/arRPC/transports/websocket.js +128 -0
  340. package/typings/enums.d.ts +346 -0
  341. package/typings/index.d.ts +7725 -0
  342. package/typings/index.test-d.ts +0 -0
  343. package/typings/rawDataTypes.d.ts +283 -0
@@ -0,0 +1,724 @@
1
+ 'use strict';
2
+
3
+ const { Buffer } = require('node:buffer');
4
+ const { setTimeout } = require('node:timers');
5
+ const { Collection } = require('@discordjs/collection');
6
+ require('lodash.permutations');
7
+ const _ = require('lodash');
8
+ const CachedManager = require('./CachedManager');
9
+ const { Error, TypeError, RangeError } = require('../errors');
10
+ const BaseGuildVoiceChannel = require('../structures/BaseGuildVoiceChannel');
11
+ const { GuildMember } = require('../structures/GuildMember');
12
+ const { Role } = require('../structures/Role');
13
+ const { Events, Opcodes } = require('../util/Constants');
14
+ const { PartialTypes } = require('../util/Constants');
15
+ const DataResolver = require('../util/DataResolver');
16
+ const GuildMemberFlags = require('../util/GuildMemberFlags');
17
+ const SnowflakeUtil = require('../util/SnowflakeUtil');
18
+
19
+ /**
20
+ * Manages API methods for GuildMembers and stores their cache.
21
+ * @extends {CachedManager}
22
+ */
23
+ class GuildMemberManager extends CachedManager {
24
+ constructor(guild, iterable) {
25
+ super(guild.client, GuildMember, iterable);
26
+
27
+ /**
28
+ * The guild this manager belongs to
29
+ * @type {Guild}
30
+ */
31
+ this.guild = guild;
32
+ }
33
+
34
+ /**
35
+ * The cache of this Manager
36
+ * @type {Collection<Snowflake, GuildMember>}
37
+ * @name GuildMemberManager#cache
38
+ */
39
+
40
+ _add(data, cache = true) {
41
+ return super._add(data, cache, { id: data.user.id, extras: [this.guild] });
42
+ }
43
+
44
+ /**
45
+ * Data that resolves to give a GuildMember object. This can be:
46
+ * * A GuildMember object
47
+ * * A User resolvable
48
+ * @typedef {GuildMember|UserResolvable} GuildMemberResolvable
49
+ */
50
+
51
+ /**
52
+ * Resolves a {@link GuildMemberResolvable} to a {@link GuildMember} object.
53
+ * @param {GuildMemberResolvable} member The user that is part of the guild
54
+ * @returns {?GuildMember}
55
+ */
56
+ resolve(member) {
57
+ const memberResolvable = super.resolve(member);
58
+ if (memberResolvable) return memberResolvable;
59
+ const userResolvable = this.client.users.resolveId(member);
60
+ if (userResolvable) return super.resolve(userResolvable);
61
+ return null;
62
+ }
63
+
64
+ /**
65
+ * Resolves a {@link GuildMemberResolvable} to a member id.
66
+ * @param {GuildMemberResolvable} member The user that is part of the guild
67
+ * @returns {?Snowflake}
68
+ */
69
+ resolveId(member) {
70
+ const memberResolvable = super.resolveId(member);
71
+ if (memberResolvable) return memberResolvable;
72
+ const userResolvable = this.client.users.resolveId(member);
73
+ return this.cache.has(userResolvable) ? userResolvable : null;
74
+ }
75
+
76
+ /**
77
+ * Options used to add a user to a guild using OAuth2.
78
+ * @typedef {Object} AddGuildMemberOptions
79
+ * @property {string} accessToken An OAuth2 access token for the user with the `guilds.join` scope granted to the
80
+ * bot's application
81
+ * @property {string} [nick] The nickname to give to the member (requires `MANAGE_NICKNAMES`)
82
+ * @property {Collection<Snowflake, Role>|RoleResolvable[]} [roles] The roles to add to the member
83
+ * (requires `MANAGE_ROLES`)
84
+ * @property {boolean} [mute] Whether the member should be muted (requires `MUTE_MEMBERS`)
85
+ * @property {boolean} [deaf] Whether the member should be deafened (requires `DEAFEN_MEMBERS`)
86
+ * @property {boolean} [force] Whether to skip the cache check and call the API directly
87
+ * @property {boolean} [fetchWhenExisting=true] Whether to fetch the user if not cached and already a member
88
+ */
89
+
90
+ /**
91
+ * Adds a user to the guild using OAuth2. Requires the `CREATE_INSTANT_INVITE` permission.
92
+ * @param {UserResolvable} user The user to add to the guild
93
+ * @param {AddGuildMemberOptions} options Options for adding the user to the guild
94
+ * @returns {Promise<GuildMember|null>}
95
+ */
96
+ async add(user, options) {
97
+ const userId = this.client.users.resolveId(user);
98
+ if (!userId) throw new TypeError('INVALID_TYPE', 'user', 'UserResolvable');
99
+ if (!options.force) {
100
+ const cachedUser = this.cache.get(userId);
101
+ if (cachedUser) return cachedUser;
102
+ }
103
+ const resolvedOptions = {
104
+ access_token: options.accessToken,
105
+ nick: options.nick,
106
+ mute: options.mute,
107
+ deaf: options.deaf,
108
+ };
109
+ if (options.roles) {
110
+ if (!Array.isArray(options.roles) && !(options.roles instanceof Collection)) {
111
+ throw new TypeError('INVALID_TYPE', 'options.roles', 'Array or Collection of Roles or Snowflakes', true);
112
+ }
113
+ const resolvedRoles = [];
114
+ for (const role of options.roles.values()) {
115
+ const resolvedRole = this.guild.roles.resolveId(role);
116
+ if (!resolvedRole) throw new TypeError('INVALID_ELEMENT', 'Array or Collection', 'options.roles', role);
117
+ resolvedRoles.push(resolvedRole);
118
+ }
119
+ resolvedOptions.roles = resolvedRoles;
120
+ }
121
+ const data = await this.client.api.guilds(this.guild.id).members(userId).put({ data: resolvedOptions });
122
+ // Data is an empty buffer if the member is already part of the guild.
123
+ return data instanceof Buffer ? (options.fetchWhenExisting === false ? null : this.fetch(userId)) : this._add(data);
124
+ }
125
+
126
+ /**
127
+ * The client user as a GuildMember of this guild
128
+ * @type {?GuildMember}
129
+ * @readonly
130
+ */
131
+ get me() {
132
+ return (
133
+ this.resolve(this.client.user.id) ??
134
+ (this.client.options.partials.includes(PartialTypes.GUILD_MEMBER)
135
+ ? this._add({ user: { id: this.client.user.id } }, true)
136
+ : null)
137
+ );
138
+ }
139
+
140
+ /**
141
+ * Options used to fetch a single member from a guild.
142
+ * @typedef {BaseFetchOptions} FetchMemberOptions
143
+ * @property {UserResolvable} user The user to fetch
144
+ */
145
+
146
+ /**
147
+ * Options used to fetch multiple members from a guild.
148
+ * @typedef {Object} FetchMembersOptions
149
+ * @property {UserResolvable|UserResolvable[]} user The user(s) to fetch
150
+ * @property {?string} query Limit fetch to members with similar usernames
151
+ * @property {number} [limit=0] Maximum number of members to request
152
+ * @property {boolean} [withPresences=false] Whether or not to include the presences
153
+ * @property {number} [time=120e3] Timeout for receipt of members
154
+ * @property {?string} nonce Nonce for this request (32 characters max - default to base 16 now timestamp)
155
+ * @property {boolean} [force=false] Whether to skip the cache check and request the API
156
+ */
157
+
158
+ /**
159
+ * Fetches member(s) from Discord, even if they're offline.
160
+ * @param {UserResolvable|FetchMemberOptions|FetchMembersOptions} [options] If a UserResolvable, the user to fetch.
161
+ * If undefined, fetches all members.
162
+ * If a query, it limits the results to users with similar usernames.
163
+ * @returns {Promise<GuildMember|Collection<Snowflake, GuildMember>>}
164
+ * @example
165
+ * // Fetch all members from a guild
166
+ * guild.members.fetch()
167
+ * .then(console.log)
168
+ * .catch(console.error);
169
+ * @example
170
+ * // Fetch a single member
171
+ * guild.members.fetch('66564597481480192')
172
+ * .then(console.log)
173
+ * .catch(console.error);
174
+ * @example
175
+ * // Fetch a single member without checking cache
176
+ * guild.members.fetch({ user, force: true })
177
+ * .then(console.log)
178
+ * .catch(console.error)
179
+ * @example
180
+ * // Fetch a single member without caching
181
+ * guild.members.fetch({ user, cache: false })
182
+ * .then(console.log)
183
+ * .catch(console.error);
184
+ * @example
185
+ * // Fetch by an array of users including their presences
186
+ * guild.members.fetch({ user: ['66564597481480192', '191615925336670208'], withPresences: true })
187
+ * .then(console.log)
188
+ * .catch(console.error);
189
+ * @example
190
+ * // Fetch by query
191
+ * guild.members.fetch({ query: 'hydra', limit: 1 })
192
+ * .then(console.log)
193
+ * .catch(console.error);
194
+ * @see {@link https://github.com/aiko-chan-ai/discord.js-selfbot-v13/blob/main/Document/FetchGuildMember.md}
195
+ */
196
+ fetch(options) {
197
+ if (!options || (typeof options === 'object' && !('user' in options) && !('query' in options))) {
198
+ if (
199
+ this.guild.members.me.permissions.has('KICK_MEMBERS') ||
200
+ this.guild.members.me.permissions.has('BAN_MEMBERS') ||
201
+ this.guild.members.me.permissions.has('MANAGE_ROLES')
202
+ ) {
203
+ return this._fetchMany();
204
+ } else {
205
+ return this.fetchBruteforce({
206
+ delay: 50,
207
+ skipWarn: true,
208
+ depth: 1,
209
+ });
210
+ }
211
+ }
212
+ const user = this.client.users.resolveId(options);
213
+ if (user) return this._fetchSingle({ user, cache: true });
214
+ if (options.user) {
215
+ if (Array.isArray(options.user)) {
216
+ options.user = options.user.map(u => this.client.users.resolveId(u));
217
+ return this._fetchMany(options);
218
+ } else {
219
+ options.user = this.client.users.resolveId(options.user);
220
+ }
221
+ if (!options.limit && !options.withPresences) return this._fetchSingle(options);
222
+ }
223
+ return this._fetchMany(options);
224
+ }
225
+
226
+ /**
227
+ * Fetches the client user as a GuildMember of the guild.
228
+ * @param {BaseFetchOptions} [options] The options for fetching the member
229
+ * @returns {Promise<GuildMember>}
230
+ */
231
+ fetchMe(options) {
232
+ return this.fetch({ ...options, user: this.client.user.id });
233
+ }
234
+
235
+ /**
236
+ * Options used for searching guild members.
237
+ * @typedef {Object} GuildSearchMembersOptions
238
+ * @property {string} query Filter members whose username or nickname start with this query
239
+ * @property {number} [limit=1] Maximum number of members to search
240
+ * @property {boolean} [cache=true] Whether or not to cache the fetched member(s)
241
+ */
242
+
243
+ /**
244
+ * Searches for members in the guild based on a query.
245
+ * @param {GuildSearchMembersOptions} options Options for searching members
246
+ * @returns {Promise<Collection<Snowflake, GuildMember>>}
247
+ */
248
+ async search({ query, limit = 1, cache = true } = {}) {
249
+ const data = await this.client.api.guilds(this.guild.id).members.search.get({ query: { query, limit } });
250
+ return data.reduce((col, member) => col.set(member.user.id, this._add(member, cache)), new Collection());
251
+ }
252
+
253
+ /**
254
+ * Options used for listing guild members.
255
+ * @typedef {Object} GuildListMembersOptions
256
+ * @property {Snowflake} [after] Limit fetching members to those with an id greater than the supplied id
257
+ * @property {number} [limit=1] Maximum number of members to list
258
+ * @property {boolean} [cache=true] Whether or not to cache the fetched member(s)
259
+ */
260
+
261
+ /**
262
+ * Lists up to 1000 members of the guild.
263
+ * @param {GuildListMembersOptions} [options] Options for listing members
264
+ * @returns {Promise<Collection<Snowflake, GuildMember>>}
265
+ */
266
+ async list({ after, limit = 1, cache = true } = {}) {
267
+ const data = await this.client.api.guilds(this.guild.id).members.get({ query: { after, limit } });
268
+ return data.reduce((col, member) => col.set(member.user.id, this._add(member, cache)), new Collection());
269
+ }
270
+
271
+ /**
272
+ * The data for editing a guild member.
273
+ * @typedef {Object} GuildMemberEditData
274
+ * @property {?string} [nick] The nickname to set for the member
275
+ * @property {Collection<Snowflake, Role>|RoleResolvable[]} [roles] The roles or role ids to apply
276
+ * @property {boolean} [mute] Whether or not the member should be muted
277
+ * @property {boolean} [deaf] Whether or not the member should be deafened
278
+ * @property {GuildVoiceChannelResolvable|null} [channel] Channel to move the member to
279
+ * (if they are connected to voice), or `null` if you want to disconnect them from voice
280
+ * @property {DateResolvable|null} [communicationDisabledUntil] The date or timestamp
281
+ * for the member's communication to be disabled until. Provide `null` to enable communication again.
282
+ * @property {GuildMemberFlagsResolvable} [flags] The flags to set for the member
283
+ * @property {?(BufferResolvable|Base64Resolvable)} [avatar] The new guild avatar
284
+ * @property {?(BufferResolvable|Base64Resolvable)} [banner] The new guild banner
285
+ * @property {?string} [bio] The new guild about me
286
+ */
287
+
288
+ /**
289
+ * Edits a member of the guild.
290
+ * <info>The user must be a member of the guild</info>
291
+ * @param {UserResolvable} user The member to edit
292
+ * @param {GuildMemberEditData} data The data to edit the member with
293
+ * @param {string} [reason] Reason for editing this user
294
+ * @returns {Promise<GuildMember>}
295
+ */
296
+ async edit(user, data, reason) {
297
+ const id = this.client.users.resolveId(user);
298
+ if (!id) throw new TypeError('INVALID_TYPE', 'user', 'UserResolvable');
299
+
300
+ // Clone the data object for immutability
301
+ const _data = { ...data };
302
+ if (_data.channel) {
303
+ _data.channel = this.guild.channels.resolve(_data.channel);
304
+ if (!(_data.channel instanceof BaseGuildVoiceChannel)) {
305
+ throw new Error('GUILD_VOICE_CHANNEL_RESOLVE');
306
+ }
307
+ _data.channel_id = _data.channel.id;
308
+ _data.channel = undefined;
309
+ } else if (_data.channel === null) {
310
+ _data.channel_id = null;
311
+ _data.channel = undefined;
312
+ }
313
+ _data.roles &&= _data.roles.map(role => (role instanceof Role ? role.id : role));
314
+
315
+ _data.communication_disabled_until =
316
+ _data.communicationDisabledUntil && new Date(_data.communicationDisabledUntil).toISOString();
317
+
318
+ _data.flags = _data.flags && GuildMemberFlags.resolve(_data.flags);
319
+
320
+ // Avatar, banner, bio
321
+ if (typeof _data.avatar !== 'undefined') {
322
+ _data.avatar = await DataResolver.resolveImage(_data.avatar);
323
+ }
324
+ if (typeof _data.banner !== 'undefined') {
325
+ _data.banner = await DataResolver.resolveImage(_data.banner);
326
+ }
327
+
328
+ let endpoint = this.client.api.guilds(this.guild.id);
329
+ if (id === this.client.user.id) {
330
+ const keys = Object.keys(data);
331
+ if (keys.length === 1 && ['nick', 'avatar', 'banner', 'bio'].includes(keys[0])) {
332
+ endpoint = endpoint.members('@me');
333
+ } else {
334
+ endpoint = endpoint.members(id);
335
+ }
336
+ } else {
337
+ endpoint = endpoint.members(id);
338
+ }
339
+ const d = await endpoint.patch({ data: _data, reason });
340
+
341
+ const clone = this.cache.get(id)?._clone();
342
+ clone?._patch(d);
343
+ return clone ?? this._add(d, false);
344
+ }
345
+
346
+ /**
347
+ * Options used for pruning guild members.
348
+ * <info>It's recommended to set {@link GuildPruneMembersOptions#count options.count}
349
+ * to `false` for large guilds.</info>
350
+ * @typedef {Object} GuildPruneMembersOptions
351
+ * @property {number} [days=7] Number of days of inactivity required to kick
352
+ * @property {boolean} [dry=false] Get the number of users that will be kicked, without actually kicking them
353
+ * @property {boolean} [count=true] Whether or not to return the number of users that have been kicked.
354
+ * @property {RoleResolvable[]} [roles] Array of roles to bypass the "...and no roles" constraint when pruning
355
+ * @property {string} [reason] Reason for this prune
356
+ */
357
+
358
+ /**
359
+ * Prunes members from the guild based on how long they have been inactive.
360
+ * @param {GuildPruneMembersOptions} [options] Options for pruning
361
+ * @returns {Promise<number|null>} The number of members that were/will be kicked
362
+ * @example
363
+ * // See how many members will be pruned
364
+ * guild.members.prune({ dry: true })
365
+ * .then(pruned => console.log(`This will prune ${pruned} people!`))
366
+ * .catch(console.error);
367
+ * @example
368
+ * // Actually prune the members
369
+ * guild.members.prune({ days: 1, reason: 'too many people!' })
370
+ * .then(pruned => console.log(`I just pruned ${pruned} people!`))
371
+ * .catch(console.error);
372
+ * @example
373
+ * // Include members with a specified role
374
+ * guild.members.prune({ days: 7, roles: ['657259391652855808'] })
375
+ * .then(pruned => console.log(`I just pruned ${pruned} people!`))
376
+ * .catch(console.error);
377
+ */
378
+ async prune({ days = 7, dry = false, count: compute_prune_count = true, roles = [], reason } = {}) {
379
+ if (typeof days !== 'number') throw new TypeError('PRUNE_DAYS_TYPE');
380
+
381
+ const query = { days };
382
+ const resolvedRoles = [];
383
+
384
+ for (const role of roles) {
385
+ const resolvedRole = this.guild.roles.resolveId(role);
386
+ if (!resolvedRole) {
387
+ throw new TypeError('INVALID_ELEMENT', 'Array', 'options.roles', role);
388
+ }
389
+ resolvedRoles.push(resolvedRole);
390
+ }
391
+
392
+ if (resolvedRoles.length) {
393
+ query.include_roles = dry ? resolvedRoles.join(',') : resolvedRoles;
394
+ }
395
+
396
+ const endpoint = this.client.api.guilds(this.guild.id).prune;
397
+
398
+ const { pruned } = await (dry
399
+ ? endpoint.get({ query, reason })
400
+ : endpoint.post({ data: { ...query, compute_prune_count }, reason }));
401
+
402
+ return pruned;
403
+ }
404
+
405
+ /**
406
+ * Kicks a user from the guild.
407
+ * <info>The user must be a member of the guild</info>
408
+ * @param {UserResolvable} user The member to kick
409
+ * @param {string} [reason] Reason for kicking
410
+ * @returns {Promise<GuildMember|User|Snowflake>} Result object will be resolved as specifically as possible.
411
+ * If the GuildMember cannot be resolved, the User will instead be attempted to be resolved. If that also cannot
412
+ * be resolved, the user's id will be the result.
413
+ * @example
414
+ * // Kick a user by id (or with a user/guild member object)
415
+ * guild.members.kick('84484653687267328')
416
+ * .then(kickInfo => console.log(`Kicked ${kickInfo.user?.tag ?? kickInfo.tag ?? kickInfo}`))
417
+ * .catch(console.error);
418
+ */
419
+ async kick(user, reason) {
420
+ const id = this.client.users.resolveId(user);
421
+ if (!id) return Promise.reject(new TypeError('INVALID_TYPE', 'user', 'UserResolvable'));
422
+
423
+ await this.client.api.guilds(this.guild.id).members(id).delete({ reason });
424
+
425
+ return this.resolve(user) ?? this.client.users.resolve(user) ?? id;
426
+ }
427
+
428
+ /**
429
+ * Bans a user from the guild.
430
+ * @param {UserResolvable} user The user to ban
431
+ * @param {BanOptions} [options] Options for the ban
432
+ * @returns {Promise<GuildMember|User|Snowflake>} Result object will be resolved as specifically as possible.
433
+ * If the GuildMember cannot be resolved, the User will instead be attempted to be resolved. If that also cannot
434
+ * be resolved, the user id will be the result.
435
+ * Internally calls the GuildBanManager#create method.
436
+ * @example
437
+ * // Ban a user by id (or with a user/guild member object)
438
+ * guild.members.ban('84484653687267328')
439
+ * .then(banInfo => console.log(`Banned ${banInfo.user?.tag ?? banInfo.tag ?? banInfo}`))
440
+ * .catch(console.error);
441
+ */
442
+ ban(user, options) {
443
+ return this.guild.bans.create(user, options);
444
+ }
445
+
446
+ /**
447
+ * Unbans a user from the guild. Internally calls the {@link GuildBanManager#remove} method.
448
+ * @param {UserResolvable} user The user to unban
449
+ * @param {string} [reason] Reason for unbanning user
450
+ * @returns {Promise<?User>} The user that was unbanned
451
+ * @example
452
+ * // Unban a user by id (or with a user/guild member object)
453
+ * guild.members.unban('84484653687267328')
454
+ * .then(user => console.log(`Unbanned ${user.username} from ${guild.name}`))
455
+ * .catch(console.error);
456
+ */
457
+ unban(user, reason) {
458
+ return this.guild.bans.remove(user, reason);
459
+ }
460
+
461
+ async _fetchSingle({ user, cache, force = false }) {
462
+ if (!force) {
463
+ const existing = this.cache.get(user);
464
+ if (existing && !existing.partial) return existing;
465
+ }
466
+
467
+ const data = await this.client.api.guilds(this.guild.id).members(user).get();
468
+ return this._add(data, cache);
469
+ }
470
+
471
+ /**
472
+ * Options used to fetch multiple members from a guild.
473
+ * @typedef {Object} BruteforceOptions
474
+ * @property {number} [limit=100] Maximum number of members per request
475
+ * @property {number} [delay=500] Timeout for new requests in ms
476
+ * @property {number} [depth=1] Permutations length
477
+ */
478
+
479
+ /**
480
+ * Fetches multiple members from the guild.
481
+ * @param {BruteforceOptions} options Options for the bruteforce
482
+ * @returns {Collection<Snowflake, GuildMember>} (All) members in the guild
483
+ * @see https://github.com/aiko-chan-ai/discord.js-selfbot-v13/blob/main/Document/FetchGuildMember.md
484
+ * @example
485
+ * guild.members.fetchBruteforce()
486
+ * .then(members => console.log(`Fetched ${members.size} members`))
487
+ * .catch(console.error);
488
+ */
489
+ fetchBruteforce(options = {}) {
490
+ const defaultQuery = 'abcdefghijklmnopqrstuvwxyz0123456789!"#$%&\'()*+,-./:;<=>?@[]^_`{|}~ ';
491
+ let dictionary;
492
+ let limit = 100;
493
+ let delay = 500;
494
+ let depth = 1;
495
+ if (options?.limit) limit = options?.limit;
496
+ if (options?.delay) delay = options?.delay;
497
+ if (options?.depth) depth = options?.depth;
498
+ if (typeof limit !== 'number') throw new TypeError('INVALID_TYPE', 'limit', 'Number');
499
+ if (limit < 1 || limit > 100) throw new RangeError('INVALID_RANGE_QUERY_MEMBER');
500
+ if (typeof delay !== 'number') throw new TypeError('INVALID_TYPE', 'delay', 'Number');
501
+ if (typeof depth !== 'number') throw new TypeError('INVALID_TYPE', 'depth', 'Number');
502
+ if (depth < 1) throw new RangeError('INVALID_RANGE_QUERY_MEMBER');
503
+ if (depth > 2) {
504
+ console.warn(`[WARNING] GuildMemberManager#fetchBruteforce: depth greater than 2, can lead to very slow speeds`);
505
+ }
506
+ if (delay < 500 && !options?.skipWarn) {
507
+ console.warn(
508
+ `[WARNING] GuildMemberManager#fetchBruteforce: delay is less than 500ms, this may cause rate limits.`,
509
+ );
510
+ }
511
+ let skipValues = [];
512
+ // eslint-disable-next-line no-async-promise-executor
513
+ return new Promise(async (resolve, reject) => {
514
+ for (let i = 1; i <= depth; i++) {
515
+ dictionary = _(defaultQuery)
516
+ .permutations(i)
517
+ .map(v => _.join(v, ''))
518
+ .value();
519
+ for (const query of dictionary) {
520
+ if (this.guild.members.cache.size >= this.guild.memberCount) break;
521
+ this.client.emit(
522
+ 'debug',
523
+ `[INFO] GuildMemberManager#fetchBruteforce: Querying ${query}, Skip: [${skipValues.join(', ')}]`,
524
+ );
525
+ if (skipValues.some(v => query.startsWith(v))) continue;
526
+ await this._fetchMany({ query, limit })
527
+ .then(members => {
528
+ if (members.size === 0) skipValues.push(query);
529
+ })
530
+ .catch(reject);
531
+ await this.guild.client.sleep(delay);
532
+ }
533
+ }
534
+ resolve(this.guild.members.cache);
535
+ });
536
+ }
537
+
538
+ /**
539
+ * Fetches multiple members from the guild in the channel.
540
+ * @param {GuildTextChannelResolvable} channel The channel to get members from (Members has VIEW_CHANNEL permission)
541
+ * @param {number} [offset=0] Start index of the members to get
542
+ * @param {boolean} [double=false] Whether to use double range
543
+ * @param {number} [retryMax=3] Number of retries
544
+ * @param {number} [time=10e3] Timeout for receipt of members
545
+ * @returns {Collection<Snowflake, GuildMember>} Members in the guild
546
+ * @see {@link https://github.com/aiko-chan-ai/discord.js-selfbot-v13/blob/main/Document/FetchGuildMember.md}
547
+ * @example
548
+ * const guild = client.guilds.cache.get('id');
549
+ * const channel = guild.channels.cache.get('id');
550
+ * // Overlap (slow)
551
+ * for (let index = 0; index <= guild.memberCount; index += 100) {
552
+ * await guild.members.fetchMemberList(channel, index, index !== 100).catch(() => {});
553
+ * await client.sleep(500);
554
+ * }
555
+ * // Non-overlap (fast)
556
+ * for (let index = 0; index <= guild.memberCount; index += 200) {
557
+ * await guild.members.fetchMemberList(channel, index == 0 ? 100 : index, index !== 100).catch(() => {});
558
+ * await client.sleep(500);
559
+ * }
560
+ * console.log(guild.members.cache.size); // will print the number of members in the guild
561
+ */
562
+ fetchMemberList(channel, offset = 0, double = false, retryMax = 3, time = 10_000) {
563
+ const channel_ = this.guild.channels.resolve(channel);
564
+ if (!channel_?.isText()) throw new TypeError('INVALID_TYPE', 'channel', 'GuildTextChannelResolvable');
565
+ if (typeof offset !== 'number') throw new TypeError('INVALID_TYPE', 'offset', 'Number');
566
+ if (typeof time !== 'number') throw new TypeError('INVALID_TYPE', 'time', 'Number');
567
+ if (typeof retryMax !== 'number') throw new TypeError('INVALID_TYPE', 'retryMax', 'Number');
568
+ if (retryMax < 1) throw new RangeError('INVALID_RANGE_RETRY');
569
+ if (typeof double !== 'boolean') throw new TypeError('INVALID_TYPE', 'double', 'Boolean');
570
+ // TODO: if (this.guild.large) throw new Error('GUILD_IS_LARGE');
571
+ return new Promise((resolve, reject) => {
572
+ const default_ = [[0, 99]];
573
+ const fetchedMembers = new Collection();
574
+ if (offset > 99) {
575
+ // eslint-disable-next-line no-unused-expressions
576
+ double
577
+ ? default_.push([offset, offset + 99], [offset + 100, offset + 199])
578
+ : default_.push([offset, offset + 99]);
579
+ }
580
+ let retry = 0;
581
+ const handler = (members, guild, type, raw) => {
582
+ timeout.refresh();
583
+ if (guild.id !== this.guild.id) return;
584
+ if (type == 'INVALIDATE' && offset > 100) {
585
+ if (retry < retryMax) {
586
+ this.guild.shard.send({
587
+ op: Opcodes.GUILD_SUBSCRIPTIONS,
588
+ d: {
589
+ guild_id: this.guild.id,
590
+ typing: true,
591
+ threads: true,
592
+ activities: true,
593
+ channels: {
594
+ [channel_.id]: default_,
595
+ },
596
+ thread_member_lists: [],
597
+ members: [],
598
+ },
599
+ });
600
+ retry++;
601
+ } else {
602
+ clearTimeout(timeout);
603
+ this.client.removeListener(Events.GUILD_MEMBER_LIST_UPDATE, handler);
604
+ this.client.decrementMaxListeners();
605
+ reject(new Error('INVALIDATE_MEMBER', raw.ops[0].range));
606
+ }
607
+ } else {
608
+ for (const member of members.values()) {
609
+ fetchedMembers.set(member.id, member);
610
+ }
611
+ clearTimeout(timeout);
612
+ this.client.removeListener(Events.GUILD_MEMBER_LIST_UPDATE, handler);
613
+ this.client.decrementMaxListeners();
614
+ resolve(fetchedMembers);
615
+ }
616
+ };
617
+ const timeout = setTimeout(() => {
618
+ this.client.removeListener(Events.GUILD_MEMBER_LIST_UPDATE, handler);
619
+ this.client.decrementMaxListeners();
620
+ reject(new Error('GUILD_MEMBERS_TIMEOUT'));
621
+ }, time).unref();
622
+ this.client.incrementMaxListeners();
623
+ this.client.on(Events.GUILD_MEMBER_LIST_UPDATE, handler);
624
+ this.guild.shard.send({
625
+ op: Opcodes.GUILD_SUBSCRIPTIONS,
626
+ d: {
627
+ guild_id: this.guild.id,
628
+ typing: true,
629
+ threads: true,
630
+ activities: true,
631
+ channels: {
632
+ [channel_.id]: default_,
633
+ },
634
+ thread_member_lists: [],
635
+ members: [],
636
+ },
637
+ });
638
+ });
639
+ }
640
+
641
+ /**
642
+ * Adds a role to a member.
643
+ * @param {GuildMemberResolvable} user The user to add the role from
644
+ * @param {RoleResolvable} role The role to add
645
+ * @param {string} [reason] Reason for adding the role
646
+ * @returns {Promise<GuildMember|User|Snowflake>}
647
+ */
648
+ async addRole(user, role, reason) {
649
+ const userId = this.guild.members.resolveId(user);
650
+ const roleId = this.guild.roles.resolveId(role);
651
+
652
+ await this.client.api.guilds(this.guild.id).members(userId).roles(roleId).put({ reason });
653
+
654
+ return this.resolve(user) ?? this.client.users.resolve(user) ?? userId;
655
+ }
656
+
657
+ /**
658
+ * Removes a role from a member.
659
+ * @param {UserResolvable} user The user to remove the role from
660
+ * @param {RoleResolvable} role The role to remove
661
+ * @param {string} [reason] Reason for removing the role
662
+ * @returns {Promise<GuildMember|User|Snowflake>}
663
+ */
664
+ async removeRole(user, role, reason) {
665
+ const userId = this.guild.members.resolveId(user);
666
+ const roleId = this.guild.roles.resolveId(role);
667
+
668
+ await this.client.api.guilds(this.guild.id).members(userId).roles(roleId).delete({ reason });
669
+
670
+ return this.resolve(user) ?? this.client.users.resolve(user) ?? userId;
671
+ }
672
+
673
+ _fetchMany({
674
+ limit = 0,
675
+ withPresences: presences = true,
676
+ user: user_ids,
677
+ query,
678
+ time = 120e3,
679
+ nonce = SnowflakeUtil.generate(),
680
+ } = {}) {
681
+ return new Promise((resolve, reject) => {
682
+ if (!query && !user_ids) query = '';
683
+ if (nonce.length > 32) throw new RangeError('MEMBER_FETCH_NONCE_LENGTH');
684
+ this.guild.shard.send({
685
+ op: Opcodes.REQUEST_GUILD_MEMBERS,
686
+ d: {
687
+ guild_id: this.guild.id,
688
+ presences,
689
+ user_ids,
690
+ query,
691
+ nonce,
692
+ limit,
693
+ },
694
+ });
695
+ const fetchedMembers = new Collection();
696
+ let i = 0;
697
+ const handler = (members, _, chunk) => {
698
+ timeout.refresh();
699
+ if (chunk.nonce !== nonce) return;
700
+ i++;
701
+ for (const member of members.values()) {
702
+ fetchedMembers.set(member.id, member);
703
+ }
704
+ if (members.size < 1_000 || (limit && fetchedMembers.size >= limit) || i === chunk.count) {
705
+ clearTimeout(timeout);
706
+ this.client.removeListener(Events.GUILD_MEMBERS_CHUNK, handler);
707
+ this.client.decrementMaxListeners();
708
+ let fetched = fetchedMembers;
709
+ if (user_ids && !Array.isArray(user_ids) && fetched.size) fetched = fetched.first();
710
+ resolve(fetched);
711
+ }
712
+ };
713
+ const timeout = setTimeout(() => {
714
+ this.client.removeListener(Events.GUILD_MEMBERS_CHUNK, handler);
715
+ this.client.decrementMaxListeners();
716
+ reject(new Error('GUILD_MEMBERS_TIMEOUT'));
717
+ }, time).unref();
718
+ this.client.incrementMaxListeners();
719
+ this.client.on(Events.GUILD_MEMBERS_CHUNK, handler);
720
+ });
721
+ }
722
+ }
723
+
724
+ module.exports = GuildMemberManager;