search.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. const {MessageEmbed, Util} = require('discord.js');
  2. const {got, escapeFormatting} = require('../../util/functions.js');
  3. const {limit: {search: searchLimit}} = require('../../util/default.json');
  4. /**
  5. * Searches a Gamepedia wiki.
  6. * @param {import('../../util/i18n.js')} lang - The user language.
  7. * @param {import('discord.js').Message} msg - The Discord message.
  8. * @param {String} searchterm - The searchterm.
  9. * @param {import('../../util/wiki.js')} wiki - The wiki for the search.
  10. * @param {Object} query - The siteinfo from the wiki.
  11. * @param {import('discord.js').MessageReaction} reaction - The reaction on the message.
  12. * @param {String} spoiler - If the response is in a spoiler.
  13. * @param {Boolean} noEmbed - If the response should be without an embed.
  14. */
  15. function gamepedia_search(lang, msg, searchterm, wiki, query, reaction, spoiler, noEmbed) {
  16. if ( searchterm.length > 250 ) {
  17. searchterm = searchterm.substring(0, 250);
  18. msg.reactEmoji('⚠️');
  19. }
  20. if ( !searchterm.trim() ) return this.special_page(lang, msg, {title: 'Special:Search'}, 'search', query, wiki, new URLSearchParams(), '', reaction, spoiler, noEmbed);
  21. var pagelink = wiki.toLink('Special:Search', {search:searchterm,fulltext:1});
  22. var resultText = '<' + pagelink + '>';
  23. var embed = null;
  24. if ( msg.showEmbed() && !noEmbed ) embed = new MessageEmbed().setAuthor( query.general.sitename ).setTitle( '`' + searchterm + '`' ).setURL( pagelink );
  25. else resultText += '\n\n**`' + searchterm + '`**';
  26. var querypage = ( Object.values(( query.pages || {} ))?.[0] || {title:'',ns:0,invalid:''} );
  27. var limit = searchLimit[( patreons[msg.guildId] ? 'patreon' : 'default' )];
  28. got.get( wiki + 'api.php?action=query&titles=Special:Search&list=search&srinfo=totalhits&srprop=redirecttitle|sectiontitle&srnamespace=4|12|14|' + ( querypage.ns >= 0 ? querypage.ns + '|' : '' ) + Object.values(query.namespaces).filter( ns => ns.content !== undefined ).map( ns => ns.id ).join('|') + '&srlimit=' + limit + '&srsearch=' + encodeURIComponent( searchterm ) + '&format=json' ).then( response => {
  29. var body = response.body;
  30. if ( body?.warnings ) log_warn(body.warnings);
  31. if ( response.statusCode !== 200 || !body?.query?.search || body.batchcomplete === undefined ) {
  32. return console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + body?.error?.info );
  33. }
  34. if ( body.query.search.length < limit ) {
  35. return got.get( wiki + 'api.php?action=query&list=search&srwhat=text&srinfo=totalhits&srprop=redirecttitle|sectiontitle&srnamespace=4|12|14|' + ( querypage.ns >= 0 ? querypage.ns + '|' : '' ) + Object.values(query.namespaces).filter( ns => ns.content !== undefined ).map( ns => ns.id ).join('|') + '&srlimit=' + limit + '&srsearch=' + encodeURIComponent( searchterm ) + '&format=json' ).then( tresponse => {
  36. var tbody = tresponse.body;
  37. if ( tbody?.warnings ) log_warn(tbody.warnings);
  38. if ( tresponse.statusCode !== 200 || !tbody?.query?.search || tbody.batchcomplete === undefined ) {
  39. return console.log( '- ' + tresponse.statusCode + ': Error while getting the text search results: ' + tbody?.error?.info );
  40. }
  41. body.query.search.push(...tbody.query.search.filter( tresult => {
  42. return !body.query.search.some( result => result.pageid === tresult.pageid );
  43. } ).slice(0, limit - body.query.search.length));
  44. if ( body.query.searchinfo && tbody.query.searchinfo ) body.query.searchinfo.totalhits += tbody.query.searchinfo.totalhits;
  45. }, error => {
  46. console.log( '- Error while getting the text search results: ' + error );
  47. } ).then( () => {
  48. return body;
  49. } );
  50. }
  51. return body;
  52. } ).then( body => {
  53. if ( !body?.query?.search ) return;
  54. if ( body.query.pages?.['-1']?.title ) {
  55. pagelink = wiki.toLink(body.query.pages['-1'].title, {search:searchterm,fulltext:1});
  56. resultText = '<' + pagelink + '>';
  57. if ( msg.showEmbed() && !noEmbed ) embed.setURL( pagelink );
  58. else resultText += '\n\n**`' + searchterm + '`**';
  59. }
  60. var hasExactMatch = false;
  61. var description = [];
  62. body.query.search.forEach( result => {
  63. let text = '• ';
  64. let bold = '';
  65. if ( result.title.replace( /[_-]/g, ' ' ).toLowerCase() === querypage.title.replace( /-/g, ' ' ).toLowerCase() ) {
  66. bold = '**';
  67. hasExactMatch = true;
  68. if ( query.redirects?.[0] ) {
  69. if ( query.redirects[0].tofragment && !result.sectiontitle ) {
  70. result.sectiontitle = query.redirects[0].tofragment;
  71. }
  72. if ( !result.redirecttitle ) result.redirecttitle = query.redirects[0].from;
  73. }
  74. }
  75. text += bold;
  76. if ( msg.showEmbed() && !noEmbed ) {
  77. text += '[' + escapeFormatting(result.title) + '](' + wiki.toLink(result.title, '', '', true) + ')';
  78. if ( result.sectiontitle ) {
  79. text += ' § [' + escapeFormatting(result.sectiontitle) + '](' + wiki.toLink(result.title, '', result.sectiontitle, true) + ')';
  80. }
  81. if ( result.redirecttitle ) {
  82. text += ' (⤷ [' + escapeFormatting(result.redirecttitle) + '](' + wiki.toLink(result.redirecttitle, 'redirect=no', '', true) + '))';
  83. }
  84. }
  85. else {
  86. text += '<' + wiki.toLink(result.title) + '>';
  87. if ( result.sectiontitle ) text += ' § ' + escapeFormatting(result.sectiontitle);
  88. if ( result.redirecttitle ) text += ' (⤷ ' + escapeFormatting(result.redirecttitle) + ')';
  89. }
  90. text += bold;
  91. description.push( text );
  92. } );
  93. if ( !hasExactMatch ) {
  94. if ( query.interwiki?.[0] ) {
  95. let text = '• **⤷ ';
  96. if ( msg.showEmbed() && !noEmbed ) {
  97. text += '__[' + escapeFormatting(query.interwiki[0].title) + '](' + query.interwiki[0].url.replace( /[()]/g, '\\$&' ) + ')__';
  98. if ( query.redirects?.[0] ) {
  99. text += ' (⤷ [' + escapeFormatting(query.redirects[0].from) + '](' + wiki.toLink(query.redirects[0].from, 'redirect=no', '', true) + '))';
  100. }
  101. }
  102. else {
  103. text += '__<' + query.interwiki[0].url.replace( /[()]/g, '\\$&' ) + '>__';
  104. if ( query.redirects?.[0] ) text += ' (⤷ ' + escapeFormatting(query.redirects[0].from) + ')';
  105. }
  106. text += '**';
  107. description.unshift( text );
  108. }
  109. else if ( querypage.invalid === undefined && ( querypage.missing === undefined || querypage.known !== undefined ) ) {
  110. let text = '• **';
  111. if ( msg.showEmbed() && !noEmbed ) {
  112. text += '[' + escapeFormatting(querypage.title) + '](' + wiki.toLink(querypage.title, '', '', true) + ')';
  113. if ( query.redirects?.[0] ) {
  114. if ( query.redirects[0].tofragment ) {
  115. text += ' § [' + escapeFormatting(query.redirects[0].tofragment) + '](' + wiki.toLink(querypage.title, '', query.redirects[0].tofragment, true) + ')';
  116. }
  117. text += ' (⤷ [' + escapeFormatting(query.redirects[0].from) + '](' + wiki.toLink(query.redirects[0].from, 'redirect=no', '', true) + '))';
  118. }
  119. }
  120. else {
  121. text += '<' + wiki.toLink(querypage.title) + '>';
  122. if ( query.redirects?.[0] ) {
  123. if ( query.redirects[0].tofragment ) text += ' § ' + escapeFormatting(query.redirects[0].tofragment);
  124. text += ' (⤷ ' + escapeFormatting(query.redirects[0].from) + ')';
  125. }
  126. }
  127. text += '**';
  128. description.unshift( text );
  129. }
  130. }
  131. var footer = '';
  132. if ( body.query.searchinfo ) {
  133. footer = lang.get('search.results', body.query.searchinfo.totalhits.toLocaleString(lang.get('dateformat')), body.query.searchinfo.totalhits);
  134. }
  135. if ( msg.showEmbed() && !noEmbed ) {
  136. if ( description.length ) embed.setDescription( Util.splitMessage( description.join('\n') )[0] );
  137. if ( footer ) embed.setFooter( footer );
  138. }
  139. else {
  140. if ( description.length ) resultText += '\n' + Util.splitMessage( description.join('\n'), {maxLength: 1995 - resultText.length - footer.length} )[0];
  141. if ( footer ) resultText += '\n' + footer;
  142. }
  143. }, error => {
  144. console.log( '- Error while getting the search results.' + error );
  145. } ).then( () => {
  146. msg.sendChannel( {content: '🔍 ' + spoiler + resultText + spoiler, embeds: [embed]} );
  147. if ( reaction ) reaction.removeEmoji();
  148. } );
  149. }
  150. module.exports = {
  151. name: 'search',
  152. run: gamepedia_search
  153. };