fandom.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. const htmlparser = require('htmlparser2');
  2. const {MessageEmbed} = require('discord.js');
  3. const {limit: {interwiki: interwikiLimit}, wikiProjects} = require('../../util/default.json');
  4. const fs = require('fs');
  5. var fn = {
  6. special_page: require('../../functions/special_page.js'),
  7. discussion: require('../../functions/discussion.js')
  8. };
  9. fs.readdir( './cmds/wiki/fandom', (error, files) => {
  10. if ( error ) return error;
  11. files.filter( file => file.endsWith('.js') ).forEach( file => {
  12. var command = require('./fandom/' + file);
  13. fn[command.name] = command.run;
  14. } );
  15. } );
  16. /**
  17. * Checks a Fandom wiki.
  18. * @param {import('../../util/i18n.js')} lang - The user language.
  19. * @param {import('discord.js').Message} msg - The Discord message.
  20. * @param {String} title - The page title.
  21. * @param {String} wiki - The wiki for the page.
  22. * @param {String} cmd - The command at this point.
  23. * @param {import('discord.js').MessageReaction} reaction - The reaction on the message.
  24. * @param {String} [spoiler] - If the response is in a spoiler.
  25. * @param {String} [querystring] - The querystring for the link.
  26. * @param {String} [fragment] - The section for the link.
  27. * @param {String} [interwiki] - The fallback interwiki link.
  28. * @param {Number} [selfcall] - The amount of followed interwiki links.
  29. */
  30. function fandom_check_wiki(lang, msg, title, wiki, cmd, reaction, spoiler = '', querystring = '', fragment = '', interwiki = '', selfcall = 0) {
  31. var full_title = title;
  32. if ( title.includes( '#' ) ) {
  33. fragment = title.split('#').slice(1).join('#');
  34. title = title.split('#')[0];
  35. }
  36. if ( /\?\w+=/.test(title) ) {
  37. var querystart = title.search(/\?\w+=/);
  38. querystring = title.substring(querystart + 1) + ( querystring ? '&' + querystring : '' );
  39. title = title.substring(0, querystart);
  40. }
  41. if ( title.length > 250 ) {
  42. title = title.substring(0, 250);
  43. msg.reactEmoji('⚠️');
  44. }
  45. var invoke = title.split(' ')[0].toLowerCase();
  46. var aliasInvoke = ( lang.aliases[invoke] || invoke );
  47. var args = title.split(' ').slice(1);
  48. if ( aliasInvoke === 'random' && !args.join('') && !querystring && !fragment ) fn.random(lang, msg, wiki, reaction, spoiler);
  49. else if ( aliasInvoke === 'overview' && !args.join('') && !querystring && !fragment ) fn.overview(lang, msg, wiki, reaction, spoiler);
  50. else if ( aliasInvoke === 'test' && !args.join('') && !querystring && !fragment ) {
  51. this.test(lang, msg, args, '', wiki);
  52. if ( reaction ) reaction.removeEmoji();
  53. }
  54. else if ( aliasInvoke === 'page' ) {
  55. msg.sendChannel( spoiler + '<' + wiki.toLink(args.join('_'), querystring.toTitle(), fragment) + '>' + spoiler );
  56. if ( reaction ) reaction.removeEmoji();
  57. }
  58. else if ( aliasInvoke === 'diff' && args.join('') && !querystring && !fragment ) fn.diff(lang, msg, args, wiki, reaction, spoiler);
  59. else {
  60. var noRedirect = ( /(?:^|&)redirect=no(?:&|$)/.test(querystring) || /(?:^|&)action=(?!view(?:&|$))/.test(querystring) );
  61. got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=description&amenableparser=true&siprop=general|namespaces|specialpagealiases|wikidesc&iwurl=true' + ( noRedirect ? '' : '&redirects=true' ) + '&prop=imageinfo|categoryinfo&titles=' + encodeURIComponent( title.replace( /\|/g, '\ufffd' ) ) + '&format=json' ).then( response => {
  62. var body = response.body;
  63. if ( body && body.warnings ) log_warn(body.warnings);
  64. if ( response.statusCode !== 200 || !body || !body.query ) {
  65. if ( interwiki ) msg.sendChannel( spoiler + ' ' + interwiki.replace( /@(here|everyone)/g, '%40$1' ) + fragment + ' ' + spoiler );
  66. else if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  67. console.log( '- This wiki doesn\'t exist!' );
  68. msg.reactEmoji('nowiki');
  69. }
  70. else {
  71. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  72. msg.sendChannelError( spoiler + '<' + wiki.toLink(( querystring || fragment || !title ? title : 'Special:Search' ), ( querystring || fragment || !title ? querystring.toTitle() : 'search=' + title.toSearch() ), fragment) + '>' + spoiler );
  73. }
  74. if ( reaction ) reaction.removeEmoji();
  75. }
  76. else if ( body.query.general.generator.startsWith( 'MediaWiki 1.3' ) ) {
  77. return this.gamepedia(lang, msg, title, wiki, cmd, reaction, spoiler, querystring, fragment, selfcall);
  78. }
  79. else if ( aliasInvoke === 'search' ) {
  80. fn.search(lang, msg, full_title.split(' ').slice(1).join(' '), wiki, body.query, reaction, spoiler);
  81. }
  82. else if ( aliasInvoke === 'discussion' && !querystring && !fragment ) {
  83. fn.discussion(lang, msg, wiki, args.join(' '), body.query, reaction, spoiler);
  84. }
  85. else {
  86. if ( body.query.pages ) {
  87. var querypages = Object.values(body.query.pages);
  88. var querypage = querypages[0];
  89. if ( body.query.redirects && body.query.redirects[0].from.split(':')[0] === body.query.namespaces['-1']['*'] && body.query.specialpagealiases.filter( sp => ['Mypage','Mytalk','MyLanguage'].includes( sp.realname ) ).map( sp => sp.aliases[0] ).includes( body.query.redirects[0].from.split(':').slice(1).join(':').split('/')[0].replace( / /g, '_' ) ) ) {
  90. querypage.title = body.query.redirects[0].from;
  91. delete body.query.redirects[0].tofragment;
  92. delete querypage.missing;
  93. querypage.ns = -1;
  94. querypage.special = '';
  95. }
  96. var contribs = body.query.namespaces['-1']['*'] + ':' + body.query.specialpagealiases.find( sp => sp.realname === 'Contributions' ).aliases[0] + '/';
  97. if ( querypage.ns === 2 && ( !querypage.title.includes( '/' ) || /^[^:]+:(?:(?:\d{1,3}\.){3}\d{1,3}\/\d{2}|(?:[\dA-F]{1,4}:){7}[\dA-F]{1,4}\/\d{2,3})$/.test(querypage.title) ) ) {
  98. var userparts = querypage.title.split(':');
  99. querypage.noRedirect = noRedirect;
  100. fn.user(lang, msg, userparts[0].toTitle() + ':', userparts.slice(1).join(':'), wiki, querystring, fragment, querypage, contribs.toTitle(), reaction, spoiler);
  101. }
  102. else if ( querypage.ns === -1 && querypage.title.startsWith( contribs ) && querypage.title.length > contribs.length ) {
  103. var username = querypage.title.split('/').slice(1).join('/');
  104. got.get( wiki + 'api.php?action=query&titles=User:' + encodeURIComponent( username ) + '&format=json' ).then( uresponse => {
  105. var ubody = uresponse.body;
  106. if ( uresponse.statusCode !== 200 || !ubody || !ubody.query ) {
  107. console.log( '- ' + uresponse.statusCode + ': Error while getting the user: ' + ( ubody && ubody.error && ubody.error.info ) );
  108. msg.sendChannelError( spoiler + '<' + wiki.toLink(contribs + username, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  109. if ( reaction ) reaction.removeEmoji();
  110. }
  111. else {
  112. querypage = Object.values(ubody.query.pages)[0];
  113. if ( querypage.ns === 2 ) {
  114. username = querypage.title.split(':').slice(1).join(':');
  115. querypage.title = contribs + username;
  116. delete querypage.missing;
  117. querypage.ns = -1;
  118. querypage.special = '';
  119. querypage.noRedirect = noRedirect;
  120. fn.user(lang, msg, contribs.toTitle(), username, wiki, querystring, fragment, querypage, contribs.toTitle(), reaction, spoiler);
  121. }
  122. else {
  123. msg.reactEmoji('error');
  124. if ( reaction ) reaction.removeEmoji();
  125. }
  126. }
  127. }, error => {
  128. console.log( '- Error while getting the user: ' + error );
  129. msg.sendChannelError( spoiler + '<' + wiki.toLink(contribs + username, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  130. if ( reaction ) reaction.removeEmoji();
  131. } );
  132. }
  133. else if ( querypage.ns === 1201 && querypage.missing !== undefined ) {
  134. var thread = querypage.title.split(':');
  135. got.get( wiki + 'api.php?action=query&prop=revisions&rvprop=user&rvdir=newer&rvlimit=1&pageids=' + thread.slice(1).join(':') + '&format=json' ).then( thresponse => {
  136. var thbody = thresponse.body;
  137. if ( thresponse.statusCode !== 200 || !thbody || !thbody.query || !thbody.query.pages ) {
  138. console.log( '- ' + thresponse.statusCode + ': Error while getting the thread: ' + ( thbody && thbody.error && thbody.error.info ) );
  139. msg.sendChannelError( spoiler + '<' + wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  140. if ( reaction ) reaction.removeEmoji();
  141. }
  142. else {
  143. querypage = thbody.query.pages[thread.slice(1).join(':')];
  144. if ( querypage.missing !== undefined ) {
  145. msg.reactEmoji('🤷');
  146. if ( reaction ) reaction.removeEmoji();
  147. }
  148. else {
  149. var pagelink = wiki.toLink(thread.join(':'), querystring.toTitle(), fragment, body.query.general);
  150. var embed = new MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( thread.join(':').escapeFormatting() ).setURL( pagelink ).setFooter( querypage.revisions[0].user );
  151. got.get( wiki.toDescLink(querypage.title), {
  152. responseType: 'text'
  153. } ).then( descresponse => {
  154. var descbody = descresponse.body;
  155. if ( descresponse.statusCode !== 200 || !descbody ) {
  156. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  157. } else {
  158. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general);
  159. var parser = new htmlparser.Parser( {
  160. onopentag: (tagname, attribs) => {
  161. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  162. var description = attribs.content.escapeFormatting();
  163. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  164. embed.setDescription( description );
  165. }
  166. if ( tagname === 'meta' && attribs.property === 'og:image' ) {
  167. thumbnail = attribs.content;
  168. }
  169. }
  170. }, {decodeEntities:true} );
  171. parser.write( descbody );
  172. parser.end();
  173. embed.setThumbnail( thumbnail );
  174. }
  175. }, error => {
  176. console.log( '- Error while getting the description: ' + error );
  177. } ).finally( () => {
  178. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  179. if ( reaction ) reaction.removeEmoji();
  180. } );
  181. }
  182. }
  183. }, error => {
  184. console.log( '- Error while getting the thread: ' + error );
  185. msg.sendChannelError( spoiler + '<' + wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  186. if ( reaction ) reaction.removeEmoji();
  187. } );
  188. }
  189. else if ( ( querypage.missing !== undefined && querypage.known === undefined && !( noRedirect || querypage.categoryinfo ) ) || querypage.invalid !== undefined ) {
  190. got.get( wiki + 'api/v1/Search/List?minArticleQuality=0&namespaces=4,12,14,' + Object.values(body.query.namespaces).filter( ns => ns.content !== undefined ).map( ns => ns.id ).join(',') + '&limit=1&query=' + encodeURIComponent( title ) + '&format=json&cache=' + Date.now() ).then( wsresponse => {
  191. var wsbody = wsresponse.body;
  192. if ( wsresponse.statusCode !== 200 || !wsbody || wsbody.exception || !wsbody.total || !wsbody.items || !wsbody.items.length ) {
  193. if ( wsbody && ( !wsbody.total || ( wsbody.items && !wsbody.items.length ) || ( wsbody.exception && wsbody.exception.code === 404 ) ) ) msg.reactEmoji('🤷');
  194. else {
  195. console.log( '- ' + wsresponse.statusCode + ': Error while getting the search results: ' + ( wsbody && wsbody.exception && wsbody.exception.details ) );
  196. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Search', 'search=' + title.toSearch(), '', body.query.general) + '>' + spoiler );
  197. }
  198. if ( reaction ) reaction.removeEmoji();
  199. }
  200. else {
  201. querypage = wsbody.items[0];
  202. if ( querypage.ns && !querypage.title.startsWith( body.query.namespaces[querypage.ns]['*'] + ':' ) ) {
  203. querypage.title = body.query.namespaces[querypage.ns]['*'] + ':' + querypage.title;
  204. }
  205. var text = '';
  206. var prefix = ( msg.channel.type === 'text' && patreons[msg.guild.id] || process.env.prefix );
  207. var linksuffix = ( querystring ? '?' + querystring : '' ) + ( fragment ? '#' + fragment : '' );
  208. if ( title.replace( /\-/g, ' ' ).toTitle().toLowerCase() === querypage.title.replace( /\-/g, ' ' ).toTitle().toLowerCase() ) {
  209. text = '';
  210. }
  211. else if ( wsbody.total === 1 ) {
  212. text = '\n' + lang.get('search.infopage', '`' + prefix + cmd + ( lang.localNames.page || 'page' ) + ' ' + title + linksuffix + '`');
  213. }
  214. else {
  215. text = '\n' + lang.get('search.infosearch', '`' + prefix + cmd + ( lang.localNames.page || 'page' ) + ' ' + title + linksuffix + '`', '`' + prefix + cmd + ( lang.localNames.search || 'search' ) + ' ' + title + linksuffix + '`');
  216. }
  217. got.get( wiki + 'api.php?action=query&prop=imageinfo|categoryinfo&titles=' + encodeURIComponent( querypage.title ) + '&format=json' ).then( srresponse => {
  218. var srbody = srresponse.body;
  219. if ( srbody && srbody.warnings ) log_warn(srbody.warnings);
  220. if ( srresponse.statusCode !== 200 || !srbody || !srbody.query || !srbody.query.pages ) {
  221. console.log( '- ' + srresponse.statusCode + ': Error while getting the search results: ' + ( srbody && srbody.error && srbody.error.info ) );
  222. msg.sendChannelError( spoiler + '<' + wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  223. if ( reaction ) reaction.removeEmoji();
  224. }
  225. else {
  226. querypage = Object.values(srbody.query.pages)[0];
  227. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general);
  228. var embed = new MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  229. if ( querypage.imageinfo ) {
  230. var filename = querypage.title.replace( body.query.namespaces['6']['*'] + ':', '' );
  231. var pageimage = wiki.toLink('Special:FilePath/' + filename, 'v=' + Date.now(), '', body.query.general);
  232. if ( msg.showEmbed() && /\.(?:png|jpg|jpeg|gif)$/.test(querypage.title.toLowerCase()) ) embed.setImage( pageimage );
  233. else if ( msg.uploadFiles() ) embed.attachFiles( [{attachment:pageimage,name:( spoiler ? 'SPOILER ' : '' ) + filename}] );
  234. }
  235. if ( querypage.categoryinfo ) {
  236. var category = [lang.get('search.category.content')];
  237. if ( querypage.categoryinfo.size === 0 ) {
  238. category.push(lang.get('search.category.empty'));
  239. }
  240. if ( querypage.categoryinfo.pages > 0 ) {
  241. category.push(lang.get('search.category.pages', querypage.categoryinfo.pages));
  242. }
  243. if ( querypage.categoryinfo.files > 0 ) {
  244. category.push(lang.get('search.category.files', querypage.categoryinfo.files));
  245. }
  246. if ( querypage.categoryinfo.subcats > 0 ) {
  247. category.push(lang.get('search.category.subcats', querypage.categoryinfo.subcats));
  248. }
  249. if ( msg.showEmbed() ) embed.addField( category[0], category.slice(1).join('\n') );
  250. else text += '\n\n' + category.join('\n');
  251. }
  252. if ( querypage.title === body.query.general.mainpage && body.query.allmessages[0]['*'] ) {
  253. embed.setDescription( body.query.allmessages[0]['*'] );
  254. embed.setThumbnail( wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general) );
  255. msg.sendChannel( spoiler + '<' + pagelink + '>' + text + spoiler, {embed} );
  256. if ( reaction ) reaction.removeEmoji();
  257. }
  258. else got.get( wiki.toDescLink(querypage.title), {
  259. responseType: 'text'
  260. } ).then( descresponse => {
  261. var descbody = descresponse.body;
  262. if ( descresponse.statusCode !== 200 || !descbody ) {
  263. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  264. } else {
  265. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general);
  266. var parser = new htmlparser.Parser( {
  267. onopentag: (tagname, attribs) => {
  268. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  269. var description = attribs.content.escapeFormatting();
  270. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  271. embed.setDescription( description );
  272. }
  273. if ( tagname === 'meta' && attribs.property === 'og:image' && querypage.title !== body.query.general.mainpage ) {
  274. thumbnail = attribs.content;
  275. }
  276. }
  277. }, {decodeEntities:true} );
  278. parser.write( descbody );
  279. parser.end();
  280. if ( !querypage.imageinfo ) embed.setThumbnail( thumbnail );
  281. }
  282. }, error => {
  283. console.log( '- Error while getting the description: ' + error );
  284. } ).finally( () => {
  285. msg.sendChannel( spoiler + '<' + pagelink + '>' + text + spoiler, {embed} );
  286. if ( reaction ) reaction.removeEmoji();
  287. } );
  288. }
  289. }, error => {
  290. console.log( '- Error while getting the search results: ' + error );
  291. msg.sendChannelError( spoiler + '<' + wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  292. if ( reaction ) reaction.removeEmoji();
  293. } );
  294. }
  295. }, error => {
  296. console.log( '- Error while getting the search results: ' + error );
  297. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Search', 'search=' + title.toSearch(), '', body.query.general) + '>' + spoiler );
  298. if ( reaction ) reaction.removeEmoji();
  299. } );
  300. }
  301. else if ( querypage.ns === -1 ) {
  302. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general);
  303. var embed = new MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink ).setThumbnail( wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general) );
  304. var specialpage = body.query.specialpagealiases.find( sp => body.query.namespaces['-1']['*'] + ':' + sp.aliases[0].replace( /\_/g, ' ' ) === querypage.title.split('/')[0] );
  305. specialpage = ( specialpage ? specialpage.realname : querypage.title.replace( body.query.namespaces['-1']['*'] + ':', '' ).split('/')[0] ).toLowerCase();
  306. fn.special_page(lang, msg, querypage.title, specialpage, embed, wiki, reaction, spoiler);
  307. }
  308. else {
  309. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), ( fragment || ( body.query.redirects && body.query.redirects[0].tofragment || '' ) ), body.query.general);
  310. var text = '';
  311. var embed = new MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  312. if ( querypage.imageinfo ) {
  313. var filename = querypage.title.replace( body.query.namespaces['6']['*'] + ':', '' );
  314. var pageimage = wiki.toLink('Special:FilePath/' + filename, 'v=' + Date.now(), '', body.query.general);
  315. if ( msg.showEmbed() && /\.(?:png|jpg|jpeg|gif)$/.test(querypage.title.toLowerCase()) ) embed.setImage( pageimage );
  316. else if ( msg.uploadFiles() ) embed.attachFiles( [{attachment:pageimage,name:( spoiler ? 'SPOILER ' : '' ) + filename}] );
  317. }
  318. if ( querypage.categoryinfo ) {
  319. var category = [lang.get('search.category.content')];
  320. if ( querypage.categoryinfo.size === 0 ) {
  321. category.push(lang.get('search.category.empty'));
  322. }
  323. if ( querypage.categoryinfo.pages > 0 ) {
  324. category.push(lang.get('search.category.pages', querypage.categoryinfo.pages));
  325. }
  326. if ( querypage.categoryinfo.files > 0 ) {
  327. category.push(lang.get('search.category.files', querypage.categoryinfo.files));
  328. }
  329. if ( querypage.categoryinfo.subcats > 0 ) {
  330. category.push(lang.get('search.category.subcats', querypage.categoryinfo.subcats));
  331. }
  332. if ( msg.showEmbed() ) embed.addField( category[0], category.slice(1).join('\n') );
  333. else text += '\n\n' + category.join('\n');
  334. }
  335. if ( querypage.title === body.query.general.mainpage && body.query.allmessages[0]['*'] ) {
  336. embed.setDescription( body.query.allmessages[0]['*'] );
  337. embed.setThumbnail( wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general) );
  338. msg.sendChannel( spoiler + '<' + pagelink + '>' + text + spoiler, {embed} );
  339. if ( reaction ) reaction.removeEmoji();
  340. }
  341. else got.get( wiki.toDescLink(querypage.title), {
  342. responseType: 'text'
  343. } ).then( descresponse => {
  344. var descbody = descresponse.body;
  345. if ( descresponse.statusCode !== 200 || !descbody ) {
  346. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  347. } else {
  348. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general);
  349. var parser = new htmlparser.Parser( {
  350. onopentag: (tagname, attribs) => {
  351. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  352. var description = attribs.content.escapeFormatting();
  353. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  354. embed.setDescription( description );
  355. }
  356. if ( tagname === 'meta' && attribs.property === 'og:image' && querypage.title !== body.query.general.mainpage ) {
  357. thumbnail = attribs.content;
  358. }
  359. }
  360. }, {decodeEntities:true} );
  361. parser.write( descbody );
  362. parser.end();
  363. if ( !querypage.imageinfo ) embed.setThumbnail( thumbnail );
  364. }
  365. }, error => {
  366. console.log( '- Error while getting the description: ' + error );
  367. } ).finally( () => {
  368. msg.sendChannel( spoiler + '<' + pagelink + '>' + text + spoiler, {embed} );
  369. if ( reaction ) reaction.removeEmoji();
  370. } );
  371. }
  372. }
  373. else if ( body.query.interwiki ) {
  374. if ( msg.channel.type === 'text' && pause[msg.guild.id] ) {
  375. if ( reaction ) reaction.removeEmoji();
  376. console.log( '- Aborted, paused.' );
  377. return;
  378. }
  379. interwiki = body.query.interwiki[0].url;
  380. var maxselfcall = interwikiLimit[( msg?.guild?.id in patreons ? 'patreon' : 'default' )];
  381. if ( selfcall < maxselfcall && /^(?:https?:)?\/\//.test(interwiki) ) {
  382. selfcall++;
  383. var regex = interwiki.match( /^(?:https?:)?\/\/(([a-z\d-]{1,50})\.(?:fandom\.com|wikia\.org)(?:(?!\/wiki\/)\/([a-z-]{2,12}))?)(?:\/wiki\/|\/?$)/ );
  384. if ( regex ) {
  385. let iwtitle = decodeURIComponent( interwiki.replace( regex[0], '' ) ).replace( /\_/g, ' ' );
  386. this.fandom(lang, msg, iwtitle, 'https://' + regex[1] + '/', ( regex[1].includes( '.wikia.org' ) ? '??' : '?' ) + ( regex[3] ? regex[3] + '.' : '' ) + regex[2] + ' ', reaction, spoiler, querystring, fragment, interwiki, selfcall);
  387. return;
  388. }
  389. regex = interwiki.match( /^(?:https?:)?\/\/([a-z\d-]{1,50})\.gamepedia\.com(?:\/|$)/ );
  390. if ( regex ) {
  391. let iwtitle = decodeURIComponent( interwiki.replace( regex[0], '' ) ).replace( /\_/g, ' ' );
  392. this.gamepedia(lang, msg, iwtitle, 'https://' + regex[1] + '.gamepedia.com/', '!' + regex[1] + ' ', reaction, spoiler, querystring, fragment, interwiki, selfcall);
  393. return;
  394. }
  395. let project = wikiProjects.find( project => interwiki.split('/')[2].endsWith( project.name ) );
  396. if ( project ) {
  397. regex = interwiki.match( new RegExp( '^(?:https?:)?//' + project.regex + `(?:${project.articlePath}|/?$)` ) );
  398. if ( regex ) {
  399. let iwtitle = decodeURIComponent( interwiki.replace( regex[0], '' ) ).replace( /\_/g, ' ' );
  400. this.gamepedia(lang, msg, iwtitle, 'https://' + regex[1] + project.scriptPath, cmd + body.query.interwiki[0].iw + ':', reaction, spoiler, querystring, fragment, interwiki, selfcall);
  401. return;
  402. }
  403. }
  404. }
  405. if ( fragment ) fragment = '#' + fragment.toSection();
  406. if ( interwiki.includes( '#' ) ) {
  407. if ( !fragment ) fragment = '#' + interwiki.split('#').slice(1).join('#');
  408. interwiki = interwiki.split('#')[0];
  409. }
  410. if ( querystring ) interwiki += ( interwiki.includes( '?' ) ? '&' : '?' ) + querystring.toTitle();
  411. msg.sendChannel( spoiler + ' ' + interwiki.replace( /@(here|everyone)/g, '%40$1' ) + fragment + ' ' + spoiler ).then( message => {
  412. if ( message && selfcall === maxselfcall ) message.reactEmoji('⚠️');
  413. } );
  414. if ( reaction ) reaction.removeEmoji();
  415. }
  416. else if ( body.query.redirects ) {
  417. var pagelink = wiki.toLink(body.query.redirects[0].to, querystring.toTitle(), ( fragment || body.query.redirects[0].tofragment || '' ) );
  418. var embed = new MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( body.query.redirects[0].to.escapeFormatting() ).setURL( pagelink ).setThumbnail( wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general) );
  419. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  420. if ( reaction ) reaction.removeEmoji();;
  421. }
  422. else {
  423. var pagelink = wiki.toLink(body.query.general.mainpage, querystring.toTitle(), fragment, body.query.general);
  424. var embed = new MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( body.query.general.mainpage.escapeFormatting() ).setURL( pagelink ).setThumbnail( wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general) );
  425. if ( body.query.allmessages[0]['*'] ) {
  426. embed.setDescription( body.query.allmessages[0]['*'] );
  427. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  428. if ( reaction ) reaction.removeEmoji();
  429. }
  430. else got.get( wiki.toDescLink(body.query.general.mainpage), {
  431. responseType: 'text'
  432. } ).then( descresponse => {
  433. var descbody = descresponse.body;
  434. if ( descresponse.statusCode !== 200 || !descbody ) {
  435. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  436. } else {
  437. var parser = new htmlparser.Parser( {
  438. onopentag: (tagname, attribs) => {
  439. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  440. var description = attribs.content.escapeFormatting();
  441. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  442. embed.setDescription( description );
  443. }
  444. }
  445. }, {decodeEntities:true} );
  446. parser.write( descbody );
  447. parser.end();
  448. }
  449. }, error => {
  450. console.log( '- Error while getting the description: ' + error );
  451. } ).finally( () => {
  452. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  453. if ( reaction ) reaction.removeEmoji();
  454. } );
  455. }
  456. }
  457. }, error => {
  458. if ( interwiki ) msg.sendChannel( spoiler + ' ' + interwiki.replace( /@(here|everyone)/g, '%40$1' ) + fragment + ' ' + spoiler );
  459. else if ( wiki.noWiki(error.message) ) {
  460. console.log( '- This wiki doesn\'t exist!' );
  461. msg.reactEmoji('nowiki');
  462. }
  463. else {
  464. console.log( '- Error while getting the search results: ' + error );
  465. msg.sendChannelError( spoiler + '<' + wiki.toLink(( querystring || fragment || !title ? title : 'Special:Search' ), ( querystring || fragment || !title ? querystring.toTitle() : 'search=' + title.toSearch() ), fragment) + '>' + spoiler );
  466. }
  467. if ( reaction ) reaction.removeEmoji();
  468. } );
  469. }
  470. }
  471. module.exports = fandom_check_wiki;