eval.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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 new Promise( function (resolve, reject) {
  45. db.all( sql, sqlargs, (error, rows) => {
  46. if (error) reject(error);
  47. resolve(rows);
  48. } );
  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' + ( wiki.isFandom() ? '|variables' : '' ) + '&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' + ( wiki.isFandom() ? '|variables' : '' ) + '&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?.query?.recentchanges ) {
  69. return response.statusCode + ': Error while getting the recent changes: ' + body?.error?.info;
  70. }
  71. wiki.updateWiki(body.query.general);
  72. var result = {
  73. wiki: wiki.href,
  74. activity: [],
  75. rcid: 0,
  76. wikiid: ( body.query.variables?.find?.( variable => variable?.id === 'wgCityId' )?.['*'] || null ),
  77. postid: null
  78. }
  79. var rc = body.query.recentchanges;
  80. if ( rc.length ) {
  81. result.rcid = rc[0].rcid;
  82. let text = '';
  83. let len = ( Date.parse(rc[0].timestamp) - Date.parse(rc[rc.length - 1].timestamp) ) / 60000;
  84. len = Math.round(len);
  85. let rdays = ( len / 1440 );
  86. let days = Math.floor(rdays);
  87. if ( days > 0 ) {
  88. if ( days === 1 ) text += ` ${days} day`;
  89. else text += ` ${days} days`;
  90. }
  91. let rhours = ( rdays - days ) * 24;
  92. let hours = Math.floor(rhours);
  93. if ( hours > 0 ) {
  94. if ( text.length ) text += ' and';
  95. if ( hours === 1 ) text += ` ${hours} hour`;
  96. else text += ` ${hours} hours`;
  97. }
  98. let rminutes = ( rhours - hours ) * 60;
  99. let minutes = Math.round(rminutes);
  100. if ( minutes > 0 ) {
  101. if ( text.length ) text += ' and';
  102. if ( minutes === 1 ) text += ` ${minutes} minute`;
  103. else text += ` ${minutes} minutes`;
  104. }
  105. result.activity.push(`${rc.length} edits in${text}`);
  106. }
  107. return Promise.all([
  108. database('SELECT guild, lang, display, rcid, wikiid, postid FROM rcgcdw WHERE wiki = ?', [result.wiki]).then( rows => {
  109. result.rcgcdb = rows;
  110. }, error => {
  111. result.rcgcdb = error.toString();
  112. } ),
  113. ( result.wikiid ? got.get( 'https://services.fandom.com/discussion/' + result.wikiid + '/posts?limit=100&format=json&cache=' + Date.now(), {
  114. headers: {
  115. Accept: 'application/hal+json'
  116. }
  117. } ).then( dsresponse => {
  118. var dsbody = dsresponse.body;
  119. if ( dsresponse.statusCode !== 200 || !dsbody || dsbody.title ) {
  120. if ( dsbody?.title !== 'site doesn\'t exists' ) result.postid = dsresponse.statusCode + ': Error while getting the discussions: ' + dsbody?.title;
  121. return;
  122. }
  123. var posts = dsbody._embedded?.['doc:posts'];
  124. result.postid = ( posts[0]?.id || 0 );
  125. if ( posts?.length ) {
  126. let text = '';
  127. let len = ( posts[0].creationDate.epochSecond - posts[posts.length - 1].creationDate.epochSecond ) / 60;
  128. len = Math.round(len);
  129. let rdays = ( len / 1440 );
  130. let days = Math.floor(rdays);
  131. if ( days > 0 ) {
  132. if ( days === 1 ) text += ` ${days} day`;
  133. else text += ` ${days} days`;
  134. }
  135. let rhours = ( rdays - days ) * 24;
  136. let hours = Math.floor(rhours);
  137. if ( hours > 0 ) {
  138. if ( text.length ) text += ' and';
  139. if ( hours === 1 ) text += ` ${hours} hour`;
  140. else text += ` ${hours} hours`;
  141. }
  142. let rminutes = ( rhours - hours ) * 60;
  143. let minutes = Math.round(rminutes);
  144. if ( minutes > 0 ) {
  145. if ( text.length ) text += ' and';
  146. if ( minutes === 1 ) text += ` ${minutes} minute`;
  147. else text += ` ${minutes} minutes`;
  148. }
  149. result.activity.push(`${posts.length} posts in${text}`);
  150. }
  151. }, error => {
  152. result.postid = 'Error while getting the discussions: ' + error;
  153. } ) : null )
  154. ]).then( () => {
  155. return result;
  156. } );
  157. }, error => {
  158. return 'Error while getting the recent changes: ' + error;
  159. } );
  160. }
  161. /**
  162. * Update the list of all sites.
  163. * @returns {Promise<Object[]>}
  164. */
  165. function updateAllSites() {
  166. return require('../util/allSites.js').update();
  167. }
  168. /**
  169. * Removes the patreon features for a guild.
  170. * @param {String} guild - The guild ID.
  171. * @param {Discord.Message} msg - The Discord message.
  172. */
  173. function removePatreons(guild, msg) {
  174. try {
  175. if ( !( typeof guild === 'string' || msg instanceof Discord.Message ) ) {
  176. return 'removePatreons(guild, msg) – No guild or message provided!';
  177. }
  178. db.get( 'SELECT lang, inline FROM discord WHERE guild = ? AND channel IS NULL', [guild], (dberror, row) => {
  179. try {
  180. if ( dberror ) {
  181. console.log( '- Error while getting the guild: ' + dberror );
  182. msg.replyMsg( 'I got an error while searching for the guild!', {}, true );
  183. return dberror;
  184. }
  185. if ( !row ) {
  186. msg.replyMsg( 'that guild doesn\'t exist!', {}, true );
  187. return;
  188. }
  189. db.run( 'UPDATE discord SET lang = ?, inline = ?, prefix = ?, patreon = NULL WHERE guild = ?', [row.lang, row.inline, process.env.prefix, guild], function (error) {
  190. try {
  191. if ( error ) {
  192. console.log( '- Error while updating the guild: ' + error );
  193. msg.replyMsg( 'I got an error while updating the guild!', {}, true );
  194. return error;
  195. }
  196. console.log( '- Guild successfully updated.' );
  197. msg.client.shard.broadcastEval( `delete global.patreons['${guild}']`);
  198. msg.replyMsg( 'the patreon features are now disabled on that guild.', {}, true );
  199. }
  200. catch ( tryerror ) {
  201. console.log( '- Error while removing the patreon features: ' + tryerror );
  202. }
  203. } );
  204. }
  205. catch ( tryerror ) {
  206. console.log( '- Error while removing the patreon features: ' + tryerror );
  207. }
  208. } );
  209. db.all( 'SELECT configid FROM verification WHERE guild = ? ORDER BY configid ASC', [guild], (dberror, rows) => {
  210. if ( dberror ) {
  211. console.log( '- Error while getting the verifications: ' + dberror );
  212. return dberror;
  213. }
  214. var ids = rows.slice(verificationLimit.default).map( row => row.configid );
  215. if ( ids.length ) db.run( 'DELETE FROM verification WHERE guild = ? AND configid IN (' + ids.map( configid => '?' ).join(', ') + ')', [guild, ...ids], function (error) {
  216. if ( error ) {
  217. console.log( '- Error while deleting the verifications: ' + error );
  218. return error;
  219. }
  220. console.log( '- Verifications successfully deleted.' );
  221. } );
  222. } );
  223. db.all( 'SELECT webhook FROM rcgcdw WHERE guild = ? ORDER BY configid ASC', [guild], (dberror, rows) => {
  224. if ( dberror ) {
  225. console.log( '- Error while getting the RcGcDw: ' + dberror );
  226. return dberror;
  227. }
  228. var webhooks = rows.slice(rcgcdwLimit.default).map( row => row.webhook );
  229. if ( webhooks.length ) db.run( 'DELETE FROM rcgcdw WHERE webhook IN (' + webhooks.map( webhook => '?' ).join(', ') + ')', webhooks, function (error) {
  230. if ( error ) {
  231. console.log( '- Error while deleting the RcGcDw: ' + error );
  232. return error;
  233. }
  234. console.log( '- RcGcDw successfully deleted.' );
  235. webhooks.forEach( hook => guild.client.fetchWebhook(...hook.split('/')).then( webhook => {
  236. webhook.delete('Removed extra recent changes webhook').catch(log_error);
  237. }, log_error ) );
  238. } );
  239. } );
  240. db.run( 'UPDATE rcgcdw SET display = ? WHERE guild = ? AND display > ?', [rcgcdwLimit.display, guild, rcgcdwLimit.display], function (dberror) {
  241. if ( dberror ) {
  242. console.log( '- Error while updating the RcGcDw: ' + dberror );
  243. return dberror;
  244. }
  245. console.log( '- RcGcDw successfully updated.' );
  246. } );
  247. }
  248. catch ( tryerror ) {
  249. console.log( '- Error while removing the patreon features: ' + tryerror );
  250. return 'removePatreons(guild, msg) – Error while removing the patreon features: ' + tryerror;
  251. }
  252. }
  253. /**
  254. * Removes the settings for deleted guilds and channels.
  255. * @param {Discord.Message} msg - The Discord message.
  256. */
  257. function removeSettings(msg) {
  258. if ( !msg ) return 'removeSettings(msg) – No message provided!';
  259. try {
  260. msg.client.shard.broadcastEval( `[[...this.guilds.cache.keys()], [...this.channels.cache.filter( channel => channel.isGuild() ).keys()]]` ).then( results => {
  261. var all_guilds = results.map( result => result[0] ).reduce( (acc, val) => acc.concat(val), [] );
  262. var all_channels = results.map( result => result[1] ).reduce( (acc, val) => acc.concat(val), [] );
  263. var guilds = [];
  264. var channels = [];
  265. db.each( 'SELECT guild, channel FROM discord', [], (dberror, row) => {
  266. if ( dberror ) {
  267. console.log( '- Error while getting the setting: ' + dberror );
  268. return dberror;
  269. }
  270. if ( !row.channel && !all_guilds.includes(row.guild) ) {
  271. if ( row.guild in patreons || row.guild in voice ) {
  272. msg.client.shard.broadcastEval( `delete global.patreons['${row.guild}'];
  273. delete global.voice['${row.guild}'];` );
  274. }
  275. return guilds.push(row.guild);
  276. }
  277. if ( row.channel && all_guilds.includes(row.guild) && !all_channels.includes(row.channel) ) return channels.push(row.channel);
  278. }, (error) => {
  279. if ( error ) {
  280. console.log( '- Error while getting the settings: ' + error );
  281. msg.replyMsg( 'I got an error while getting the settings!', {}, true );
  282. return error;
  283. }
  284. if ( guilds.length ) {
  285. db.run( 'DELETE FROM discord WHERE main IN (' + guilds.map( guild => '?' ).join(', ') + ')', guilds, function (dberror) {
  286. if ( dberror ) {
  287. console.log( '- Error while removing the guilds: ' + dberror );
  288. msg.replyMsg( 'I got an error while removing the guilds!', {}, true );
  289. return dberror;
  290. }
  291. console.log( '- Guilds successfully removed.' );
  292. } );
  293. }
  294. if ( channels.length ) db.run( 'DELETE FROM discord WHERE channel IN (' + channels.map( channel => '?' ).join(', ') + ')', channels, function (dberror) {
  295. if ( dberror ) {
  296. console.log( '- Error while removing the channels: ' + dberror );
  297. msg.replyMsg( 'I got an error while removing the channels!', {}, true );
  298. return dberror;
  299. }
  300. console.log( '- Channels successfully removed.' );
  301. } );
  302. if ( !guilds.length && !channels.length ) console.log( '- Settings successfully removed.' );
  303. } );
  304. } );
  305. }
  306. catch ( tryerror ) {
  307. console.log( '- Error while removing the settings: ' + tryerror );
  308. return 'removeSettings(msg) – Error while removing the settings: ' + tryerror;
  309. }
  310. }
  311. module.exports = {
  312. name: 'eval',
  313. everyone: false,
  314. pause: false,
  315. owner: true,
  316. run: cmd_eval
  317. };