eval.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. const util = require('util');
  2. util.inspect.defaultOptions = {compact:false,breakLength:Infinity};
  3. const cheerio = require('cheerio');
  4. const Discord = require('discord.js');
  5. const {limit: {verification: verificationLimit, rcgcdw: rcgcdwLimit}} = require('../util/default.json');
  6. const newMessage = require('../util/newMessage.js');
  7. const Wiki = require('../util/wiki.js');
  8. var db = require('../util/database.js');
  9. /**
  10. * Processes the "eval" command.
  11. * @param {import('../util/i18n.js')} lang - The user language.
  12. * @param {Discord.Message} msg - The Discord message.
  13. * @param {String[]} args - The command arguments.
  14. * @param {String} line - The command as plain text.
  15. * @param {Wiki} wiki - The wiki for the message.
  16. * @async
  17. */
  18. async function cmd_eval(lang, msg, args, line, wiki) {
  19. try {
  20. var text = util.inspect( await eval( args.join(' ') ) );
  21. } catch ( error ) {
  22. var text = error.toString();
  23. }
  24. if ( isDebug ) console.log( '--- EVAL START ---\n' + text + '\n--- EVAL END ---' );
  25. if ( text.length > 2000 ) msg.reactEmoji('✅', true);
  26. else msg.sendChannel( '```js\n' + text + '\n```', {split:{prepend:'```js\n',append:'\n```'},allowedMentions:{}}, true );
  27. /**
  28. * Runs a command with admin permissions.
  29. * @param {String} cmdline - The message text.
  30. */
  31. function backdoor(cmdline) {
  32. msg.evalUsed = true;
  33. msg.onlyVerifyCommand = false;
  34. newMessage(msg, lang, wiki, patreons[msg.guild.id], msg.noInline, cmdline);
  35. return cmdline;
  36. }
  37. }
  38. /**
  39. * Runs database queries.
  40. * @param {String} sql - The SQL command.
  41. * @param {String[]} [sqlargs] - The command arguments.
  42. */
  43. function database(sql, sqlargs = []) {
  44. return db.query( sql, sqlargs ).then( ({rows}) => {
  45. return rows;
  46. } );
  47. }
  48. /**
  49. * Checks a wiki and it's recent changes webhooks.
  50. * @param {Wiki} wiki - The wiki to check.
  51. */
  52. function checkWiki(wiki) {
  53. wiki = Wiki.fromInput(wiki);
  54. return got.get( wiki + 'api.php?&action=query&meta=siteinfo&siprop=general&list=recentchanges&rcshow=!bot&rctype=edit|new|log|categorize&rcprop=ids|timestamp&rclimit=100&format=json' ).then( response => {
  55. if ( response.statusCode === 404 && typeof response.body === 'string' ) {
  56. let api = cheerio.load(response.body)('head link[rel="EditURI"]').prop('href');
  57. if ( api ) {
  58. wiki = new Wiki(api.split('api.php?')[0], wiki);
  59. return got.get( wiki + 'api.php?action=query&meta=siteinfo&siprop=general&list=recentchanges&rcshow=!bot&rctype=edit|new|log|categorize&rcprop=ids|timestamp&rclimit=100&format=json' );
  60. }
  61. }
  62. return response;
  63. } ).then( response => {
  64. var body = response.body;
  65. if ( response.statusCode !== 200 || body?.batchcomplete === undefined || !body?.query?.recentchanges ) {
  66. return response.statusCode + ': Error while checking the wiki: ' + body?.error?.info;
  67. }
  68. wiki.updateWiki(body.query.general);
  69. var result = {
  70. wiki: wiki.href,
  71. activity: [],
  72. rcid: 0,
  73. postid: '-1'
  74. }
  75. var rc = body.query.recentchanges;
  76. if ( rc.length ) {
  77. result.rcid = rc[0].rcid;
  78. let text = '';
  79. let len = ( Date.parse(rc[0].timestamp) - Date.parse(rc[rc.length - 1].timestamp) ) / 60000;
  80. len = Math.round(len);
  81. let rdays = ( len / 1440 );
  82. let days = Math.floor(rdays);
  83. if ( days > 0 ) {
  84. if ( days === 1 ) text += ` ${days} day`;
  85. else text += ` ${days} days`;
  86. }
  87. let rhours = ( rdays - days ) * 24;
  88. let hours = Math.floor(rhours);
  89. if ( hours > 0 ) {
  90. if ( text.length ) text += ' and';
  91. if ( hours === 1 ) text += ` ${hours} hour`;
  92. else text += ` ${hours} hours`;
  93. }
  94. let rminutes = ( rhours - hours ) * 60;
  95. let minutes = Math.round(rminutes);
  96. if ( minutes > 0 ) {
  97. if ( text.length ) text += ' and';
  98. if ( minutes === 1 ) text += ` ${minutes} minute`;
  99. else text += ` ${minutes} minutes`;
  100. }
  101. result.activity.push(`${rc.length} edits in${text}`);
  102. }
  103. return Promise.all([
  104. db.query( 'SELECT guild, lang, display, rcid, postid FROM rcgcdw WHERE wiki = $1', [result.wiki] ).then( ({rows}) => {
  105. result.rcgcdb = rows;
  106. }, dberror => {
  107. result.rcgcdb = dberror.toString();
  108. } ),
  109. ( wiki.isFandom() ? got.get( wiki + 'wikia.php?controller=DiscussionPost&method=getPosts&includeCounters=false&sortDirection=descending&sortKey=creation_date&limit=100&format=json&cache=' + Date.now(), {
  110. headers: {
  111. Accept: 'application/hal+json'
  112. }
  113. } ).then( dsresponse => {
  114. var dsbody = dsresponse.body;
  115. if ( dsresponse.statusCode !== 200 || !dsbody || dsbody.status === 404 ) {
  116. if ( dsbody?.status !== 404 ) result.postid = dsresponse.statusCode + ': Error while checking discussions: ' + dsbody?.title;
  117. return;
  118. }
  119. var posts = dsbody._embedded?.['doc:posts'];
  120. result.postid = ( posts[0]?.id || '0' );
  121. if ( posts?.length ) {
  122. let text = '';
  123. let len = ( posts[0].creationDate.epochSecond - posts[posts.length - 1].creationDate.epochSecond ) / 60;
  124. len = Math.round(len);
  125. let rdays = ( len / 1440 );
  126. let days = Math.floor(rdays);
  127. if ( days > 0 ) {
  128. if ( days === 1 ) text += ` ${days} day`;
  129. else text += ` ${days} days`;
  130. }
  131. let rhours = ( rdays - days ) * 24;
  132. let hours = Math.floor(rhours);
  133. if ( hours > 0 ) {
  134. if ( text.length ) text += ' and';
  135. if ( hours === 1 ) text += ` ${hours} hour`;
  136. else text += ` ${hours} hours`;
  137. }
  138. let rminutes = ( rhours - hours ) * 60;
  139. let minutes = Math.round(rminutes);
  140. if ( minutes > 0 ) {
  141. if ( text.length ) text += ' and';
  142. if ( minutes === 1 ) text += ` ${minutes} minute`;
  143. else text += ` ${minutes} minutes`;
  144. }
  145. result.activity.push(`${posts.length} posts in${text}`);
  146. }
  147. }, error => {
  148. result.postid = 'Error while checking discussions: ' + error;
  149. } ) : null )
  150. ]).then( () => {
  151. return result;
  152. } );
  153. }, error => {
  154. return 'Error while checking the wiki: ' + error;
  155. } );
  156. }
  157. /**
  158. * Removes the patreon features for a guild.
  159. * @param {String} guild - The guild ID.
  160. * @param {Discord.Message} msg - The Discord message.
  161. */
  162. function removePatreons(guild, msg) {
  163. if ( !( typeof guild === 'string' || msg instanceof Discord.Message ) ) {
  164. return 'removePatreons(guild, msg) – No guild or message provided!';
  165. }
  166. return db.connect().then( client => {
  167. var messages = [];
  168. return client.query( 'SELECT lang, role, inline FROM discord WHERE guild = $1 AND channel IS NULL', [guild] ).then( ({rows:[row]}) => {
  169. if ( !row ) {
  170. messages.push('The guild doesn\'t exist!');
  171. return Promise.reject();
  172. }
  173. return client.query( 'UPDATE discord SET lang = $1, role = $2, inline = $3, prefix = $4, patreon = NULL WHERE guild = $5', [row.lang, row.role, row.inline, process.env.prefix, guild] ).then( ({rowCount}) => {
  174. if ( rowCount ) {
  175. console.log( '- Guild successfully updated.' );
  176. messages.push('Guild successfully updated.');
  177. }
  178. msg.client.shard.broadcastEval( `delete global.patreons['${guild}']` );
  179. }, dberror => {
  180. console.log( '- Error while updating the guild: ' + dberror );
  181. messages.push('Error while updating the guild: ' + dberror);
  182. return Promise.reject();
  183. } ).then( () => {
  184. return client.query( 'DELETE FROM discord WHERE guild = $1 AND channel LIKE $2 RETURNING channel, wiki', [guild, '#%'] ).then( ({rows}) => {
  185. if ( rows.length ) {
  186. console.log( '- Channel categories successfully deleted.' );
  187. messages.push('Channel categories successfully deleted.');
  188. return msg.client.shard.broadcastEval( `if ( this.guilds.cache.has('${guild}') ) {
  189. let rows = ${JSON.stringify(rows)};
  190. this.guilds.cache.get('${guild}').channels.cache.filter( channel => {
  191. return ( channel.isGuild() && rows.some( row => {
  192. return ( row.channel === '#' + channel.parentID );
  193. } ) );
  194. } ).map( channel => {
  195. return {
  196. id: channel.id,
  197. wiki: rows.find( row => {
  198. return ( row.channel === '#' + channel.parentID );
  199. } ).wiki
  200. };
  201. } )
  202. }`, Discord.ShardClientUtil.shardIDForGuildID(guild, msg.client.shard.count) ).then( channels => {
  203. if ( channels.length ) return Promise.all(channels.map( channel => {
  204. return client.query( 'INSERT INTO discord(wiki, guild, channel, lang, role, inline, prefix) VALUES($1, $2, $3, $4, $5, $6, $7)', [channel.wiki, guild, channel.id, row.lang, row.role, row.inline, process.env.prefix] ).catch( dberror => {
  205. if ( dberror.message !== 'duplicate key value violates unique constraint "discord_guild_channel_key"' ) {
  206. console.log( '- Error while adding category settings to channels: ' + dberror );
  207. }
  208. } );
  209. } ));
  210. }, error => {
  211. console.log( '- Error while getting the channels in categories: ' + error );
  212. messages.push('Error while getting the channels in categories: ' + error);
  213. } );
  214. }
  215. }, dberror => {
  216. console.log( '- Error while deleting the channel categories: ' + dberror );
  217. messages.push('Error while deleting the channel categories: ' + dberror);
  218. return Promise.reject();
  219. } );
  220. } );
  221. }, dberror => {
  222. console.log( '- Error while getting the guild: ' + dberror );
  223. messages.push('Error while getting the guild: ' + dberror);
  224. return Promise.reject();
  225. } ).then( () => {
  226. return client.query( 'SELECT configid FROM verification WHERE guild = $1 ORDER BY configid ASC OFFSET $2', [guild, verificationLimit.default] ).then( ({rows}) => {
  227. if ( rows.length ) {
  228. return client.query( 'DELETE FROM verification WHERE guild = $1 AND configid IN (' + rows.map( (row, i) => '$' + ( i + 2 ) ).join(', ') + ')', [guild, ...rows.map( row => row.configid )] ).then( () => {
  229. console.log( '- Verifications successfully deleted.' );
  230. messages.push('Verifications successfully deleted.');
  231. }, dberror => {
  232. console.log( '- Error while deleting the verifications: ' + dberror );
  233. messages.push('Error while deleting the verifications: ' + dberror);
  234. } );
  235. }
  236. }, dberror => {
  237. console.log( '- Error while getting the verifications: ' + dberror );
  238. messages.push('Error while getting the verifications: ' + dberror);
  239. } );
  240. } ).then( () => {
  241. return client.query( 'SELECT webhook FROM rcgcdw WHERE guild = $1 ORDER BY configid ASC OFFSET $2', [guild, rcgcdwLimit.default] ).then( ({rows}) => {
  242. if ( rows.length ) {
  243. return client.query( 'DELETE FROM rcgcdw WHERE webhook IN (' + rows.map( (row, i) => '$' + ( i + 1 ) ).join(', ') + ')', rows.map( row => row.webhook ) ).then( () => {
  244. console.log( '- RcGcDw successfully deleted.' );
  245. messages.push('RcGcDw successfully deleted.');
  246. rows.forEach( row => msg.client.fetchWebhook(...row.webhook.split('/')).then( webhook => {
  247. webhook.delete('Removed extra recent changes webhook').catch(log_error);
  248. }, log_error ) );
  249. }, dberror => {
  250. console.log( '- Error while deleting the RcGcDw: ' + dberror );
  251. messages.push('Error while deleting the RcGcDw: ' + dberror);
  252. } );
  253. }
  254. }, dberror => {
  255. console.log( '- Error while getting the RcGcDw: ' + dberror );
  256. messages.push('Error while getting the RcGcDw: ' + dberror);
  257. } );
  258. } ).then( () => {
  259. return client.query( 'UPDATE rcgcdw SET display = $1 WHERE guild = $2 AND display > $1', [rcgcdwLimit.display, guild] ).then( () => {
  260. console.log( '- RcGcDw successfully updated.' );
  261. messages.push('RcGcDw successfully updated.');
  262. }, dberror => {
  263. console.log( '- Error while updating the RcGcDw: ' + dberror );
  264. messages.push('Error while updating the RcGcDw: ' + dberror);
  265. } );
  266. } ).then( () => {
  267. if ( !messages.length ) messages.push('No settings found that had to be removed.');
  268. return messages;
  269. }, error => {
  270. if ( error ) {
  271. console.log( '- Error while removing the patreon features: ' + error );
  272. messages.push('Error while removing the patreon features: ' + error);
  273. }
  274. if ( !messages.length ) messages.push('No settings found that had to be removed.');
  275. return messages;
  276. } ).finally( () => {
  277. client.release();
  278. } );
  279. }, dberror => {
  280. console.log( '- Error while connecting to the database client: ' + dberror );
  281. return 'Error while connecting to the database client: ' + dberror;
  282. } );
  283. }
  284. /**
  285. * Removes the settings for deleted guilds and channels.
  286. * @param {Discord.Message} msg - The Discord message.
  287. */
  288. function removeSettings(msg) {
  289. if ( !( msg instanceof Discord.Message ) ) return 'removeSettings(msg) – No message provided!';
  290. return db.connect().then( client => {
  291. var messages = [];
  292. return msg.client.shard.broadcastEval( `[
  293. [...this.guilds.cache.keys()],
  294. this.channels.cache.filter( channel => {
  295. return ( channel.isGuild() || ( channel.type === 'category' && global.patreons.hasOwnProperty(channel.guild.id) ) );
  296. } ).map( channel => ( channel.type === 'category' ? '#' : '' ) + channel.id )
  297. ]` ).then( results => {
  298. var all_guilds = results.map( result => result[0] ).reduce( (acc, val) => acc.concat(val), [] );
  299. var all_channels = results.map( result => result[1] ).reduce( (acc, val) => acc.concat(val), [] );
  300. var guilds = [];
  301. var channels = [];
  302. return client.query( 'SELECT guild, channel FROM discord' ).then( ({rows}) => {
  303. return rows.forEach( row => {
  304. if ( !all_guilds.includes(row.guild) ) {
  305. if ( !row.channel ) {
  306. if ( patreons.hasOwnProperty(row.guild) || voice.hasOwnProperty(row.guild) ) {
  307. msg.client.shard.broadcastEval( `delete global.patreons['${row.guild}'];
  308. delete global.voice['${row.guild}'];` );
  309. }
  310. return guilds.push(row.guild);
  311. }
  312. }
  313. else if ( row.channel && !all_channels.includes(row.channel) ) {
  314. return channels.push(row.channel);
  315. }
  316. } );
  317. }, dberror => {
  318. console.log( '- Error while getting the settings: ' + dberror );
  319. messages.push('Error while getting the settings: ' + dberror);
  320. } ).then( () => {
  321. if ( guilds.length ) {
  322. return client.query( 'DELETE FROM discord WHERE main IN (' + guilds.map( (guild, i) => '$' + ( i + 1 ) ).join(', ') + ')', guilds ).then( ({rowCount}) => {
  323. console.log( '- Guilds successfully removed: ' + rowCount );
  324. messages.push('Guilds successfully removed: ' + rowCount);
  325. }, dberror => {
  326. console.log( '- Error while removing the guilds: ' + dberror );
  327. messages.push('Error while removing the guilds: ' + dberror);
  328. } );
  329. }
  330. } ).then( () => {
  331. if ( channels.length ) {
  332. return client.query( 'DELETE FROM discord WHERE channel IN (' + channels.map( (channel, i) => '$' + ( i + 1 ) ).join(', ') + ')', channels ).then( ({rowCount}) => {
  333. console.log( '- Channels successfully removed: ' + rowCount );
  334. messages.push('Channels successfully removed: ' + rowCount);
  335. }, dberror => {
  336. console.log( '- Error while removing the channels: ' + dberror );
  337. messages.push('Error while removing the channels: ' + dberror);
  338. } );
  339. }
  340. } );
  341. } ).then( () => {
  342. if ( !messages.length ) messages.push('No settings found that had to be removed.');
  343. return messages;
  344. }, error => {
  345. if ( error ) {
  346. console.log( '- Error while removing the settings: ' + error );
  347. messages.push('Error while removing the settings: ' + error);
  348. }
  349. if ( !messages.length ) messages.push('No settings found that had to be removed.');
  350. return messages;
  351. } ).finally( () => {
  352. client.release();
  353. } );
  354. }, dberror => {
  355. console.log( '- Error while connecting to the database client: ' + dberror );
  356. return 'Error while connecting to the database client: ' + dberror;
  357. } );
  358. }
  359. module.exports = {
  360. name: 'eval',
  361. everyone: false,
  362. pause: false,
  363. owner: true,
  364. run: cmd_eval
  365. };