eval.js 16 KB

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