使用DeepL API调用命令返回undefined问题排查求助
排查DeepL API返回"undefined"的问题
下面是导致你遇到问题的几个核心原因及对应修复方案:
1. API密钥未正确配置
你的代码里deeplApiKey是空字符串,且已经引入了config.js,却没有从配置文件读取密钥。DeepL API会因未授权返回异常响应,直接导致data.translations不存在,最终出现undefined。
修复:
const deeplApiKey = config.deeplApiKey; // 确保config.js中配置了deeplApiKey字段
2. 错误获取待翻译文本
在Slash Command场景下,interaction.content不是获取用户输入参数的正确方式(这个属性适用于普通消息命令)。你已经定义了名为text的必填参数,应该通过options对象获取。
修复:
'text': interaction.options.getString('text'),
3. 未检查请求状态&缺失错误日志
当前代码既没有验证请求是否成功(比如HTTP 401未授权、400参数错误),也没有在报错时输出具体信息,导致你无法定位问题根源。
修复:
在获取response后添加状态检查:
if (!response.ok) { throw new Error(`请求失败: ${response.status} ${response.statusText}`); }
在catch块中添加错误日志:
console.error('翻译错误详情:', error);
4. 未处理翻译结果为空的情况
如果请求参数无效(比如text为空),DeepL可能返回空的translations数组,此时直接访问data.translations[0].text会触发报错。
修复:
用可选链安全访问结果:
const translatedText = data.translations?.[0]?.text || '无法获取翻译结果';
修改后的完整代码
const fetch = require('node-fetch'); const config = require('../../config.js'); const deeplApiKey = config.deeplApiKey; 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.options.getString('text'), 'target_lang': 'EN' }) }); if (!response.ok) { throw new Error(`请求失败: ${response.status} ${response.statusText}`); } const data = await response.json(); const translatedText = data.translations?.[0]?.text || '无法获取翻译结果'; interaction.editReply({ content: translatedText, ephemeral: true }) } catch (error) { console.error('翻译错误详情:', error); interaction.editReply({ content: 'La traduction à échoué', ephemeral: true }) } } }
内容的提问来源于stack exchange,提问作者AirZoma
相关产品推荐
相关产品推荐

