eval.js 16 KB

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