rcscript.js 35 KB

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