Advertisement
Frostyy22

wikipedia.js

Apr 12th, 2023
723
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const wiki = require('wikijs').default();
  2. const {EmbedBuilder} = require('discord.js');
  3.  
  4. async function wikipedia(interaction){
  5.     if (interaction.commandName === 'wiki') {
  6.         const searchQuery = interaction.options.get('search').value;
  7.         interaction.deferReply();
  8.         try {
  9.         const search = await wiki.search(searchQuery);
  10.         if (search.results.length === 0) {
  11.           interaction.editReply("No Wikipedia page found for that query.");
  12.           return;
  13.         }
  14.         const result = await wiki.page(search.results[0]);
  15.         const summary = await result.summary();
  16.         const imageUrl = await result.mainImage();
  17.         if (summary.length > 2048) {
  18.           const truncatedSummary = summary.slice(0, 2045);
  19.           const lastPeriodIndex = truncatedSummary.lastIndexOf('.');
  20.           const finalSummary = truncatedSummary.slice(0, lastPeriodIndex + 1) + '';
  21.  
  22.           const embed = new EmbedBuilder()
  23.             .setColor('White')
  24.             .setTitle(`Wikipedia search: ${result.raw.title}`)
  25.             .setDescription(finalSummary)
  26.             .setThumbnail(imageUrl)
  27.             .addFields({ name: '\u200b', value: '\u200b' })
  28.             .addFields({ name: 'Read More:', value: `[${result.raw.title}](${result.raw.fullurl})`});
  29.           interaction.editReply({ embeds: [embed] });
  30.         } else {
  31.           const embed = new EmbedBuilder()
  32.             .setColor('White')
  33.             .setTitle(`Wikipedia search: ${result.raw.title}`)
  34.             .setDescription(summary)
  35.             .setThumbnail(imageUrl)
  36.             .addFields({ name: '\u200b', value: '\u200b' })
  37.             .addFields({ name: 'Read More:', value: `[${result.raw.title}](${result.raw.fullurl})`});
  38.           interaction.editReply({ embeds: [embed] });
  39.         }      
  40.       } catch (err){
  41.         interaction.editReply(`An error occurred while searching.\n\n${err}`)
  42.       }
  43.     }
  44. }
  45.  
  46. module.exports = wikipedia;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement