random.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. const {MessageEmbed} = require('discord.js');
  2. const parse_page = require('../../functions/parse_page.js');
  3. const logging = require('../../util/logging.js');
  4. const {toMarkdown, htmlToDiscord, escapeFormatting} = require('../../util/functions.js');
  5. const extract_desc = require('../../util/extract_desc.js');
  6. /**
  7. * Sends a random Gamepedia page.
  8. * @param {import('../../util/i18n.js')} lang - The user language.
  9. * @param {import('discord.js').Message} msg - The Discord message.
  10. * @param {import('../../util/wiki.js')} wiki - The wiki for the page.
  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 {String[]} [namespace] - The namespace to get a random page of.
  14. * @param {URLSearchParams} [querystring] - The querystring for the link.
  15. * @param {String} [fragment] - The section for the link.
  16. */
  17. function gamepedia_random(lang, msg, wiki, reaction, spoiler, namespace = ['0', '*'], querystring = new URLSearchParams(), fragment = '') {
  18. var uselang = ( querystring.get('variant') || querystring.get('uselang') || lang.lang );
  19. got.get( wiki + 'api.php?uselang=' + uselang + '&action=query&meta=allmessages|siteinfo&amenableparser=true&amtitle=Special:Random&ammessages=randompage|randompage-nopages&amargs=%1F' + namespace[1] + '%1F' + namespace[0].split('|').length + '&siprop=general&prop=categoryinfo|info|pageprops|pageimages|extracts&piprop=original|name&ppprop=description|displaytitle|page_image_free|disambiguation|infoboxes&explaintext=true&exsectionformat=raw&exlimit=1&converttitles=true&generator=random&grnfilterredir=nonredirects&grnlimit=1&grnnamespace=' + namespace[0] + '&format=json' ).then( response => {
  20. var body = response.body;
  21. if ( body && body.warnings ) log_warn(body.warnings);
  22. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query || !body.query.general ) {
  23. if ( wiki.noWiki(response.url, response.statusCode) ) {
  24. console.log( '- This wiki doesn\'t exist!' );
  25. msg.reactEmoji('nowiki');
  26. }
  27. else {
  28. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  29. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Random', querystring, fragment) + '>' + spoiler );
  30. }
  31. if ( reaction ) reaction.removeEmoji();
  32. return;
  33. }
  34. wiki.updateWiki(body.query.general);
  35. logging(wiki, msg.guild?.id, 'random');
  36. if ( !body.query.pages ) {
  37. var title = 'Special:Random';
  38. if ( namespace[0] !== '0' && namespace[0].split('|').length === 1 ) title += '/' + namespace[1];
  39. var pagelink = wiki.toLink(title, querystring, fragment);
  40. var embed = new MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( escapeFormatting(title) ).setURL( pagelink ).setThumbnail( new URL(body.query.general.logo, wiki).href );
  41. if ( body.query.allmessages?.[0]?.['*']?.trim?.() ) {
  42. let displaytitle = escapeFormatting(body.query.allmessages[0]['*'].trim());
  43. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  44. embed.setTitle( displaytitle );
  45. }
  46. if ( body.query.allmessages?.[1]?.['*']?.trim?.() ) {
  47. var description = toMarkdown(body.query.allmessages[1]['*'], wiki, title, true);
  48. if ( description.length > 1000 ) description = description.substring(0, 1000) + '\u2026';
  49. embed.setDescription( description );
  50. }
  51. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  52. if ( reaction ) reaction.removeEmoji();
  53. return;
  54. }
  55. var querypage = Object.values(body.query.pages)[0];
  56. var pagelink = wiki.toLink(querypage.title, querystring, fragment);
  57. var text = '';
  58. var embed = new MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( escapeFormatting(querypage.title) ).setURL( pagelink );
  59. if ( querypage.pageprops && querypage.pageprops.displaytitle ) {
  60. var displaytitle = htmlToDiscord( querypage.pageprops.displaytitle );
  61. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  62. embed.setTitle( displaytitle );
  63. }
  64. if ( querypage.extract ) {
  65. var extract = extract_desc(querypage.extract, fragment);
  66. embed.backupDescription = extract[0];
  67. if ( extract[1].length && extract[2].length ) {
  68. embed.backupField = {name: extract[1], value: extract[2]};
  69. }
  70. }
  71. if ( querypage.pageprops && querypage.pageprops.description ) {
  72. var description = htmlToDiscord( querypage.pageprops.description );
  73. if ( description.length > 1000 ) description = description.substring(0, 1000) + '\u2026';
  74. embed.backupDescription = description;
  75. }
  76. if ( querypage.ns === 6 ) {
  77. var pageimage = ( querypage?.original?.source || wiki.toLink('Special:FilePath/' + querypage.title, {version:Date.now()}) );
  78. if ( msg.showEmbed() && /\.(?:png|jpg|jpeg|gif)$/.test(querypage.title.toLowerCase()) ) embed.setImage( pageimage );
  79. else if ( msg.uploadFiles() ) embed.attachFiles( [{attachment:pageimage,name:( spoiler ? 'SPOILER ' : '' ) + querypage.title}] );
  80. }
  81. else if ( querypage.title === body.query.general.mainpage ) {
  82. embed.setThumbnail( new URL(body.query.general.logo, wiki).href );
  83. }
  84. else if ( querypage.pageimage && querypage.original ) {
  85. embed.setThumbnail( querypage.original.source );
  86. }
  87. else if ( querypage.pageprops && querypage.pageprops.page_image_free ) {
  88. embed.setThumbnail( wiki.toLink('Special:FilePath/' + querypage.pageprops.page_image_free, {version:Date.now()}) );
  89. }
  90. else embed.setThumbnail( new URL(body.query.general.logo, wiki).href );
  91. if ( querypage.categoryinfo ) {
  92. var category = [lang.get('search.category.content')];
  93. if ( querypage.categoryinfo.size === 0 ) {
  94. category.push(lang.get('search.category.empty'));
  95. }
  96. if ( querypage.categoryinfo.pages > 0 ) {
  97. category.push(lang.get('search.category.pages', querypage.categoryinfo.pages.toLocaleString(lang.get('dateformat')), querypage.categoryinfo.pages));
  98. }
  99. if ( querypage.categoryinfo.files > 0 ) {
  100. category.push(lang.get('search.category.files', querypage.categoryinfo.files.toLocaleString(lang.get('dateformat')), querypage.categoryinfo.files));
  101. }
  102. if ( querypage.categoryinfo.subcats > 0 ) {
  103. category.push(lang.get('search.category.subcats', querypage.categoryinfo.subcats.toLocaleString(lang.get('dateformat')), querypage.categoryinfo.subcats));
  104. }
  105. if ( msg.showEmbed() ) embed.addField( category[0], category.slice(1).join('\n') );
  106. else text += '\n\n' + category.join('\n');
  107. }
  108. return parse_page(lang, msg, '🎲 ' + spoiler + '<' + pagelink + '>' + text + spoiler, embed, wiki, reaction, querypage, ( querypage.title === body.query.general.mainpage ? '' : new URL(body.query.general.logo, wiki).href ), fragment, pagelink);
  109. }, error => {
  110. if ( wiki.noWiki(error.message) ) {
  111. console.log( '- This wiki doesn\'t exist!' );
  112. msg.reactEmoji('nowiki');
  113. }
  114. else {
  115. console.log( '- Error while getting the search results: ' + error );
  116. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Random', querystring, fragment) + '>' + spoiler );
  117. }
  118. if ( reaction ) reaction.removeEmoji();
  119. } );
  120. }
  121. module.exports = {
  122. name: 'random',
  123. run: gamepedia_random
  124. };