eval.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. newMessage(msg, lang, wiki, patreons[msg.guild.id], msg.noInline, cmdline);
  34. return cmdline;
  35. }
  36. }
  37. /**
  38. * Runs database queries.
  39. * @param {String} sql - The SQL command.
  40. * @param {String[]} [sqlargs] - The command arguments.
  41. */
  42. function database(sql, sqlargs = []) {
  43. return new Promise( function (resolve, reject) {
  44. db.all( sql, sqlargs, (error, rows) => {
  45. if (error) reject(error);
  46. resolve(rows);
  47. } );
  48. } );
  49. }
  50. /**
  51. * Checks a wiki and it's recent changes webhooks.
  52. * @param {Wiki} wiki - The wiki to check.
  53. */
  54. function checkWiki(wiki) {
  55. wiki = Wiki.fromInput(wiki);
  56. 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&rclimit=1&format=json' ).then( response => {
  57. if ( response.statusCode === 404 && typeof response.body === 'string' ) {
  58. let api = cheerio.load(response.body)('head link[rel="EditURI"]').prop('href');
  59. if ( api ) {
  60. wiki = new Wiki(api.split('api.php?')[0], wiki);
  61. 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&rclimit=1&format=json' );
  62. }
  63. }
  64. return response;
  65. } ).then( response => {
  66. var body = response.body;
  67. if ( response.statusCode !== 200 || !body?.query?.recentchanges ) {
  68. return response.statusCode + ': Error while getting the recent changes: ' + body?.error?.info;
  69. }
  70. wiki.updateWiki(body.query.general);
  71. var result = {
  72. wiki: wiki.href,
  73. rcid: ( body.query.recentchanges[0]?.rcid || 0 ),
  74. wikiid: ( body.query.variables?.find?.( variable => variable?.id === 'wgCityId' )?.['*'] || null ),
  75. postid: null
  76. }
  77. return Promise.all([
  78. database('SELECT guild, lang, display, rcid, wikiid, postid FROM rcgcdw WHERE wiki = ?', [result.wiki]).then( rows => {
  79. result.rcgcdb = rows;
  80. }, error => {
  81. result.rcgcdb = error.toString();
  82. } ),
  83. ( result.wikiid ? got.get( 'https://services.fandom.com/discussion/' + result.wikiid + '/posts?limit=1&format=json&cache=' + Date.now(), {
  84. headers: {
  85. Accept: 'application/hal+json'
  86. }
  87. } ).then( dsresponse => {
  88. var dsbody = dsresponse.body;
  89. if ( dsresponse.statusCode !== 200 || !dsbody || dsbody.title ) {
  90. if ( dsbody?.title !== 'site doesn\'t exists' ) result.postid = dsresponse.statusCode + ': Error while getting the discussions: ' + dsbody?.title;
  91. }
  92. else result.postid = ( dsbody._embedded?.['doc:posts']?.[0]?.id || 0 );
  93. }, error => {
  94. result.postid = 'Error while getting the discussions: ' + error;
  95. } ) : null )
  96. ]).then( () => {
  97. return result;
  98. } );
  99. }, error => {
  100. return 'Error while getting the recent changes: ' + error;
  101. } );
  102. }
  103. /**
  104. * Update the list of all sites.
  105. * @returns {Promise<Object[]>}
  106. */
  107. function updateAllSites() {
  108. return require('../util/allSites.js').update();
  109. }
  110. /**
  111. * Removes the patreon features for a guild.
  112. * @param {String} guild - The guild ID.
  113. * @param {Discord.Message} msg - The Discord message.
  114. */
  115. function removePatreons(guild, msg) {
  116. try {
  117. if ( !( typeof guild === 'string' || msg instanceof Discord.Message ) ) {
  118. return 'removePatreons(guild, msg) – No guild or message provided!';
  119. }
  120. db.get( 'SELECT lang, inline FROM discord WHERE guild = ? AND channel IS NULL', [guild], (dberror, row) => {
  121. try {
  122. if ( dberror ) {
  123. console.log( '- Error while getting the guild: ' + dberror );
  124. msg.replyMsg( 'I got an error while searching for the guild!', {}, true );
  125. return dberror;
  126. }
  127. if ( !row ) {
  128. msg.replyMsg( 'that guild doesn\'t exist!', {}, true );
  129. return;
  130. }
  131. db.run( 'UPDATE discord SET lang = ?, inline = ?, prefix = ?, patreon = NULL WHERE guild = ?', [row.lang, row.inline, process.env.prefix, guild], function (error) {
  132. try {
  133. if ( error ) {
  134. console.log( '- Error while updating the guild: ' + error );
  135. msg.replyMsg( 'I got an error while updating the guild!', {}, true );
  136. return error;
  137. }
  138. console.log( '- Guild successfully updated.' );
  139. msg.client.shard.broadcastEval( `delete global.patreons['${guild}']`);
  140. msg.replyMsg( 'the patreon features are now disabled on that guild.', {}, true );
  141. }
  142. catch ( tryerror ) {
  143. console.log( '- Error while removing the patreon features: ' + tryerror );
  144. }
  145. } );
  146. }
  147. catch ( tryerror ) {
  148. console.log( '- Error while removing the patreon features: ' + tryerror );
  149. }
  150. } );
  151. db.all( 'SELECT configid FROM verification WHERE guild = ? ORDER BY configid ASC', [guild], (dberror, rows) => {
  152. if ( dberror ) {
  153. console.log( '- Error while getting the verifications: ' + dberror );
  154. return dberror;
  155. }
  156. var ids = rows.slice(verificationLimit.default).map( row => row.configid );
  157. if ( ids.length ) db.run( 'DELETE FROM verification WHERE guild = ? AND configid IN (' + ids.map( configid => '?' ).join(', ') + ')', [guild, ...ids], function (error) {
  158. if ( error ) {
  159. console.log( '- Error while deleting the verifications: ' + error );
  160. return error;
  161. }
  162. console.log( '- Verifications successfully deleted.' );
  163. } );
  164. } );
  165. db.all( 'SELECT webhook FROM rcgcdw WHERE guild = ? ORDER BY configid ASC', [guild], (dberror, rows) => {
  166. if ( dberror ) {
  167. console.log( '- Error while getting the RcGcDw: ' + dberror );
  168. return dberror;
  169. }
  170. var webhooks = rows.slice(rcgcdwLimit.default).map( row => row.webhook );
  171. if ( webhooks.length ) db.run( 'DELETE FROM rcgcdw WHERE webhook IN (' + webhooks.map( webhook => '?' ).join(', ') + ')', webhooks, function (error) {
  172. if ( error ) {
  173. console.log( '- Error while deleting the RcGcDw: ' + error );
  174. return error;
  175. }
  176. console.log( '- RcGcDw successfully deleted.' );
  177. webhooks.forEach( hook => guild.client.fetchWebhook(...hook.split('/')).then( webhook => {
  178. webhook.delete('Removed extra recent changes webhook').catch(log_error);
  179. }, log_error ) );
  180. } );
  181. } );
  182. db.run( 'UPDATE rcgcdw SET display = ? WHERE guild = ? AND display > ?', [rcgcdwLimit.display, guild, rcgcdwLimit.display], function (dberror) {
  183. if ( dberror ) {
  184. console.log( '- Error while updating the RcGcDw: ' + dberror );
  185. return dberror;
  186. }
  187. console.log( '- RcGcDw successfully updated.' );
  188. } );
  189. }
  190. catch ( tryerror ) {
  191. console.log( '- Error while removing the patreon features: ' + tryerror );
  192. return 'removePatreons(guild, msg) – Error while removing the patreon features: ' + tryerror;
  193. }
  194. }
  195. /**
  196. * Removes the settings for deleted guilds and channels.
  197. * @param {Discord.Message} msg - The Discord message.
  198. */
  199. function removeSettings(msg) {
  200. if ( !msg ) return 'removeSettings(msg) – No message provided!';
  201. try {
  202. msg.client.shard.broadcastEval( `[[...this.guilds.cache.keys()], [...this.channels.cache.filter( channel => channel.isGuild() ).keys()]]` ).then( results => {
  203. var all_guilds = results.map( result => result[0] ).reduce( (acc, val) => acc.concat(val), [] );
  204. var all_channels = results.map( result => result[1] ).reduce( (acc, val) => acc.concat(val), [] );
  205. var guilds = [];
  206. var channels = [];
  207. db.each( 'SELECT guild, channel FROM discord', [], (dberror, row) => {
  208. if ( dberror ) {
  209. console.log( '- Error while getting the setting: ' + dberror );
  210. return dberror;
  211. }
  212. if ( !row.channel && !all_guilds.includes(row.guild) ) {
  213. if ( row.guild in patreons ) msg.client.shard.broadcastEval( `delete global.patreons['${row.guild}']` );
  214. if ( row.guild in voice ) delete voice[row.guild];
  215. return guilds.push(row.guild);
  216. }
  217. if ( row.channel && all_guilds.includes(row.guild) && !all_channels.includes(row.channel) ) return channels.push(row.channel);
  218. }, (error) => {
  219. if ( error ) {
  220. console.log( '- Error while getting the settings: ' + error );
  221. msg.replyMsg( 'I got an error while getting the settings!', {}, true );
  222. return error;
  223. }
  224. if ( guilds.length ) {
  225. db.run( 'DELETE FROM discord WHERE guild IN (' + guilds.map( guild => '?' ).join(', ') + ')', guilds, function (dberror) {
  226. if ( dberror ) {
  227. console.log( '- Error while removing the guilds: ' + dberror );
  228. msg.replyMsg( 'I got an error while removing the guilds!', {}, true );
  229. return dberror;
  230. }
  231. console.log( '- Guilds successfully removed.' );
  232. } );
  233. db.run( 'DELETE FROM verification WHERE guild IN (' + guilds.map( guild => '?' ).join(', ') + ')', guilds, function (dberror) {
  234. if ( dberror ) {
  235. console.log( '- Error while removing the verifications: ' + dberror );
  236. msg.replyMsg( 'I got an error while removing the verifications!', {}, true );
  237. return dberror;
  238. }
  239. console.log( '- Verifications successfully removed.' );
  240. } );
  241. db.run( 'DELETE FROM rcgcdw WHERE guild IN (' + guilds.map( guild => '?' ).join(', ') + ')', guilds, function (dberror) {
  242. if ( dberror ) {
  243. console.log( '- Error while removing the RcGcDw: ' + dberror );
  244. msg.replyMsg( 'I got an error while removing the RcGcDw!', {}, true );
  245. return dberror;
  246. }
  247. console.log( '- Verifications successfully removed.' );
  248. } );
  249. }
  250. if ( channels.length ) db.run( 'DELETE FROM discord WHERE channel IN (' + channels.map( channel => '?' ).join(', ') + ')', channels, function (dberror) {
  251. if ( dberror ) {
  252. console.log( '- Error while removing the channels: ' + dberror );
  253. msg.replyMsg( 'I got an error while removing the channels!', {}, true );
  254. return dberror;
  255. }
  256. console.log( '- Channels successfully removed.' );
  257. } );
  258. if ( !guilds.length && !channels.length ) console.log( '- Settings successfully removed.' );
  259. } );
  260. } );
  261. }
  262. catch ( tryerror ) {
  263. console.log( '- Error while removing the settings: ' + tryerror );
  264. return 'removeSettings(msg) – Error while removing the settings: ' + tryerror;
  265. }
  266. }
  267. module.exports = {
  268. name: 'eval',
  269. everyone: false,
  270. pause: false,
  271. owner: true,
  272. run: cmd_eval
  273. };