repalce the dictioanry command to use wordnik

This commit is contained in:
Ayden Jahola 2024-09-14 21:51:31 +01:00
parent 89a486065a
commit 7616d82a8b
No known key found for this signature in database
GPG key ID: 71DD90AE4AE92742
3 changed files with 114 additions and 31 deletions

View file

@ -11,6 +11,7 @@ EMAIL_DOMAINS=example@example.com // or it can be a list, example: example.com,e
# API # API
RAPIDAPI_KEY=YOUR_RAPIDAPI_KEY // grab yours from https://rapidapi.com/community/api/urban-dictionary/playground/53aa4f68e4b07e1f4ebeb2b0 RAPIDAPI_KEY=YOUR_RAPIDAPI_KEY // grab yours from https://rapidapi.com/community/api/urban-dictionary/playground/53aa4f68e4b07e1f4ebeb2b0
WORDNIK_API_KEY=YOUR_WORDNIK_API_KEY // grab yours from https://developer.wordnik.com/
# Discord # Discord
GUILD_ID=YOUR_GUILD_ID GUILD_ID=YOUR_GUILD_ID

View file

@ -1,7 +1,15 @@
const { SlashCommandBuilder } = require("discord.js"); const { SlashCommandBuilder, EmbedBuilder } = require("discord.js");
const Word = require("../../models/wordModel"); const Word = require("../../models/wordModel");
const axios = require("axios"); const axios = require("axios");
const WORDNIK_API_KEY = process.env.WORDNIK_API_KEY;
// Function to clean up XML-like tags from the text
function cleanText(text) {
// Ensure text is a string and remove XML-like tags
return (text || "").replace(/<[^>]*>/g, "");
}
module.exports = { module.exports = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName("dictionary") .setName("dictionary")
@ -21,54 +29,120 @@ module.exports = {
async execute(interaction) { async execute(interaction) {
const word = interaction.options.getString("word").toLowerCase(); const word = interaction.options.getString("word").toLowerCase();
const isEphemeral = interaction.options.getBoolean("ephemeral") || false; const isEphemeral = interaction.options.getBoolean("ephemeral") || false;
const wordnikUrl = `https://www.wordnik.com/words/${word}`;
// Create the base embed
const embed = new EmbedBuilder()
.setColor("#0099ff")
.setTitle(`Dictionary: ${word.charAt(0).toUpperCase() + word.slice(1)}`)
.setURL(wordnikUrl) // Set URL to the Wordnik page for the word
.setFooter({
text: "Powered by Wordnik | Source: Loading...",
iconURL: "https://wordnik.com/favicon.ico",
});
// Try to find the word in the database // Try to find the word in the database
let result = await Word.findOne({ word }); let result = await Word.findOne({ word });
if (result) { if (result) {
// If the word is found in the database // If the word is found in the database
await interaction.reply({ embed
content: `**${result.word}**: ${result.definition}`, .setDescription(
ephemeral: isEphemeral, `**Definition:** ${cleanText(
result.definition || "No definition found"
)}\n` +
`**Part of Speech:** ${result.partOfSpeech || "Unknown"}\n` +
`**Attribution:** ${result.attributionText || "No attribution"}\n` +
`**Source Dictionary:** ${
result.sourceDictionary || "Unknown source"
}\n` +
`**Synonyms:** ${result.synonyms.join(", ") || "None found"}\n` +
`**Antonyms:** ${result.antonyms.join(", ") || "None found"}\n` +
`**Example:** ${result.exampleSentence || "No examples found"}`
)
.setURL(result.wordnikUrl || wordnikUrl)
.setFooter({
text: `Powered by Wordnik | Source: Database`,
iconURL: "https://wordnik.com/favicon.ico",
}); });
} else { } else {
// Fetch the word definition from an API if not found in the database // Fetch the word information from Wordnik API
try { try {
const response = await axios.get( // Fetch definitions
`https://api.dictionaryapi.dev/api/v2/entries/en/${word}` const definitionResponse = await axios.get(
`https://api.wordnik.com/v4/word.json/${word}/definitions`,
{
params: {
api_key: WORDNIK_API_KEY,
limit: 1,
includeRelated: true,
sourceDictionaries: "all",
useCanonical: true,
includeTags: false,
},
}
); );
const data = response.data;
if ( const definitionData = definitionResponse.data[0];
data && if (definitionData) {
data[0] && const definition = cleanText(
data[0].meanings && definitionData.text || "No definition found"
data[0].meanings[0] && );
data[0].meanings[0].definitions && const partOfSpeech = definitionData.partOfSpeech || "Unknown";
data[0].meanings[0].definitions[0] const attributionText =
) { definitionData.attributionText || "No attribution";
const definition = data[0].meanings[0].definitions[0].definition; const sourceDictionary =
definitionData.sourceDictionary || "Unknown source";
const wordnikUrl = definitionData.wordnikUrl || wordnikUrl;
// Example sentence extraction (make sure `exampleUses` is correctly handled)
const exampleSentence =
(definitionData.exampleUses &&
definitionData.exampleUses[0] &&
definitionData.exampleUses[0].text) ||
"No examples found";
// Save the new word and definition in the database // Save the new word and definition in the database
await Word.create({ word, definition }); await Word.create({
word,
definition,
partOfSpeech,
attributionText,
sourceDictionary,
exampleSentence,
wordnikUrl,
});
await interaction.reply({ embed
content: `**${word}**: ${definition}`, .setDescription(
ephemeral: isEphemeral, `**Definition:** ${definition}\n` +
`**Part of Speech:** ${partOfSpeech}\n` +
`**Attribution:** ${attributionText}\n` +
`**Source Dictionary:** ${sourceDictionary}\n` +
`**Example:** ${exampleSentence}`
)
.setURL(wordnikUrl); // Add a URL to the embed if available
embed.setFooter({
text: `Powered by Wordnik | Source: API`,
iconURL: "https://wordnik.com/favicon.ico",
}); });
} else { } else {
await interaction.reply({ embed.setDescription(
content: `Sorry, I couldn't find a definition for **${word}**.`, `Sorry, I couldn't find a definition for **${word}**.`
ephemeral: isEphemeral, );
});
} }
} catch (error) { } catch (error) {
console.error(error); console.error("Error fetching Wordnik data:", error.message);
embed.setDescription(
`An error occurred while fetching the definition for **${word}**. ${error.message}`
);
}
}
await interaction.reply({ await interaction.reply({
content: `An error occurred while fetching the definition for **${word}**.`, embeds: [embed],
ephemeral: isEphemeral, ephemeral: isEphemeral,
}); });
}
}
}, },
}; };

View file

@ -3,6 +3,14 @@ const mongoose = require("mongoose");
const wordSchema = new mongoose.Schema({ const wordSchema = new mongoose.Schema({
word: { type: String, required: true, unique: true }, word: { type: String, required: true, unique: true },
definition: { type: String, required: true }, definition: { type: String, required: true },
partOfSpeech: { type: String, default: "Unknown" },
attributionText: { type: String, default: "No attribution" },
sourceDictionary: { type: String, default: "Unknown source" },
synonyms: { type: [String], default: [] },
antonyms: { type: [String], default: [] },
exampleSentence: { type: String, default: "No examples found" },
wordnikUrl: { type: String, default: "" },
attributionUrl: { type: String, default: "" },
}); });
module.exports = mongoose.model("Word", wordSchema); module.exports = mongoose.model("Word", wordSchema);