rcscript.js 36 KB

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