Advertisement
Guest User

Untitled

a guest
Jun 22nd, 2018
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 38.36 KB | None | 0 0
  1. const querystring = require('querystring');
  2. const long = require('long');
  3. const Permissions = require('../../util/Permissions');
  4. const Constants = require('../../util/Constants');
  5. const Endpoints = Constants.Endpoints;
  6. const Collection = require('../../util/Collection');
  7. const Util = require('../../util/Util');
  8.  
  9. const User = require('../../structures/User');
  10. const GuildMember = require('../../structures/GuildMember');
  11. const Message = require('../../structures/Message');
  12. const Role = require('../../structures/Role');
  13. const Invite = require('../../structures/Invite');
  14. const Webhook = require('../../structures/Webhook');
  15. const UserProfile = require('../../structures/UserProfile');
  16. const OAuth2Application = require('../../structures/OAuth2Application');
  17. const Channel = require('../../structures/Channel');
  18. const GroupDMChannel = require('../../structures/GroupDMChannel');
  19. const Guild = require('../../structures/Guild');
  20. const VoiceRegion = require('../../structures/VoiceRegion');
  21. const GuildAuditLogs = require('../../structures/GuildAuditLogs');
  22.  
  23. const translate = require('google-translate-api');
  24. const translatecache = new Map();
  25. /**
  26. * Traduz uma String para inglês se ela não estiver no cache.
  27. * @param {String} string
  28. */
  29. const plstranslate = string => {
  30. return new Promise((resolve, rej) => {
  31. if(translatecache.has(string)) {
  32. resolve(translatecache.get(string));
  33. return;
  34. }
  35.  
  36. translate(string, { to: "en" }).then(res => {
  37. let text = res.text;
  38. translatecache.set(string, text);
  39. resolve(text);
  40. }).catch(err => {
  41. rej(err);
  42. });
  43. });
  44. }
  45.  
  46. const DISABLED = null;
  47.  
  48. class RESTMethods {
  49. constructor(restManager) {
  50. this.rest = restManager;
  51. this.client = restManager.client;
  52. this._ackToken = null;
  53. }
  54.  
  55. login(token = this.client.token) {
  56. return new Promise((resolve, reject) => {
  57. if (typeof token !== 'string') throw new Error(Constants.Errors.INVALID_TOKEN);
  58. token = token.replace(/^Bot\s*/i, '');
  59. this.client.manager.connectToWebSocket(token, resolve, reject);
  60. });
  61. }
  62.  
  63. logout() {
  64. return this.rest.makeRequest('post', Endpoints.logout, true, {});
  65. }
  66.  
  67. getGateway(bot = false) {
  68. return this.rest.makeRequest('get', bot ? Endpoints.gateway.bot : Endpoints.gateway, true);
  69. }
  70.  
  71. fetchVoiceRegions(guildID) {
  72. let endpoint;
  73. if (guildID) endpoint = Endpoints.Guild(guildID).voiceRegions;
  74. else endpoint = Endpoints.voiceRegions;
  75. return this.rest.makeRequest('get', endpoint, true).then(res => {
  76. const regions = new Collection();
  77. for (const region of res) regions.set(region.id, new VoiceRegion(region));
  78. return regions;
  79. });
  80. }
  81.  
  82. sendMessage(channel, content, { tts, nonce, embed, disableEveryone, split, code, reply, english } = {}, files = null) {
  83. return new Promise(async (resolve, reject) => { // eslint-disable-line complexity
  84. if (typeof content !== 'undefined') content = this.client.resolver.resolveString(content);
  85.  
  86. // The nonce has to be a uint64 :<
  87. if (typeof nonce !== 'undefined') {
  88. nonce = parseInt(nonce);
  89. if (isNaN(nonce) || nonce < 0) throw new RangeError('Message nonce must fit in an unsigned 64-bit integer.');
  90. }
  91.  
  92. if (content) {
  93. if (split && typeof split !== 'object') split = {};
  94.  
  95. // Wrap everything in a code block
  96. if (typeof code !== 'undefined' && (typeof code !== 'boolean' || code === true)) {
  97. content = Util.escapeMarkdown(this.client.resolver.resolveString(content), true);
  98. content = `\`\`\`${typeof code !== 'boolean' ? code || '' : ''}\n${content}\n\`\`\``;
  99. if (split) {
  100. split.prepend = `\`\`\`${typeof code !== 'boolean' ? code || '' : ''}\n`;
  101. split.append = '\n```';
  102. }
  103. }
  104.  
  105. // Add zero-width spaces to @everyone/@here
  106. if (disableEveryone || (typeof disableEveryone === 'undefined' && this.client.options.disableEveryone)) {
  107. content = content.replace(/@(everyone|here)/g, '@\u200b$1');
  108. }
  109.  
  110. // Add the reply prefix
  111. if (DISABLED && reply && !(channel instanceof User || channel instanceof GuildMember) && channel.type !== 'dm') {
  112. const id = this.client.resolver.resolveUserID(reply);
  113. const mention = `<@${reply instanceof GuildMember && reply.nickname ? '!' : ''}${id}>`;
  114. content = `${mention}${content ? `, ${content}` : ''}`;
  115. if (split) split.prepend = `${mention}, ${split.prepend || ''}`;
  116. }
  117.  
  118. // Split the content
  119. if (split) content = Util.splitMessage(content, split);
  120. } else if (reply && !(channel instanceof User || channel instanceof GuildMember) && channel.type !== 'dm') {
  121. const id = this.client.resolver.resolveUserID(reply);
  122. content = `<@${reply instanceof GuildMember && reply.nickname ? '!' : ''}${id}>`;
  123. }
  124.  
  125. let shouldTranslate = english ? true : false;
  126.  
  127. if(shouldTranslate) {
  128.  
  129. if(content) content = await plstranslate(content);
  130.  
  131. if(embed) {
  132. if(embed.description) {
  133. let r = await plstranslate(embed.description);
  134. embed.description = r.replace(/(?:\]\ \()/g, "](");
  135. }
  136.  
  137. let f = [];
  138.  
  139. for(let i = 0; i < embed.fields.length; i++) {
  140. let e = embed.fields[i];
  141. let name = e.name;
  142. let val = e.value;
  143. if(name) name = await plstranslate(name);
  144. if(val) val = await plstranslate(val);
  145. val = val.replace(/(?:\]\ \()/g, "](");
  146. console.log(name, val);
  147. f.push({ name: name, value: val, inline: e.inline });
  148. }
  149.  
  150. embed.fields = f;
  151. }
  152. }
  153.  
  154. const send = chan => {
  155. if (content instanceof Array) {
  156. const messages = [];
  157. (function sendChunk(list, index) {
  158. const options = index === list.length - 1 ? { tts, embed, files } : { tts };
  159. chan.send(list[index], options).then(message => {
  160. messages.push(message);
  161. if (index >= list.length - 1) return resolve(messages);
  162. return sendChunk(list, ++index);
  163. }).catch(reject);
  164. }(content, 0));
  165. } else {
  166. this.rest.makeRequest('post', Endpoints.Channel(chan).messages, true, {
  167. content, tts, nonce, embed,
  168. }, files).then(data => resolve(this.client.actions.MessageCreate.handle(data).message), reject);
  169. }
  170. };
  171.  
  172. if (channel instanceof User || channel instanceof GuildMember) this.createDM(channel).then(send, reject);
  173. else send(channel);
  174. });
  175. }
  176.  
  177. updateMessage(message, content, { embed, code, reply } = {}) {
  178. if (typeof content !== 'undefined') content = this.client.resolver.resolveString(content);
  179.  
  180. // Wrap everything in a code block
  181. if (typeof code !== 'undefined' && (typeof code !== 'boolean' || code === true)) {
  182. content = Util.escapeMarkdown(this.client.resolver.resolveString(content), true);
  183. content = `\`\`\`${typeof code !== 'boolean' ? code || '' : ''}\n${content}\n\`\`\``;
  184. }
  185.  
  186. // Add the reply prefix
  187. if (DISABLED && reply && message.channel.type !== 'dm') {
  188. const id = this.client.resolver.resolveUserID(reply);
  189. const mention = `<@${reply instanceof GuildMember && reply.nickname ? '!' : ''}${id}>`;
  190. content = `${mention}${content ? `, ${content}` : ''}`;
  191. }
  192.  
  193. return this.rest.makeRequest('patch', Endpoints.Message(message), true, {
  194. content, embed,
  195. }).then(data => this.client.actions.MessageUpdate.handle(data).updated);
  196. }
  197.  
  198. deleteMessage(message) {
  199. return this.rest.makeRequest('delete', Endpoints.Message(message), true)
  200. .then(() =>
  201. this.client.actions.MessageDelete.handle({
  202. id: message.id,
  203. channel_id: message.channel.id,
  204. }).message
  205. );
  206. }
  207.  
  208. ackMessage(message) {
  209. return this.rest.makeRequest('post', Endpoints.Message(message).ack, true, { token: this._ackToken }).then(res => {
  210. if (res.token) this._ackToken = res.token;
  211. return message;
  212. });
  213. }
  214.  
  215. ackTextChannel(channel) {
  216. return this.rest.makeRequest('post', Endpoints.Channel(channel).Message(channel.lastMessageID).ack, true, {
  217. token: this._ackToken,
  218. }).then(res => {
  219. if (res.token) this._ackToken = res.token;
  220. return channel;
  221. });
  222. }
  223.  
  224. ackGuild(guild) {
  225. return this.rest.makeRequest('post', Endpoints.Guild(guild).ack, true).then(() => guild);
  226. }
  227.  
  228. bulkDeleteMessages(channel, messages) {
  229. return this.rest.makeRequest('post', Endpoints.Channel(channel).messages.bulkDelete, true, {
  230. messages: messages.map(m => m.id),
  231. }).then(() =>
  232. this.client.actions.MessageDeleteBulk.handle({
  233. channel_id: channel.id,
  234. messages,
  235. }).messages
  236. );
  237. }
  238.  
  239. search(target, options) {
  240. if (typeof options === 'string') options = { content: options };
  241. if (options.before) {
  242. if (!(options.before instanceof Date)) options.before = new Date(options.before);
  243. options.maxID = long.fromNumber(options.before.getTime() - 14200704e5).shiftLeft(22).toString();
  244. }
  245. if (options.after) {
  246. if (!(options.after instanceof Date)) options.after = new Date(options.after);
  247. options.minID = long.fromNumber(options.after.getTime() - 14200704e5).shiftLeft(22).toString();
  248. }
  249. if (options.during) {
  250. if (!(options.during instanceof Date)) options.during = new Date(options.during);
  251. const t = options.during.getTime() - 14200704e5;
  252. options.minID = long.fromNumber(t).shiftLeft(22).toString();
  253. options.maxID = long.fromNumber(t + 86400000).shiftLeft(22).toString();
  254. }
  255. if (options.channel) options.channel = this.client.resolver.resolveChannelID(options.channel);
  256. if (options.author) options.author = this.client.resolver.resolveUserID(options.author);
  257. if (options.mentions) options.mentions = this.client.resolver.resolveUserID(options.options.mentions);
  258. options = {
  259. content: options.content,
  260. max_id: options.maxID,
  261. min_id: options.minID,
  262. has: options.has,
  263. channel_id: options.channel,
  264. author_id: options.author,
  265. author_type: options.authorType,
  266. context_size: options.contextSize,
  267. sort_by: options.sortBy,
  268. sort_order: options.sortOrder,
  269. limit: options.limit,
  270. offset: options.offset,
  271. mentions: options.mentions,
  272. mentions_everyone: options.mentionsEveryone,
  273. link_hostname: options.linkHostname,
  274. embed_provider: options.embedProvider,
  275. embed_type: options.embedType,
  276. attachment_filename: options.attachmentFilename,
  277. attachment_extension: options.attachmentExtension,
  278. include_nsfw: options.nsfw,
  279. };
  280.  
  281. for (const key in options) if (options[key] === undefined) delete options[key];
  282. const queryString = (querystring.stringify(options).match(/[^=&?]+=[^=&?]+/g) || []).join('&');
  283.  
  284. let endpoint;
  285. if (target instanceof Channel) {
  286. endpoint = Endpoints.Channel(target).search;
  287. } else if (target instanceof Guild) {
  288. endpoint = Endpoints.Guild(target).search;
  289. } else {
  290. throw new TypeError('Target must be a TextChannel, DMChannel, GroupDMChannel, or Guild.');
  291. }
  292. return this.rest.makeRequest('get', `${endpoint}?${queryString}`, true).then(body => {
  293. const messages = body.messages.map(x =>
  294. x.map(m => new Message(this.client.channels.get(m.channel_id), m, this.client))
  295. );
  296. return {
  297. totalResults: body.total_results,
  298. messages,
  299. };
  300. });
  301. }
  302.  
  303. createChannel(guild, channelName, channelType, overwrites, reason) {
  304. if (overwrites instanceof Collection || overwrites instanceof Array) {
  305. overwrites = overwrites.map(overwrite => {
  306. let allow = overwrite.allow || overwrite._allowed;
  307. let deny = overwrite.deny || overwrite._denied;
  308. if (allow instanceof Array) allow = Permissions.resolve(allow);
  309. if (deny instanceof Array) deny = Permissions.resolve(deny);
  310.  
  311. const role = this.client.resolver.resolveRole(guild, overwrite.id);
  312. if (role) {
  313. overwrite.id = role.id;
  314. overwrite.type = 'role';
  315. } else {
  316. overwrite.id = this.client.resolver.resolveUserID(overwrite.id);
  317. overwrite.type = 'member';
  318. }
  319.  
  320. return {
  321. allow,
  322. deny,
  323. type: overwrite.type,
  324. id: overwrite.id,
  325. };
  326. });
  327. }
  328. return this.rest.makeRequest('post', Endpoints.Guild(guild).channels, true, {
  329. name: channelName,
  330. type: channelType ? Constants.ChannelTypes[channelType.toUpperCase()] : 'text',
  331. permission_overwrites: overwrites,
  332. }, undefined, reason).then(data => this.client.actions.ChannelCreate.handle(data).channel);
  333. }
  334.  
  335. createDM(recipient) {
  336. const dmChannel = this.getExistingDM(recipient);
  337. if (dmChannel) return Promise.resolve(dmChannel);
  338. return this.rest.makeRequest('post', Endpoints.User(this.client.user).channels, true, {
  339. recipient_id: recipient.id,
  340. }).then(data => this.client.actions.ChannelCreate.handle(data).channel);
  341. }
  342.  
  343. createGroupDM(options) {
  344. const data = this.client.user.bot ?
  345. { access_tokens: options.accessTokens, nicks: options.nicks } :
  346. { recipients: options.recipients };
  347. return this.rest.makeRequest('post', Endpoints.User('@me').channels, true, data)
  348. .then(res => new GroupDMChannel(this.client, res));
  349. }
  350.  
  351. addUserToGroupDM(channel, options) {
  352. const data = this.client.user.bot ?
  353. { nick: options.nick, access_token: options.accessToken } :
  354. { recipient: options.id };
  355. return this.rest.makeRequest('put', Endpoints.Channel(channel).Recipient(options.id), true, data)
  356. .then(() => channel);
  357. }
  358.  
  359. removeUserFromGroupDM(channel, userId) {
  360. return this.rest.makeRequest('delete', Endpoints.Channel(channel).Recipient(userId), true)
  361. .then(() => channel);
  362. }
  363.  
  364. updateGroupDMChannel(channel, _data) {
  365. const data = {};
  366. data.name = _data.name;
  367. data.icon = _data.icon;
  368. return this.rest.makeRequest('patch', Endpoints.Channel(channel), true, data).then(() => channel);
  369. }
  370.  
  371. getExistingDM(recipient) {
  372. return this.client.channels.find(channel =>
  373. channel.recipient && channel.recipient.id === recipient.id
  374. );
  375. }
  376.  
  377. deleteChannel(channel, reason) {
  378. if (channel instanceof User || channel instanceof GuildMember) channel = this.getExistingDM(channel);
  379. if (!channel) return Promise.reject(new Error('No channel to delete.'));
  380. return this.rest.makeRequest('delete', Endpoints.Channel(channel), true, undefined, undefined, reason)
  381. .then(data => {
  382. data.id = channel.id;
  383. return this.client.actions.ChannelDelete.handle(data).channel;
  384. });
  385. }
  386.  
  387. updateChannel(channel, _data, reason) {
  388. const data = {};
  389. data.name = (_data.name || channel.name).trim();
  390. data.topic = _data.topic || channel.topic;
  391. data.position = _data.position || channel.position;
  392. data.bitrate = _data.bitrate || (channel.bitrate ? channel.bitrate * 1000 : undefined);
  393. data.user_limit = typeof _data.userLimit !== 'undefined' ? _data.userLimit : channel.userLimit;
  394. data.parent_id = _data.parent || (channel.parent ? channel.parent.id : undefined);
  395. return this.rest.makeRequest('patch', Endpoints.Channel(channel), true, data, undefined, reason).then(newData =>
  396. this.client.actions.ChannelUpdate.handle(newData).updated
  397. );
  398. }
  399.  
  400. leaveGuild(guild) {
  401. if (guild.ownerID === this.client.user.id) return Promise.reject(new Error('Guild is owned by the client.'));
  402. return this.rest.makeRequest('delete', Endpoints.User('@me').Guild(guild.id), true).then(() =>
  403. this.client.actions.GuildDelete.handle({ id: guild.id }).guild
  404. );
  405. }
  406.  
  407. createGuild(options) {
  408. options.icon = this.client.resolver.resolveBase64(options.icon) || null;
  409. options.region = options.region || 'us-central';
  410. return new Promise((resolve, reject) => {
  411. this.rest.makeRequest('post', Endpoints.guilds, true, options).then(data => {
  412. if (this.client.guilds.has(data.id)) return resolve(this.client.guilds.get(data.id));
  413.  
  414. const handleGuild = guild => {
  415. if (guild.id === data.id) {
  416. this.client.removeListener(Constants.Events.GUILD_CREATE, handleGuild);
  417. this.client.clearTimeout(timeout);
  418. resolve(guild);
  419. }
  420. };
  421. this.client.on(Constants.Events.GUILD_CREATE, handleGuild);
  422.  
  423. const timeout = this.client.setTimeout(() => {
  424. this.client.removeListener(Constants.Events.GUILD_CREATE, handleGuild);
  425. reject(new Error('Took too long to receive guild data.'));
  426. }, 10000);
  427. return undefined;
  428. }, reject);
  429. });
  430. }
  431.  
  432. // Untested but probably will work
  433. deleteGuild(guild) {
  434. return this.rest.makeRequest('delete', Endpoints.Guild(guild), true).then(() =>
  435. this.client.actions.GuildDelete.handle({ id: guild.id }).guild
  436. );
  437. }
  438.  
  439. getUser(userID, cache) {
  440. return this.rest.makeRequest('get', Endpoints.User(userID), true).then(data => {
  441. if (cache) return this.client.actions.UserGet.handle(data).user;
  442. else return new User(this.client, data);
  443. });
  444. }
  445.  
  446. updateCurrentUser(_data, password) {
  447. const user = this.client.user;
  448. const data = {};
  449. data.username = _data.username || user.username;
  450. data.avatar = typeof _data.avatar === 'undefined' ? user.avatar : this.client.resolver.resolveBase64(_data.avatar);
  451. if (!user.bot) {
  452. data.email = _data.email || user.email;
  453. data.password = password;
  454. if (_data.new_password) data.new_password = _data.newPassword;
  455. }
  456. return this.rest.makeRequest('patch', Endpoints.User('@me'), true, data).then(newData =>
  457. this.client.actions.UserUpdate.handle(newData).updated
  458. );
  459. }
  460.  
  461. updateGuild(guild, data, reason) {
  462. return this.rest.makeRequest('patch', Endpoints.Guild(guild), true, data, undefined, reason).then(newData =>
  463. this.client.actions.GuildUpdate.handle(newData).updated
  464. );
  465. }
  466.  
  467. kickGuildMember(guild, member, reason) {
  468. return this.rest.makeRequest(
  469. 'delete', Endpoints.Guild(guild).Member(member), true,
  470. undefined, undefined, reason)
  471. .then(() =>
  472. this.client.actions.GuildMemberRemove.handle({
  473. guild_id: guild.id,
  474. user: member.user,
  475. }).member
  476. );
  477. }
  478.  
  479. createGuildRole(guild, data, reason) {
  480. if (data.color) data.color = this.client.resolver.resolveColor(data.color);
  481. if (data.permissions) data.permissions = Permissions.resolve(data.permissions);
  482. return this.rest.makeRequest('post', Endpoints.Guild(guild).roles, true, data, undefined, reason).then(r => {
  483. const { role } = this.client.actions.GuildRoleCreate.handle({
  484. guild_id: guild.id,
  485. role: r,
  486. });
  487. if (data.position) return role.setPosition(data.position, reason);
  488. return role;
  489. });
  490. }
  491.  
  492. deleteGuildRole(role, reason) {
  493. return this.rest.makeRequest(
  494. 'delete', Endpoints.Guild(role.guild).Role(role.id), true,
  495. undefined, undefined, reason)
  496. .then(() =>
  497. this.client.actions.GuildRoleDelete.handle({
  498. guild_id: role.guild.id,
  499. role_id: role.id,
  500. }).role
  501. );
  502. }
  503.  
  504. setChannelOverwrite(channel, payload) {
  505. return this.rest.makeRequest('put', `${Endpoints.Channel(channel).permissions}/${payload.id}`, true, payload);
  506. }
  507.  
  508. deletePermissionOverwrites(overwrite, reason) {
  509. return this.rest.makeRequest(
  510. 'delete', `${Endpoints.Channel(overwrite.channel).permissions}/${overwrite.id}`,
  511. true, undefined, undefined, reason
  512. ).then(() => overwrite);
  513. }
  514.  
  515. getChannelMessages(channel, payload = {}) {
  516. const params = [];
  517. if (payload.limit) params.push(`limit=${payload.limit}`);
  518. if (payload.around) params.push(`around=${payload.around}`);
  519. else if (payload.before) params.push(`before=${payload.before}`);
  520. else if (payload.after) params.push(`after=${payload.after}`);
  521.  
  522. let endpoint = Endpoints.Channel(channel).messages;
  523. if (params.length > 0) endpoint += `?${params.join('&')}`;
  524. return this.rest.makeRequest('get', endpoint, true);
  525. }
  526.  
  527. getChannelMessage(channel, messageID) {
  528. const msg = channel.messages.get(messageID);
  529. if (msg) return Promise.resolve(msg);
  530. return this.rest.makeRequest('get', Endpoints.Channel(channel).Message(messageID), true);
  531. }
  532.  
  533. putGuildMember(guild, user, options) {
  534. options.access_token = options.accessToken;
  535. if (options.roles) {
  536. const roles = options.roles;
  537. if (roles instanceof Collection || (roles instanceof Array && roles[0] instanceof Role)) {
  538. options.roles = roles.map(role => role.id);
  539. }
  540. }
  541. return this.rest.makeRequest('put', Endpoints.Guild(guild).Member(user.id), true, options)
  542. .then(data => this.client.actions.GuildMemberGet.handle(guild, data).member);
  543. }
  544.  
  545. getGuildMember(guild, user, cache) {
  546. return this.rest.makeRequest('get', Endpoints.Guild(guild).Member(user.id), true).then(data => {
  547. if (cache) return this.client.actions.GuildMemberGet.handle(guild, data).member;
  548. else return new GuildMember(guild, data);
  549. });
  550. }
  551.  
  552. updateGuildMember(member, data, reason) {
  553. if (data.channel) {
  554. data.channel_id = this.client.resolver.resolveChannel(data.channel).id;
  555. data.channel = null;
  556. }
  557. if (data.roles) data.roles = data.roles.map(role => role instanceof Role ? role.id : role);
  558.  
  559. let endpoint = Endpoints.Member(member);
  560. // Fix your endpoints, discord ;-;
  561. if (member.id === this.client.user.id) {
  562. const keys = Object.keys(data);
  563. if (keys.length === 1 && keys[0] === 'nick') {
  564. endpoint = Endpoints.Member(member).nickname;
  565. }
  566. }
  567.  
  568. return this.rest.makeRequest('patch', endpoint, true, data, undefined, reason).then(newData =>
  569. member.guild._updateMember(member, newData).mem
  570. );
  571. }
  572.  
  573. addMemberRole(member, role, reason) {
  574. return new Promise((resolve, reject) => {
  575. if (member._roles.includes(role.id)) return resolve(member);
  576.  
  577. const listener = (oldMember, newMember) => {
  578. if (!oldMember._roles.includes(role.id) && newMember._roles.includes(role.id)) {
  579. this.client.removeListener(Constants.Events.GUILD_MEMBER_UPDATE, listener);
  580. resolve(newMember);
  581. }
  582. };
  583.  
  584. this.client.on(Constants.Events.GUILD_MEMBER_UPDATE, listener);
  585. const timeout = this.client.setTimeout(() =>
  586. this.client.removeListener(Constants.Events.GUILD_MEMBER_UPDATE, listener), 10e3);
  587.  
  588. return this.rest.makeRequest('put', Endpoints.Member(member).Role(role.id), true, undefined, undefined, reason)
  589. .catch(err => {
  590. this.client.removeListener(Constants.Events.GUILD_BAN_REMOVE, listener);
  591. this.client.clearTimeout(timeout);
  592. reject(err);
  593. });
  594. });
  595. }
  596.  
  597. removeMemberRole(member, role, reason) {
  598. return new Promise((resolve, reject) => {
  599. if (!member._roles.includes(role.id)) return resolve(member);
  600.  
  601. const listener = (oldMember, newMember) => {
  602. if (oldMember._roles.includes(role.id) && !newMember._roles.includes(role.id)) {
  603. this.client.removeListener(Constants.Events.GUILD_MEMBER_UPDATE, listener);
  604. resolve(newMember);
  605. }
  606. };
  607.  
  608. this.client.on(Constants.Events.GUILD_MEMBER_UPDATE, listener);
  609. const timeout = this.client.setTimeout(() =>
  610. this.client.removeListener(Constants.Events.GUILD_MEMBER_UPDATE, listener), 10e3);
  611.  
  612. return this.rest.makeRequest('delete', Endpoints.Member(member).Role(role.id), true, undefined, undefined, reason)
  613. .catch(err => {
  614. this.client.removeListener(Constants.Events.GUILD_BAN_REMOVE, listener);
  615. this.client.clearTimeout(timeout);
  616. reject(err);
  617. });
  618. });
  619. }
  620.  
  621. sendTyping(channelID) {
  622. return this.rest.makeRequest('post', Endpoints.Channel(channelID).typing, true);
  623. }
  624.  
  625. banGuildMember(guild, member, options) {
  626. const id = this.client.resolver.resolveUserID(member);
  627. if (!id) return Promise.reject(new Error('Couldn\'t resolve the user ID to ban.'));
  628.  
  629. const url = `${Endpoints.Guild(guild).bans}/${id}?${querystring.stringify(options)}`;
  630. return this.rest.makeRequest('put', url, true).then(() => {
  631. if (member instanceof GuildMember) return member;
  632. const user = this.client.resolver.resolveUser(id);
  633. if (user) {
  634. member = this.client.resolver.resolveGuildMember(guild, user);
  635. return member || user;
  636. }
  637. return id;
  638. });
  639. }
  640.  
  641. unbanGuildMember(guild, member, reason) {
  642. return new Promise((resolve, reject) => {
  643. const id = this.client.resolver.resolveUserID(member);
  644. if (!id) throw new Error('Couldn\'t resolve the user ID to unban.');
  645.  
  646. const listener = (eGuild, eUser) => {
  647. if (eGuild.id === guild.id && eUser.id === id) {
  648. this.client.removeListener(Constants.Events.GUILD_BAN_REMOVE, listener);
  649. this.client.clearTimeout(timeout);
  650. resolve(eUser);
  651. }
  652. };
  653. this.client.on(Constants.Events.GUILD_BAN_REMOVE, listener);
  654.  
  655. const timeout = this.client.setTimeout(() => {
  656. this.client.removeListener(Constants.Events.GUILD_BAN_REMOVE, listener);
  657. reject(new Error('Took too long to receive the ban remove event.'));
  658. }, 10000);
  659.  
  660. this.rest.makeRequest('delete', `${Endpoints.Guild(guild).bans}/${id}`, true, undefined, undefined, reason)
  661. .catch(err => {
  662. this.client.removeListener(Constants.Events.GUILD_BAN_REMOVE, listener);
  663. this.client.clearTimeout(timeout);
  664. reject(err);
  665. });
  666. });
  667. }
  668.  
  669. getGuildBans(guild) {
  670. return this.rest.makeRequest('get', Endpoints.Guild(guild).bans, true).then(bans =>
  671. bans.reduce((collection, ban) => {
  672. collection.set(ban.user.id, {
  673. reason: ban.reason,
  674. user: this.client.dataManager.newUser(ban.user),
  675. });
  676. return collection;
  677. }, new Collection())
  678. );
  679. }
  680.  
  681. updateGuildRole(role, _data, reason) {
  682. const data = {};
  683. data.name = _data.name || role.name;
  684. data.position = typeof _data.position !== 'undefined' ? _data.position : role.position;
  685. data.color = this.client.resolver.resolveColor(_data.color || role.color);
  686. data.hoist = typeof _data.hoist !== 'undefined' ? _data.hoist : role.hoist;
  687. data.mentionable = typeof _data.mentionable !== 'undefined' ? _data.mentionable : role.mentionable;
  688.  
  689. if (_data.permissions) data.permissions = Permissions.resolve(_data.permissions);
  690. else data.permissions = role.permissions;
  691.  
  692. return this.rest.makeRequest('patch', Endpoints.Guild(role.guild).Role(role.id), true, data, undefined, reason)
  693. .then(_role =>
  694. this.client.actions.GuildRoleUpdate.handle({
  695. role: _role,
  696. guild_id: role.guild.id,
  697. }).updated
  698. );
  699. }
  700.  
  701. pinMessage(message) {
  702. return this.rest.makeRequest('put', Endpoints.Channel(message.channel).Pin(message.id), true)
  703. .then(() => message);
  704. }
  705.  
  706. unpinMessage(message) {
  707. return this.rest.makeRequest('delete', Endpoints.Channel(message.channel).Pin(message.id), true)
  708. .then(() => message);
  709. }
  710.  
  711. getChannelPinnedMessages(channel) {
  712. return this.rest.makeRequest('get', Endpoints.Channel(channel).pins, true);
  713. }
  714.  
  715. createChannelInvite(channel, options, reason) {
  716. const payload = {};
  717. payload.temporary = options.temporary;
  718. payload.max_age = options.maxAge;
  719. payload.max_uses = options.maxUses;
  720. payload.unique = options.unique;
  721. return this.rest.makeRequest('post', Endpoints.Channel(channel).invites, true, payload, undefined, reason)
  722. .then(invite => new Invite(this.client, invite));
  723. }
  724.  
  725. deleteInvite(invite, reason) {
  726. return this.rest.makeRequest('delete', Endpoints.Invite(invite.code), true, undefined, undefined, reason)
  727. .then(() => invite);
  728. }
  729.  
  730. getInvite(code) {
  731. return this.rest.makeRequest('get', Endpoints.Invite(code), true).then(invite =>
  732. new Invite(this.client, invite)
  733. );
  734. }
  735.  
  736. getGuildInvites(guild) {
  737. return this.rest.makeRequest('get', Endpoints.Guild(guild).invites, true).then(inviteItems => {
  738. const invites = new Collection();
  739. for (const inviteItem of inviteItems) {
  740. const invite = new Invite(this.client, inviteItem);
  741. invites.set(invite.code, invite);
  742. }
  743. return invites;
  744. });
  745. }
  746.  
  747. pruneGuildMembers(guild, days, dry, reason) {
  748. return this.rest.makeRequest(dry ?
  749. 'get' :
  750. 'post',
  751. `${Endpoints.Guild(guild).prune}?days=${days}`, true, undefined, undefined, reason)
  752. .then(data => data.pruned);
  753. }
  754.  
  755. createEmoji(guild, image, name, roles, reason) {
  756. const data = { image, name };
  757. if (roles) data.roles = roles.map(r => r.id ? r.id : r);
  758. return this.rest.makeRequest('post', Endpoints.Guild(guild).emojis, true, data, undefined, reason)
  759. .then(emoji => this.client.actions.GuildEmojiCreate.handle(guild, emoji).emoji);
  760. }
  761.  
  762. updateEmoji(emoji, _data, reason) {
  763. const data = {};
  764. if (_data.name) data.name = _data.name;
  765. if (_data.roles) data.roles = _data.roles.map(r => r.id ? r.id : r);
  766. return this.rest.makeRequest('patch', Endpoints.Guild(emoji.guild).Emoji(emoji.id), true, data, undefined, reason)
  767. .then(newEmoji => this.client.actions.GuildEmojiUpdate.handle(emoji, newEmoji).emoji);
  768. }
  769.  
  770. deleteEmoji(emoji, reason) {
  771. return this.rest.makeRequest('delete', Endpoints.Guild(emoji.guild).Emoji(emoji.id), true, undefined, reason)
  772. .then(() => this.client.actions.GuildEmojiDelete.handle(emoji).data);
  773. }
  774.  
  775. getGuildAuditLogs(guild, options = {}) {
  776. if (options.before && options.before instanceof GuildAuditLogs.Entry) options.before = options.before.id;
  777. if (options.after && options.after instanceof GuildAuditLogs.Entry) options.after = options.after.id;
  778. if (typeof options.type === 'string') options.type = GuildAuditLogs.Actions[options.type];
  779.  
  780. const queryString = (querystring.stringify({
  781. before: options.before,
  782. after: options.after,
  783. limit: options.limit,
  784. user_id: this.client.resolver.resolveUserID(options.user),
  785. action_type: options.type,
  786. }).match(/[^=&?]+=[^=&?]+/g) || []).join('&');
  787.  
  788. return this.rest.makeRequest('get', `${Endpoints.Guild(guild).auditLogs}?${queryString}`, true)
  789. .then(data => GuildAuditLogs.build(guild, data));
  790. }
  791.  
  792. getWebhook(id, token) {
  793. return this.rest.makeRequest('get', Endpoints.Webhook(id, token), !token).then(data =>
  794. new Webhook(this.client, data)
  795. );
  796. }
  797.  
  798. getGuildWebhooks(guild) {
  799. return this.rest.makeRequest('get', Endpoints.Guild(guild).webhooks, true).then(data => {
  800. const hooks = new Collection();
  801. for (const hook of data) hooks.set(hook.id, new Webhook(this.client, hook));
  802. return hooks;
  803. });
  804. }
  805.  
  806. getChannelWebhooks(channel) {
  807. return this.rest.makeRequest('get', Endpoints.Channel(channel).webhooks, true).then(data => {
  808. const hooks = new Collection();
  809. for (const hook of data) hooks.set(hook.id, new Webhook(this.client, hook));
  810. return hooks;
  811. });
  812. }
  813.  
  814. createWebhook(channel, name, avatar, reason) {
  815. return this.rest.makeRequest('post', Endpoints.Channel(channel).webhooks, true, { name, avatar }, undefined, reason)
  816. .then(data => new Webhook(this.client, data));
  817. }
  818.  
  819. editWebhook(webhook, name, avatar) {
  820. return this.rest.makeRequest('patch', Endpoints.Webhook(webhook.id, webhook.token), false, {
  821. name,
  822. avatar,
  823. }).then(data => {
  824. webhook.name = data.name;
  825. webhook.avatar = data.avatar;
  826. return webhook;
  827. });
  828. }
  829.  
  830. deleteWebhook(webhook, reason) {
  831. return this.rest.makeRequest(
  832. 'delete', Endpoints.Webhook(webhook.id, webhook.token),
  833. false, undefined, undefined, reason);
  834. }
  835.  
  836. sendWebhookMessage(webhook, content, { avatarURL, tts, embeds, username } = {}, files = null) {
  837. return new Promise((resolve, reject) => {
  838. username = username || webhook.name;
  839.  
  840. if (content instanceof Array) {
  841. const messages = [];
  842. (function sendChunk(list, index) {
  843. const options = index === list.length - 1 ? { tts, embeds, files } : { tts };
  844. webhook.send(list[index], options).then(message => {
  845. messages.push(message);
  846. if (index >= list.length - 1) return resolve(messages);
  847. return sendChunk(list, ++index);
  848. }).catch(reject);
  849. }(content, 0));
  850. } else {
  851. this.rest.makeRequest('post', `${Endpoints.Webhook(webhook.id, webhook.token)}?wait=true`, false, {
  852. username,
  853. avatar_url: avatarURL,
  854. content,
  855. tts,
  856. embeds,
  857. }, files).then(data => {
  858. if (!this.client.channels) resolve(data);
  859. else resolve(this.client.actions.MessageCreate.handle(data).message);
  860. }, reject);
  861. }
  862. });
  863. }
  864.  
  865. sendSlackWebhookMessage(webhook, body) {
  866. return this.rest.makeRequest(
  867. 'post', `${Endpoints.Webhook(webhook.id, webhook.token)}/slack?wait=true`, false, body
  868. );
  869. }
  870.  
  871. fetchUserProfile(user) {
  872. return this.rest.makeRequest('get', Endpoints.User(user).profile, true).then(data =>
  873. new UserProfile(user, data)
  874. );
  875. }
  876.  
  877. fetchMentions(options) {
  878. if (options.guild instanceof Guild) options.guild = options.guild.id;
  879. Util.mergeDefault({ limit: 25, roles: true, everyone: true, guild: null }, options);
  880.  
  881. return this.rest.makeRequest(
  882. 'get', Endpoints.User('@me').Mentions(options.limit, options.roles, options.everyone, options.guild), true
  883. ).then(data => data.map(m => new Message(this.client.channels.get(m.channel_id), m, this.client)));
  884. }
  885.  
  886. addFriend(user) {
  887. return this.rest.makeRequest('post', Endpoints.User('@me'), true, {
  888. username: user.username,
  889. discriminator: user.discriminator,
  890. }).then(() => user);
  891. }
  892.  
  893. removeFriend(user) {
  894. return this.rest.makeRequest('delete', Endpoints.User('@me').Relationship(user.id), true)
  895. .then(() => user);
  896. }
  897.  
  898. blockUser(user) {
  899. return this.rest.makeRequest('put', Endpoints.User('@me').Relationship(user.id), true, { type: 2 })
  900. .then(() => user);
  901. }
  902.  
  903. unblockUser(user) {
  904. return this.rest.makeRequest('delete', Endpoints.User('@me').Relationship(user.id), true)
  905. .then(() => user);
  906. }
  907.  
  908. updateChannelPositions(guildID, channels) {
  909. const data = new Array(channels.length);
  910. for (let i = 0; i < channels.length; i++) {
  911. data[i] = {
  912. id: this.client.resolver.resolveChannelID(channels[i].channel),
  913. position: channels[i].position,
  914. };
  915. }
  916.  
  917. return this.rest.makeRequest('patch', Endpoints.Guild(guildID).channels, true, data).then(() =>
  918. this.client.actions.GuildChannelsPositionUpdate.handle({
  919. guild_id: guildID,
  920. channels,
  921. }).guild
  922. );
  923. }
  924.  
  925. setRolePositions(guildID, roles) {
  926. return this.rest.makeRequest('patch', Endpoints.Guild(guildID).roles, true, roles).then(() =>
  927. this.client.actions.GuildRolesPositionUpdate.handle({
  928. guild_id: guildID,
  929. roles,
  930. }).guild
  931. );
  932. }
  933.  
  934. setChannelPositions(guildID, channels) {
  935. return this.rest.makeRequest('patch', Endpoints.Guild(guildID).channels, true, channels).then(() =>
  936. this.client.actions.GuildChannelsPositionUpdate.handle({
  937. guild_id: guildID,
  938. channels,
  939. }).guild
  940. );
  941. }
  942.  
  943. addMessageReaction(message, emoji) {
  944. return this.rest.makeRequest(
  945. 'put', Endpoints.Message(message).Reaction(emoji).User('@me'), true
  946. ).then(() =>
  947. message._addReaction(Util.parseEmoji(emoji), message.client.user)
  948. );
  949. }
  950.  
  951. removeMessageReaction(message, emoji, userID) {
  952. const endpoint = Endpoints.Message(message).Reaction(emoji).User(userID === this.client.user.id ? '@me' : userID);
  953. return this.rest.makeRequest('delete', endpoint, true).then(() =>
  954. this.client.actions.MessageReactionRemove.handle({
  955. user_id: userID,
  956. message_id: message.id,
  957. emoji: Util.parseEmoji(emoji),
  958. channel_id: message.channel.id,
  959. }).reaction
  960. );
  961. }
  962.  
  963. removeMessageReactions(message) {
  964. return this.rest.makeRequest('delete', Endpoints.Message(message).reactions, true)
  965. .then(() => message);
  966. }
  967.  
  968. getMessageReactionUsers(message, emoji, options) {
  969. const queryString = (querystring.stringify(options).match(/[^=&?]+=[^=&?]+/g) || []).join('&');
  970.  
  971. return this.rest.makeRequest('get', `${Endpoints.Message(message).Reaction(emoji)}?${queryString}`, true);
  972. }
  973.  
  974. getApplication(id) {
  975. return this.rest.makeRequest('get', Endpoints.OAUTH2.Application(id), true).then(app =>
  976. new OAuth2Application(this.client, app)
  977. );
  978. }
  979.  
  980. resetApplication(id) {
  981. return this.rest.makeRequest('post', Endpoints.OAUTH2.Application(id).resetToken, true)
  982. .then(() => this.rest.makeRequest('post', Endpoints.OAUTH2.Application(id).resetSecret, true))
  983. .then(app => new OAuth2Application(this.client, app));
  984. }
  985.  
  986. setNote(user, note) {
  987. return this.rest.makeRequest('put', Endpoints.User(user).note, true, { note }).then(() => user);
  988. }
  989.  
  990. acceptInvite(code) {
  991. if (code.id) code = code.id;
  992. return new Promise((resolve, reject) =>
  993. this.rest.makeRequest('post', Endpoints.Invite(code), true).then(res => {
  994. const handler = guild => {
  995. if (guild.id === res.id) {
  996. resolve(guild);
  997. this.client.removeListener(Constants.Events.GUILD_CREATE, handler);
  998. }
  999. };
  1000. this.client.on(Constants.Events.GUILD_CREATE, handler);
  1001. this.client.setTimeout(() => {
  1002. this.client.removeListener(Constants.Events.GUILD_CREATE, handler);
  1003. reject(new Error('Accepting invite timed out'));
  1004. }, 120e3);
  1005. })
  1006. );
  1007. }
  1008.  
  1009. patchUserSettings(data) {
  1010. return this.rest.makeRequest('patch', Constants.Endpoints.User('@me').settings, true, data);
  1011. }
  1012.  
  1013. patchClientUserGuildSettings(guildID, data) {
  1014. return this.rest.makeRequest('patch', Constants.Endpoints.User('@me').Guild(guildID).settings, true, data);
  1015. }
  1016. }
  1017.  
  1018. module.exports = RESTMethods;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement