I have a problem with the DeepL API which means that when I use the command, it doesn't give me the translated text but always the word "undefined".
I'll leave you my code, if you can help me please!
const fetch = require('node-fetch');
const deeplApiKey = "";
const config = require('../../config.js');
module.exports = {
name: 'traduction',
description: 'Permet de traduire le texte en anglais',
dm: false,
permission: 'Aucune',
category: "Utilitaires",
options: [
{
type: "string",
name: "text",
description: "Texte à traduire",
required: true,
},
],
async run(bot, interaction, args) {
await interaction.deferReply({ ephemeral: true });
try {
const response = await fetch('https://api-free.deepl.com/v2/translate', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
'auth_key': deeplApiKey,
'text': interaction.content,
'target_lang': 'EN'
})
});
const data = await response.json();
const translatedText = data.translations[0].text;
interaction.editReply({ content: translatedText, ephemeral: true })
} catch (error) {
interaction.editReply({ content: 'La traduction à échoué', ephemeral: true })
}
}
}
undefined
is not the string but something likenull
in other languages - there is notext
attribute on that object. There is an error in your request - the API key has to be passed as a header, as documented in the API docs.More generally, DeepL offers a Node library to interact with their API.