rcscript.js 36 KB

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