Guest User

Untitled

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