Why does my command always say "undefined"?

116 Views Asked by At

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 })
        }
    }
}

1

There are 1 best solutions below

7
On

undefined is not the string but something like null in other languages - there is no text 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.

const response = await fetch('https://api-free.deepl.com/v2/translate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Authorization': `DeepL-Auth-Key {deeplApiKey}`
                },
                body: new URLSearchParams({
                    'text': [interaction.content],
                    'target_lang': 'EN'
                })
            });

More generally, DeepL offers a Node library to interact with their API.