rcscript.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. const cheerio = require('cheerio');
  2. const {Util, MessageActionRow, MessageButton, Permissions: {FLAGS}} = require('discord.js');
  3. const help_setup = require('../functions/helpsetup.js');
  4. const {limit: {rcgcdw: rcgcdwLimit}} = require('../util/default.json');
  5. const {got} = require('../util/functions.js');
  6. const Lang = require('../util/i18n.js');
  7. const allLangs = Lang.allLangs(true);
  8. const Wiki = require('../util/wiki.js');
  9. var db = require('../util/database.js');
  10. const fs = require('fs');
  11. const rcscriptExists = ( isDebug || fs.existsSync('./RcGcDb/start.py') );
  12. const display_types = [
  13. 'compact',
  14. 'embed',
  15. 'image',
  16. 'diff'
  17. ];
  18. /**
  19. * Processes the "rcscript" command.
  20. * @param {Lang} lang - The user language.
  21. * @param {import('discord.js').Message} msg - The Discord message.
  22. * @param {String[]} args - The command arguments.
  23. * @param {String} line - The command as plain text.
  24. * @param {Wiki} wiki - The wiki for the message.
  25. */
  26. function cmd_rcscript(lang, msg, args, line, wiki) {
  27. if ( args[0] === 'block' && msg.isOwner() ) return blocklist(msg, args.slice(1));
  28. if ( !msg.isAdmin() ) return msg.reactEmoji('❌');
  29. if ( msg.defaultSettings ) return help_setup(lang, msg);
  30. db.query( 'SELECT configid, webhook, wiki, lang, display, rcid, postid FROM rcgcdw WHERE guild = $1 ORDER BY configid ASC', [msg.guildId] ).then( ({rows}) => {
  31. var prefix = process.env.prefix;
  32. var limit = rcgcdwLimit.default;
  33. var display = display_types.slice(0, rcgcdwLimit.display + 1);
  34. if ( patreons[msg.guildId] ) {
  35. prefix = patreons[msg.guildId];
  36. limit = rcgcdwLimit.patreon;
  37. display = display_types.slice();
  38. }
  39. var button = null;
  40. var components = [];
  41. if ( process.env.dashboard ) {
  42. button = new MessageButton().setLabel(lang.get('settings.button')).setEmoji('<:wikibot:588723255972593672>').setStyle('LINK').setURL(new URL(`/guild/${msg.guildId}/rcscript`, process.env.dashboard).href);
  43. components.push(new MessageActionRow().addComponents(button));
  44. }
  45. if ( args[0] === 'add' ) {
  46. if ( !msg.channel.permissionsFor(msg.client.user).has(FLAGS.MANAGE_WEBHOOKS) ) {
  47. console.log( msg.guildId + ': Missing permissions - MANAGE_WEBHOOKS' );
  48. return msg.replyMsg( lang.get('general.missingperm') + ' `MANAGE_WEBHOOKS`' );
  49. }
  50. if ( !( msg.channel.permissionsFor(msg.member).has(FLAGS.MANAGE_WEBHOOKS) || ( msg.isOwner() && msg.evalUsed ) ) ) {
  51. return msg.replyMsg( lang.get('rcscript.noadmin') );
  52. }
  53. if ( rows.length >= limit ) return msg.replyMsg( lang.get('rcscript.max_entries'), true );
  54. if ( process.env.READONLY ) return msg.replyMsg( lang.get('general.readonly') + '\n' + process.env.invite, true );
  55. button?.setURL(new URL(`/guild/${msg.guildId}/rcscript/new`, button.url).href);
  56. var wikihelp = '\n`' + prefix + 'rcscript add ' + lang.get('rcscript.new_wiki') + '`\n' + lang.get('rcscript.help_wiki');
  57. var input = args.slice(1).join(' ').toLowerCase().trim().replace( /^<\s*(.*?)\s*>$/, '$1' );
  58. var wikinew = new Wiki(wiki);
  59. if ( input ) {
  60. wikinew = Wiki.fromInput(input);
  61. if ( !wikinew ) return msg.replyMsg( {content: lang.get('settings.wikiinvalid') + wikihelp, components}, true );
  62. }
  63. return msg.reactEmoji('⏳', true).then( reaction => got.get( wikinew + 'api.php?&action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw|recentchanges&amenableparser=true&siprop=general&titles=Special:RecentChanges&format=json', {
  64. responseType: 'text'
  65. } ).then( response => {
  66. try {
  67. response.body = JSON.parse(response.body);
  68. }
  69. catch (error) {
  70. if ( response.statusCode === 404 && typeof response.body === 'string' ) {
  71. let api = cheerio.load(response.body)('head link[rel="EditURI"]').prop('href');
  72. if ( api ) {
  73. wikinew = new Wiki(api.split('api.php?')[0], wikinew);
  74. return got.get( wikinew + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw|recentchanges&amenableparser=true&siprop=general&titles=Special:RecentChanges&format=json' );
  75. }
  76. }
  77. }
  78. return response;
  79. } ).then( response => {
  80. var body = response.body;
  81. if ( response.statusCode !== 200 || body?.batchcomplete === undefined || !body?.query?.allmessages || !body?.query?.general || !body?.query?.pages?.['-1'] ) {
  82. console.log( '- ' + response.statusCode + ': Error while testing the wiki: ' + body?.error?.info );
  83. if ( reaction ) reaction.removeEmoji();
  84. if ( body?.error?.info === 'You need read permission to use this module.' ) {
  85. return msg.replyMsg( {content: lang.get('settings.wikiinvalid_private') + wikihelp, components}, true );
  86. }
  87. msg.reactEmoji('nowiki', true);
  88. return msg.replyMsg( {content: lang.get('settings.wikiinvalid') + wikihelp, components}, true );
  89. }
  90. wikinew.updateWiki(body.query.general);
  91. if ( body.query.general.generator.replace( /^MediaWiki 1\.(\d\d).*$/, '$1' ) < 30 ) {
  92. if ( reaction ) reaction.removeEmoji();
  93. return msg.replyMsg( {content: lang.get('test.MediaWiki', 'MediaWiki 1.30', body.query.general.generator) + '\nhttps://www.mediawiki.org/wiki/MediaWiki_1.30', components}, true );
  94. }
  95. if ( body.query.allmessages[0]['*'] !== msg.guildId ) {
  96. if ( reaction ) reaction.removeEmoji();
  97. return msg.replyMsg( {content: lang.get('rcscript.sysmessage', 'MediaWiki:Custom-RcGcDw', msg.guildId) + '\n<' + wikinew.toLink('MediaWiki:Custom-RcGcDw', 'action=edit') + '>', components}, true );
  98. }
  99. return db.query( 'SELECT reason FROM blocklist WHERE wiki = $1', [wikinew.href] ).then( ({rows:[block]}) => {
  100. if ( block ) {
  101. console.log( '- This wiki is blocked: ' + block.reason );
  102. if ( reaction ) reaction.removeEmoji();
  103. return msg.replyMsg( {content: ( block.reason ? lang.get('rcscript.blocked_reason', block.reason) : lang.get('rcscript.blocked') ), components}, true );
  104. }
  105. if ( wikinew.isFandom(false) ) return got.get( wikinew + 'wikia.php?controller=DiscussionPost&method=getPosts&includeCounters=false&limit=1&format=json&cache=' + Date.now(), {
  106. headers: {
  107. Accept: 'application/hal+json'
  108. }
  109. } ).then( dsresponse => {
  110. var dsbody = dsresponse.body;
  111. if ( dsresponse.statusCode !== 200 || !dsbody || dsbody.status === 404 ) {
  112. if ( dsbody?.status !== 404 ) console.log( '- ' + dsresponse.statusCode + ': Error while checking for discussions: ' + dsbody?.title );
  113. return createWebhook();
  114. }
  115. return createWebhook(true);
  116. }, error => {
  117. console.log( '- Error while checking for discussions: ' + error );
  118. return createWebhook();
  119. } );
  120. return createWebhook();
  121. /**
  122. * Creates the webhook.
  123. * @param {Boolean} enableFeeds - If feeds based changes should be enabled.
  124. */
  125. function createWebhook(enableFeeds = false) {
  126. msg.channel.createWebhook( ( body.query.allmessages[1]['*'] || 'Recent changes' ), {
  127. avatar: msg.client.user.displayAvatarURL({format:'png',size:4096}),
  128. reason: lang.get('rcscript.audit_reason', wikinew.href)
  129. } ).then( webhook => {
  130. console.log( '- Webhook successfully created.' );
  131. var webhook_lang = new Lang(( allLangs.map[lang.lang] || allLangs.map[body.query.general.lang] ), 'rcscript.webhook');
  132. webhook.send( webhook_lang.get('created', body.query.general.sitename) + '\n<' + wikinew.toLink(body.query.pages['-1'].title) + ( enableFeeds ? '>\n<' + wikinew + 'f' : '' ) + '>' ).catch(log_error);
  133. var new_configid = 1;
  134. for ( let i of rows.map( row => row.configid ) ) {
  135. if ( new_configid === i ) new_configid++;
  136. else break;
  137. }
  138. db.query( 'INSERT INTO rcgcdw(guild, configid, webhook, wiki, lang, display, postid) VALUES($1, $2, $3, $4, $5, $6, $7)', [msg.guildId, new_configid, webhook.id + '/' + webhook.token, wikinew.href, webhook_lang.lang, ( msg.showEmbed() ? 1 : 0 ), ( enableFeeds ? null : '-1' )] ).then( () => {
  139. console.log( '- RcGcDw successfully added.' );
  140. if ( reaction ) reaction.removeEmoji();
  141. msg.replyMsg( {content: lang.get('rcscript.added') + ' <' + wikinew + '>\n`' + prefix + 'rcscript' + ( rows.length ? ' ' + new_configid : '' ) + '`', components}, true );
  142. }, dberror => {
  143. console.log( '- Error while adding the RcGcDw: ' + dberror );
  144. if ( reaction ) reaction.removeEmoji();
  145. msg.replyMsg( {content: lang.get('settings.save_failed'), components}, true );
  146. } );
  147. }, error => {
  148. console.log( '- Error while creating the webhook: ' + error );
  149. if ( reaction ) reaction.removeEmoji();
  150. msg.replyMsg( {content: lang.get('rcscript.webhook_failed'), components}, true );
  151. } );
  152. }
  153. }, dberror => {
  154. console.log( '- Error while getting the blocklist: ' + dberror );
  155. if ( reaction ) reaction.removeEmoji();
  156. msg.reactEmoji('error', true);
  157. } );
  158. }, error => {
  159. if ( reaction ) reaction.removeEmoji();
  160. if ( error.message?.startsWith( 'connect ECONNREFUSED ' ) || error.message?.startsWith( 'Hostname/IP does not match certificate\'s altnames: ' ) || error.message === 'certificate has expired' || error.message === 'self signed certificate' ) {
  161. console.log( '- Error while testing the wiki: No HTTPS' );
  162. return msg.replyMsg( {content: lang.get('settings.wikiinvalid_http') + wikihelp, components}, true );
  163. }
  164. console.log( '- Error while testing the wiki: ' + error );
  165. if ( error.message === `Timeout awaiting 'request' for ${got.defaults.options.timeout.request}ms` ) {
  166. return msg.replyMsg( {content: lang.get('settings.wikiinvalid_timeout') + wikihelp, components}, true );
  167. }
  168. msg.reactEmoji('nowiki', true);
  169. return msg.replyMsg( {content: lang.get('settings.wikiinvalid') + wikihelp, components}, true );
  170. } ) );
  171. }
  172. var selected_row = rows.find( row => row.configid.toString() === args[0] );
  173. if ( selected_row ) {
  174. args[0] = args[1];
  175. args[1] = args.slice(2).join(' ').toLowerCase().trim().replace( /^<\s*(.*)\s*>$/, '$1' );
  176. }
  177. else {
  178. args[1] = args.slice(1).join(' ').toLowerCase().trim().replace( /^<\s*(.*)\s*>$/, '$1' );
  179. if ( rows.length === 1 ) selected_row = rows[0];
  180. }
  181. if ( args[0] ) args[0] = args[0].toLowerCase();
  182. if ( selected_row ) {
  183. let webhook_lang = new Lang(selected_row.lang, 'rcscript.webhook');
  184. let cmd = prefix + 'rcscript' + ( rows.length === 1 ? '' : ' ' + selected_row.configid );
  185. if ( args[0] === 'delete' && !args[1] ) {
  186. if ( process.env.READONLY ) return msg.replyMsg( lang.get('general.readonly') + '\n' + process.env.invite, true );
  187. return msg.client.fetchWebhook(...selected_row.webhook.split('/')).then( webhook => {
  188. var channel = msg.guild.channels.cache.get(webhook.channelId);
  189. if ( !channel || !channel.permissionsFor(msg.member).has(FLAGS.MANAGE_WEBHOOKS) ) {
  190. return msg.replyMsg( lang.get('rcscript.noadmin') );
  191. }
  192. db.query( 'DELETE FROM rcgcdw WHERE webhook = $1', [selected_row.webhook] ).then( () => {
  193. console.log( '- RcGcDw successfully removed.' );
  194. webhook.send( webhook_lang.get('deleted') ).catch(log_error).finally( () => {
  195. webhook.delete(lang.get('rcscript.audit_reason_delete')).catch(log_error);
  196. } );
  197. msg.replyMsg( {content: lang.get('rcscript.deleted'), components}, true );
  198. }, dberror => {
  199. console.log( '- Error while removing the RcGcDw: ' + dberror );
  200. button?.setURL(new URL(`/guild/${msg.guildId}/rcscript/${selected_row.configid}`, button.url).href);
  201. msg.replyMsg( {content: lang.get('settings.save_failed'), components}, true );
  202. } );
  203. }, error => {
  204. log_error(error);
  205. if ( error.name === 'DiscordAPIError' && ['Unknown Webhook', 'Invalid Webhook Token'].includes( error.message ) ) {
  206. button?.setURL(new URL(`/guild/${msg.guildId}/rcscript/${selected_row.configid}`, button.url).href);
  207. return msg.replyMsg( {content: lang.get('settings.save_failed'), components}, true );
  208. }
  209. db.query( 'DELETE FROM rcgcdw WHERE webhook = $1', [selected_row.webhook] ).then( () => {
  210. console.log( '- RcGcDw successfully removed.' );
  211. msg.replyMsg( {content: lang.get('rcscript.deleted'), components}, true );
  212. }, dberror => {
  213. console.log( '- Error while removing the RcGcDw: ' + dberror );
  214. button?.setURL(new URL(`/guild/${msg.guildId}/rcscript/${selected_row.configid}`, button.url).href);
  215. msg.replyMsg( {content: lang.get('settings.save_failed'), components}, true );
  216. } );
  217. } );
  218. }
  219. button?.setURL(new URL(`/guild/${msg.guildId}/rcscript/${selected_row.configid}`, button.url).href);
  220. if ( args[0] === 'wiki' ) {
  221. if ( !args[1] ) {
  222. return msg.replyMsg( {content: lang.get('rcscript.current_wiki') + ' <' + selected_row.wiki + '>\n`' + cmd + ' wiki ' + lang.get('rcscript.new_wiki') + '`\n' + lang.get('rcscript.help_wiki'), components}, true );
  223. }
  224. if ( process.env.READONLY ) return msg.replyMsg( lang.get('general.readonly') + '\n' + process.env.invite, true );
  225. var wikihelp = '\n`' + cmd + ' wiki ' + lang.get('rcscript.new_wiki') + '`\n' + lang.get('rcscript.help_wiki');
  226. var wikinew = Wiki.fromInput(args[1]);
  227. if ( !wikinew ) return msg.replyMsg( {content: lang.get('settings.wikiinvalid') + wikihelp, components}, true );
  228. return msg.reactEmoji('⏳', true).then( reaction => got.get( wikinew + 'api.php?&action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw&amenableparser=true&siprop=general&titles=Special:RecentChanges&format=json', {
  229. responseType: 'text'
  230. } ).then( response => {
  231. try {
  232. response.body = JSON.parse(response.body);
  233. }
  234. catch (error) {
  235. if ( response.statusCode === 404 && typeof response.body === 'string' ) {
  236. let api = cheerio.load(response.body)('head link[rel="EditURI"]').prop('href');
  237. if ( api ) {
  238. wikinew = new Wiki(api.split('api.php?')[0], wikinew);
  239. return got.get( wikinew + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=custom-RcGcDw&amenableparser=true&siprop=general&titles=Special:RecentChanges&format=json' );
  240. }
  241. }
  242. }
  243. return response;
  244. } ).then( response => {
  245. var body = response.body;
  246. if ( response.statusCode !== 200 || body?.batchcomplete === undefined || !body?.query?.allmessages || !body?.query?.general || !body?.query?.pages?.['-1'] ) {
  247. console.log( '- ' + response.statusCode + ': Error while testing the wiki: ' + body?.error?.info );
  248. if ( reaction ) reaction.removeEmoji();
  249. if ( body?.error?.info === 'You need read permission to use this module.' ) {
  250. return msg.replyMsg( {content: lang.get('settings.wikiinvalid_private') + wikihelp, components}, true );
  251. }
  252. msg.reactEmoji('nowiki', true);
  253. return msg.replyMsg( {content: lang.get('settings.wikiinvalid') + wikihelp, components}, true );
  254. }
  255. wikinew.updateWiki(body.query.general);
  256. if ( body.query.general.generator.replace( /^MediaWiki 1\.(\d\d).*$/, '$1' ) <= 30 ) {
  257. console.log( '- This wiki is using ' + body.query.general.generator + '.' );
  258. if ( reaction ) reaction.removeEmoji();
  259. return msg.replyMsg( {content: lang.get('test.MediaWiki', 'MediaWiki 1.30', body.query.general.generator) + '\nhttps://www.mediawiki.org/wiki/MediaWiki_1.30', components}, true );
  260. }
  261. if ( body.query.allmessages[0]['*'] !== msg.guildId ) {
  262. if ( reaction ) reaction.removeEmoji();
  263. return msg.replyMsg( {content: lang.get('rcscript.sysmessage', 'MediaWiki:Custom-RcGcDw', msg.guildId) + '\n<' + wikinew.toLink('MediaWiki:Custom-RcGcDw', 'action=edit') + '>', components}, true );
  264. }
  265. return db.query( 'SELECT reason FROM blocklist WHERE wiki = $1', [wikinew.href] ).then( ({rows:[block]}) => {
  266. if ( block ) {
  267. console.log( '- This wiki is blocked: ' + block.reason );
  268. if ( reaction ) reaction.removeEmoji();
  269. return msg.replyMsg( {content: ( block.reason ? lang.get('rcscript.blocked_reason', block.reason) : lang.get('rcscript.blocked') ), components}, true );
  270. }
  271. if ( wikinew.isFandom(false) ) return got.get( wikinew + 'wikia.php?controller=DiscussionPost&method=getPosts&includeCounters=false&limit=1&format=json&cache=' + Date.now(), {
  272. headers: {
  273. Accept: 'application/hal+json'
  274. }
  275. } ).then( dsresponse => {
  276. var dsbody = dsresponse.body;
  277. if ( dsresponse.statusCode !== 200 || !dsbody || dsbody.status === 404 ) {
  278. if ( dsbody?.status !== 404 ) console.log( '- ' + dsresponse.statusCode + ': Error while checking for discussions: ' + dsbody?.title );
  279. return updateWiki();
  280. }
  281. return updateWiki(true);
  282. }, error => {
  283. console.log( '- Error while checking for discussions: ' + error );
  284. return updateWiki();
  285. } );
  286. return updateWiki();
  287. /**
  288. * Changes the wiki.
  289. * @param {Boolean} enableFeeds - If feeds based changes should be enabled.
  290. */
  291. function updateWiki(enableFeeds = false) {
  292. msg.client.fetchWebhook(...selected_row.webhook.split('/')).then( webhook => {
  293. webhook.send( webhook_lang.get('updated_wiki', body.query.general.sitename) + '\n<' + wikinew.toLink(body.query.pages['-1'].title) + ( enableFeeds ? '>\n<' + wikinew + 'f' : '' ) + '>' ).catch(log_error);
  294. }, log_error );
  295. db.query( 'UPDATE rcgcdw SET wiki = $1, rcid = $2, postid = $3 WHERE webhook = $4', [wikinew.href, null, ( enableFeeds ? null : '-1' ), selected_row.webhook] ).then( () => {
  296. console.log( '- RcGcDw successfully updated.' );
  297. if ( reaction ) reaction.removeEmoji();
  298. msg.replyMsg( {content: lang.get('rcscript.updated_wiki') + ' <' + wikinew + '>\n`' + cmd + '`', components}, true );
  299. }, dberror => {
  300. console.log( '- Error while updating the RcGcDw: ' + dberror );
  301. if ( reaction ) reaction.removeEmoji();
  302. msg.replyMsg( {content: lang.get('settings.save_failed'), components}, true );
  303. } );
  304. }
  305. }, dberror => {
  306. console.log( '- Error while getting the blocklist: ' + dberror );
  307. if ( reaction ) reaction.removeEmoji();
  308. msg.reactEmoji('error', true);
  309. } );
  310. }, error => {
  311. if ( reaction ) reaction.removeEmoji();
  312. if ( error.message?.startsWith( 'connect ECONNREFUSED ' ) || error.message?.startsWith( 'Hostname/IP does not match certificate\'s altnames: ' ) || error.message === 'certificate has expired' || error.message === 'self signed certificate' ) {
  313. console.log( '- Error while testing the wiki: No HTTPS' );
  314. return msg.replyMsg( {content: lang.get('settings.wikiinvalid_http') + wikihelp, components}, true );
  315. }
  316. console.log( '- Error while testing the wiki: ' + error );
  317. if ( error.message === `Timeout awaiting 'request' for ${got.defaults.options.timeout.request}ms` ) {
  318. return msg.replyMsg( {content: lang.get('settings.wikiinvalid_timeout') + wikihelp, components}, true );
  319. }
  320. msg.reactEmoji('nowiki', true);
  321. return msg.replyMsg( {content: lang.get('settings.wikiinvalid') + wikihelp, components}, true );
  322. } ) );
  323. }
  324. if ( args[0] === 'lang' || args[0] === 'language' ) {
  325. if ( !args[1] ) {
  326. return msg.replyMsg( {content: lang.get('rcscript.current_lang') + ' `' + allLangs.names[selected_row.lang] + '`\n`' + cmd + ' lang ' + lang.get('rcscript.new_lang') + '`\n' + lang.get('rcscript.help_lang') + ' `' + Object.values(allLangs.names).join('`, `') + '`', files: ( msg.uploadFiles() ? [`./RcGcDb/locale/widgets/${selected_row.lang}.png`] : [] ), components}, true );
  327. }
  328. if ( process.env.READONLY ) return msg.replyMsg( lang.get('general.readonly') + '\n' + process.env.invite, true );
  329. if ( !allLangs.map.hasOwnProperty(args[1]) ) {
  330. return msg.replyMsg( {content: lang.get('settings.langinvalid') + '\n`' + cmd + ' lang ' + lang.get('rcscript.new_lang') + '`\n' + lang.get('rcscript.help_lang') + ' `' + Object.values(allLangs.names).join('`, `') + '`', components}, true );
  331. }
  332. msg.client.fetchWebhook(...selected_row.webhook.split('/')).then( webhook => {
  333. webhook.send( {content: new Lang(allLangs.map[args[1]], 'rcscript.webhook').get('updated_lang', allLangs.names[allLangs.map[args[1]]]), files: [`./RcGcDb/locale/widgets/${allLangs.map[args[1]]}.png`]} ).catch(log_error);
  334. }, log_error );
  335. return db.query( 'UPDATE rcgcdw SET lang = $1 WHERE webhook = $2', [allLangs.map[args[1]], selected_row.webhook] ).then( () => {
  336. console.log( '- RcGcDw successfully updated.' );
  337. msg.replyMsg( {content: lang.get('rcscript.updated_lang') + ' `' + allLangs.names[allLangs.map[args[1]]] + '`\n`' + cmd + '`', files: ( msg.uploadFiles() ? [`./RcGcDb/locale/widgets/${allLangs.map[args[1]]}.png`] : [] ), components}, true );
  338. }, dberror => {
  339. console.log( '- Error while updating the RcGcDw: ' + dberror );
  340. msg.replyMsg( {content: lang.get('settings.save_failed'), components}, true );
  341. } );
  342. }
  343. if ( args[0] === 'display' ) {
  344. if ( !args[1] || !display_types.includes( args[1] ) ) {
  345. return msg.replyMsg( {content: lang.get('rcscript.current_display') + ' `' + display_types[selected_row.display] + '`\n`' + cmd + ' display (' + display.join('|') + ')`\n' + display.map( display_type => '`' + display_type + '`: ' + lang.get('rcscript.help_display_' + display_type) ).join('\n'), components}, true );
  346. }
  347. if ( process.env.READONLY ) return msg.replyMsg( lang.get('general.readonly') + '\n' + process.env.invite, true );
  348. if ( !display.includes( args[1] ) ) {
  349. return msg.replyMsg( lang.get('general.patreon') + '\n<' + process.env.patreon + '>', true );
  350. }
  351. msg.client.fetchWebhook(...selected_row.webhook.split('/')).then( webhook => {
  352. webhook.send( webhook_lang.get('updated_display_' + args[1]) ).catch(log_error);
  353. }, log_error );
  354. return db.query( 'UPDATE rcgcdw SET display = $1 WHERE webhook = $2', [display_types.indexOf(args[1]), selected_row.webhook] ).then( () => {
  355. console.log( '- RcGcDw successfully updated.' );
  356. msg.replyMsg( {content: lang.get('rcscript.updated_display') + ' `' + args[1] + '`\n`' + cmd + '`', components}, true );
  357. }, dberror => {
  358. console.log( '- Error while updating the RcGcDw: ' + dberror );
  359. msg.replyMsg( {content: lang.get('settings.save_failed'), components}, true );
  360. } );
  361. }
  362. if ( new Wiki(selected_row.wiki).isFandom(false) && args[0] === 'feeds' ) {
  363. if ( process.env.READONLY ) return msg.replyMsg( lang.get('general.readonly') + '\n' + process.env.invite, true );
  364. if ( args[1] === 'only' ) {
  365. if ( selected_row.rcid === -1 ) {
  366. msg.client.fetchWebhook(...selected_row.webhook.split('/')).then( webhook => {
  367. webhook.send( webhook_lang.get('enabled_rc') ).catch(log_error);
  368. }, log_error );
  369. return db.query( 'UPDATE rcgcdw SET rcid = $1 WHERE webhook = $2', [null, selected_row.webhook] ).then( () => {
  370. console.log( '- RcGcDw successfully updated.' );
  371. msg.replyMsg( {content: lang.get('rcscript.enabled_rc') + '\n`' + cmd + '`', components}, true );
  372. }, dberror => {
  373. console.log( '- Error while updating the RcGcDw: ' + dberror );
  374. msg.replyMsg( {content: lang.get('settings.save_failed'), components}, true );
  375. } );
  376. }
  377. if ( selected_row.postid === '-1' ) {
  378. return msg.replyMsg( {content: lang.get('rcscript.all_inactive') + '\n\n' + lang.get('rcscript.delete') + '\n`' + cmd + ' delete`', components}, true );
  379. }
  380. msg.client.fetchWebhook(...selected_row.webhook.split('/')).then( webhook => {
  381. webhook.send( webhook_lang.get('disabled_rc') ).catch(log_error);
  382. }, log_error );
  383. return db.query( 'UPDATE rcgcdw SET rcid = $1 WHERE webhook = $2', [-1, selected_row.webhook] ).then( () => {
  384. console.log( '- RcGcDw successfully updated.' );
  385. msg.replyMsg( {content: lang.get('rcscript.disabled_rc') + '\n`' + cmd + '`', components}, true );
  386. }, dberror => {
  387. console.log( '- Error while updating the RcGcDw: ' + dberror );
  388. msg.replyMsg( {content: lang.get('settings.save_failed'), components}, true );
  389. } );
  390. }
  391. if ( selected_row.postid !== '-1' ) {
  392. if ( selected_row.rcid === -1 ) {
  393. return msg.replyMsg( {content: lang.get('rcscript.all_inactive') + '\n\n' + lang.get('rcscript.delete') + '\n`' + cmd + ' delete`', components}, true );
  394. }
  395. msg.client.fetchWebhook(...selected_row.webhook.split('/')).then( webhook => {
  396. webhook.send( webhook_lang.get('disabled_feeds') ).catch(log_error);
  397. }, log_error );
  398. return db.query( 'UPDATE rcgcdw SET postid = $1 WHERE webhook = $2', ['-1', selected_row.webhook] ).then( () => {
  399. console.log( '- RcGcDw successfully updated.' );
  400. msg.replyMsg( {content: lang.get('rcscript.disabled_feeds') + '\n`' + cmd + '`', components}, true );
  401. }, dberror => {
  402. console.log( '- Error while updating the RcGcDw: ' + dberror );
  403. msg.replyMsg( {content: lang.get('settings.save_failed'), components}, true );
  404. } );
  405. }
  406. return msg.reactEmoji('⏳', true).then( reaction => got.get( selected_row.wiki + 'wikia.php?controller=DiscussionPost&method=getPosts&includeCounters=false&limit=1&format=json&cache=' + Date.now(), {
  407. headers: {
  408. Accept: 'application/hal+json'
  409. }
  410. } ).then( dsresponse => {
  411. var dsbody = dsresponse.body;
  412. if ( dsresponse.statusCode !== 200 || !dsbody || dsbody.status === 404 ) {
  413. if ( dsbody?.status !== 404 ) console.log( '- ' + dsresponse.statusCode + ': Error while checking for discussions: ' + dsbody?.title );
  414. if ( reaction ) reaction.removeEmoji();
  415. return msg.replyMsg( {content: lang.get('rcscript.no_feeds'), components}, true );
  416. }
  417. msg.client.fetchWebhook(...selected_row.webhook.split('/')).then( webhook => {
  418. webhook.send( webhook_lang.get('enabled_feeds') + '\n<' + selected_row.wiki + 'f>' ).catch(log_error);
  419. }, log_error );
  420. db.query( 'UPDATE rcgcdw SET postid = $1 WHERE webhook = $2', [null, selected_row.webhook] ).then( () => {
  421. console.log( '- RcGcDw successfully updated.' );
  422. if ( reaction ) reaction.removeEmoji();
  423. msg.replyMsg( {content: lang.get('rcscript.enabled_feeds') + '\n`' + cmd + '`', components}, true );
  424. }, dberror => {
  425. console.log( '- Error while updating the RcGcDw: ' + dberror );
  426. if ( reaction ) reaction.removeEmoji();
  427. msg.replyMsg( {content: lang.get('settings.save_failed'), components}, true );
  428. } );
  429. }, error => {
  430. console.log( '- Error while checking for discussions: ' + error );
  431. if ( reaction ) reaction.removeEmoji();
  432. return msg.replyMsg( {content: lang.get('rcscript.no_feeds'), components}, true );
  433. } ) );
  434. }
  435. if ( rows.length > 1 ) return msg.client.fetchWebhook(...selected_row.webhook.split('/')).then( webhook => {
  436. return webhook.channelId;
  437. }, error => {
  438. log_error(error);
  439. if ( error.name === 'DiscordAPIError' && ['Unknown Webhook', 'Invalid Webhook Token'].includes( error.message ) ) {
  440. db.query( 'DELETE FROM rcgcdw WHERE webhook = $1', [selected_row.webhook] ).then( () => {
  441. console.log( '- RcGcDw successfully removed.' );
  442. }, dberror => {
  443. console.log( '- Error while removing the RcGcDw: ' + dberror );
  444. } );
  445. return Promise.reject();
  446. }
  447. return;
  448. } ).then( channel => {
  449. var text = lang.get('rcscript.current_selected', selected_row.configid);
  450. if ( button ) text += `\n<${button.url}>\n`;
  451. text += '\n' + lang.get('rcscript.channel') + ' <#' + channel + '>\n';
  452. text += '\n' + lang.get('rcscript.wiki') + ' <' + selected_row.wiki + '>';
  453. text += '\n`' + cmd + ' wiki ' + lang.get('rcscript.new_wiki') + '`\n';
  454. text += '\n' + lang.get('rcscript.lang') + ' `' + allLangs.names[selected_row.lang] + '`';
  455. text += '\n`' + cmd + ' lang ' + lang.get('rcscript.new_lang') + '`\n';
  456. text += '\n' + lang.get('rcscript.display') + ' `' + display_types[selected_row.display] + '`';
  457. text += '\n`' + cmd + ' display (' + display.join('|') + ')`\n';
  458. if ( selected_row.rcid === -1 ) {
  459. text += '\n' + lang.get('rcscript.rc') + ' *`' + lang.get('rcscript.disabled') + '`*';
  460. text += '\n`' + cmd + ' feeds only` ' + lang.get('rcscript.toggle') + '\n';
  461. }
  462. if ( new Wiki(selected_row.wiki).isFandom(false) ) {
  463. text += '\n' + lang.get('rcscript.feeds') + ' *`' + lang.get('rcscript.' + ( selected_row.postid === '-1' ? 'disabled' : 'enabled' )) + '`*';
  464. text += '\n' + lang.get('rcscript.help_feeds') + '\n`' + cmd + ' feeds` ' + lang.get('rcscript.toggle') + '\n';
  465. }
  466. text += '\n' + lang.get('rcscript.delete') + '\n`' + cmd + ' delete`\n';
  467. msg.replyMsg( {content: text, components}, true );
  468. }, () => msg.replyMsg( {content: lang.get('rcscript.deleted'), components}, true ) );
  469. }
  470. Promise.all(rows.map( row => msg.client.fetchWebhook(...row.webhook.split('/')).then( webhook => {
  471. return webhook.channelId;
  472. }, error => {
  473. log_error(error);
  474. if ( error.name === 'DiscordAPIError' && ['Unknown Webhook', 'Invalid Webhook Token'].includes( error.message ) ) {
  475. db.query( 'DELETE FROM rcgcdw WHERE webhook = $1', [row.webhook] ).then( () => {
  476. console.log( '- RcGcDw successfully removed.' );
  477. }, dberror => {
  478. console.log( '- Error while removing the RcGcDw: ' + dberror );
  479. } );
  480. return;
  481. }
  482. return 'undefined';
  483. } ) )).then( webhooks => {
  484. rows.forEach( (row, i) => {
  485. if ( webhooks[i] ) row.channel = webhooks[i];
  486. } );
  487. rows = rows.filter( row => row.channel );
  488. var only = ( rows.length === 1 );
  489. var text = '';
  490. if ( rows.length ) {
  491. text += lang.get('rcscript.current');
  492. if ( button ) text += `\n<${button.url}>`;
  493. text += rows.map( row => {
  494. var cmd = prefix + 'rcscript' + ( only ? '' : ' ' + row.configid );
  495. var row_text = '\n';
  496. if ( !only ) row_text += '\n`' + cmd + '`';
  497. row_text += '\n' + lang.get('rcscript.channel') + ' <#' + row.channel + '>';
  498. if ( only ) row_text += '\n';
  499. row_text += '\n' + lang.get('rcscript.wiki') + ' <' + row.wiki + '>';
  500. if ( only ) row_text += '\n`' + cmd + ' wiki ' + lang.get('rcscript.new_wiki') + '`\n';
  501. row_text += '\n' + lang.get('rcscript.lang') + ' `' + allLangs.names[row.lang] + '`';
  502. if ( only ) row_text += '\n`' + cmd + ' lang ' + lang.get('rcscript.new_lang') + '`\n';
  503. row_text += '\n' + lang.get('rcscript.display') + ' `' + display_types[row.display] + '`';
  504. if ( only ) row_text += '\n`' + cmd + ' display (' + display.join('|') + ')`\n';
  505. if ( row.rcid === -1 ) {
  506. row_text += '\n' + lang.get('rcscript.rc') + ' *`' + lang.get('rcscript.disabled' ) + '`*';
  507. if ( only ) row_text += '\n`' + cmd + ' feeds only` ' + lang.get('rcscript.toggle') + '\n';
  508. }
  509. if ( new Wiki(row.wiki).isFandom(false) ) {
  510. row_text += '\n' + lang.get('rcscript.feeds') + ' *`' + lang.get('rcscript.' + ( row.postid === '-1' ? 'disabled' : 'enabled' )) + '`*';
  511. if ( only ) row_text += '\n' + lang.get('rcscript.help_feeds') + '\n`' + cmd + ' feeds` ' + lang.get('rcscript.toggle') + '\n';
  512. }
  513. if ( only ) row_text += '\n' + lang.get('rcscript.delete') + '\n`' + cmd + ' delete`\n';
  514. return row_text;
  515. } ).join('');
  516. }
  517. else {
  518. text += lang.get('rcscript.missing');
  519. if ( button ) text += `\n<${button.url}>`;
  520. }
  521. if ( rows.length < limit ) text += '\n\n' + lang.get('rcscript.add_more') + '\n`' + prefix + 'rcscript add ' + lang.get('rcscript.new_wiki') + '`';
  522. Util.splitMessage( text ).forEach( textpart => msg.replyMsg( {content: textpart, components}, true ) );
  523. } );
  524. }, dberror => {
  525. console.log( '- Error while getting the RcGcDw: ' + dberror );
  526. msg.reactEmoji('error', true);
  527. } );
  528. }
  529. /**
  530. * Processes the blocklist.
  531. * @param {import('discord.js').Message} msg - The Discord message.
  532. * @param {String[]} args - The command arguments.
  533. */
  534. function blocklist(msg, args) {
  535. var prefix = ( patreons[msg?.guildId] || process.env.prefix );
  536. if ( args[0] === 'add' ) {
  537. if ( !args[1] ) return msg.replyMsg( '`' + prefix + 'rcscript block add <wiki> [<reason>]`', true );
  538. if ( process.env.READONLY ) return msg.replyMsg( lang.get('general.readonly') + '\n' + process.env.invite, true );
  539. let input = args[1].toLowerCase().replace( /^<(.*?)>$/, '$1' );
  540. let wiki = Wiki.fromInput(input);
  541. if ( !wiki ) return msg.replyMsg( '`' + prefix + 'rcscript block add <wiki> [<reason>]`', true );
  542. let reason = ( args.slice(2).join(' ').trim() || null );
  543. return db.query( 'INSERT INTO blocklist(wiki, reason) VALUES($1, $2)', [wiki.href, reason] ).then( () => {
  544. console.log( '- Successfully added to the blocklist.' );
  545. db.query( 'DELETE FROM rcgcdw WHERE wiki = $1 RETURNING webhook, lang', [wiki.href] ).then( ({rows}) => {
  546. console.log( '- Successfully removed ' + rows.length + ' webhooks.' );
  547. msg.replyMsg( 'I added `' + wiki + '` to the blocklist for `' + reason + '` and removed ' + rows.length + ' webhooks.', true );
  548. if ( rows.length ) rows.forEach( row => {
  549. msg.client.fetchWebhook(...row.webhook.split('/')).then( webhook => {
  550. var lang = new Lang(row.lang, 'rcscript.webhook');
  551. webhook.send( '**' + ( reason ? lang.get('blocked_reason', reason) : lang.get('blocked') ) + '**\n' + lang.get('blocked_help', `<${process.env.invite}>`) ).catch(log_error).finally( () => {
  552. webhook.delete().catch(log_error);
  553. } );
  554. }, log_error );
  555. } );
  556. }, dberror => {
  557. console.log( '- Error while removing the webhooks: ' + dberror );
  558. msg.replyMsg( 'I added `' + wiki + '` to the blocklist for `' + reason + '` but got an error while removing the webhooks: ' + dberror, true );
  559. } );
  560. }, dberror => {
  561. if ( dberror.message === 'duplicate key value violates unique constraint "blocklist_wiki_key"' ) {
  562. return msg.replyMsg( '`' + wiki + '` is already on the blocklist.\n`' + prefix + 'rcscript block <' + wiki + '>`', true );
  563. }
  564. console.log( '- Error while adding to the blocklist: ' + dberror );
  565. msg.replyMsg( 'I got an error while adding to the blocklist: ' + dberror, true );
  566. } );
  567. }
  568. if ( args[0] === 'remove' ) {
  569. let input = args.slice(1).join(' ').toLowerCase().trim().replace( /^<\s*(.*?)\s*>$/, '$1' );
  570. let wiki = Wiki.fromInput(input);
  571. if ( !wiki ) return msg.replyMsg( '`' + prefix + 'rcscript block remove <wiki>`', true );
  572. if ( process.env.READONLY ) return msg.replyMsg( lang.get('general.readonly') + '\n' + process.env.invite, true );
  573. return db.query( 'DELETE FROM blocklist WHERE wiki = $1', [wiki.href] ).then( ({rowCount}) => {
  574. if ( rowCount ) {
  575. console.log( '- Successfully removed from the blocklist.' );
  576. msg.replyMsg( 'I removed `' + wiki + '` from the blocklist.', true );
  577. }
  578. else msg.replyMsg( '`' + wiki + '` was not on the blocklist.', true );
  579. }, dberror => {
  580. console.log( '- Error while removing from the blocklist: ' + dberror );
  581. msg.replyMsg( 'I got an error while removing from the blocklist: ' + dberror, true );
  582. } );
  583. }
  584. if ( args.length ) {
  585. let input = args.join(' ').toLowerCase().trim().replace( /^<\s*(.*?)\s*>$/, '$1' );
  586. let wiki = Wiki.fromInput(input);
  587. if ( !wiki ) return msg.replyMsg( '`' + prefix + 'rcscript block <wiki>`\n`' + prefix + 'rcscript block add <wiki> [<reason>]`\n`' + prefix + 'rcscript block remove <wiki>`', true );
  588. return db.query( 'SELECT reason FROM blocklist WHERE wiki = $1', [wiki.href] ).then( ({rows:[row]}) => {
  589. if ( !row ) return msg.replyMsg( '`' + wiki + '` is currently not on the blocklist.\n`' + prefix + 'rcscript block add <' + wiki + '> [<reason>]`', true );
  590. msg.replyMsg( '`' + wiki + '` is currently on the blocklist ' + ( row.reason ? 'for `' + row.reason + '`' : 'with no reason provided' ) + '.\n`' + prefix + 'rcscript block remove <' + wiki + '>`', true );
  591. }, dberror => {
  592. console.log( '- Error while checking the blocklist: ' + dberror );
  593. msg.replyMsg( 'I got an error while checking the blocklist: ' + dberror, true );
  594. } );
  595. }
  596. db.query( 'SELECT wiki, reason FROM blocklist' ).then( ({rows}) => {
  597. if ( !rows.length ) return msg.replyMsg( 'There are currently no wikis on the blocklist.\n`' + prefix + 'rcscript block add <wiki> [<reason>]`', true );
  598. Util.splitMessage( 'There are currently ' + row.length + ' wikis the blocklist:\n' + rows.map( row => '`' + row.wiki + '` – ' + ( row.reason ? '`' + row.reason + '`' : 'No reason provided.' ) ).join('\n') + '\n`' + prefix + 'rcscript block remove <wiki>`' ).forEach( textpart => msg.replyMsg( textpart, true ) );
  599. }, dberror => {
  600. console.log( '- Error while checking the blocklist: ' + dberror );
  601. msg.replyMsg( 'I got an error while checking the blocklist: ' + dberror, true );
  602. } );
  603. }
  604. module.exports = {
  605. name: 'rcscript',
  606. everyone: rcscriptExists,
  607. pause: rcscriptExists,
  608. owner: false,
  609. run: cmd_rcscript
  610. };