Discord机器人发送歌词嵌入报错DiscordAPIError[50035]求助
问题解决:DiscordAPIError[50035] 无效表单内容(嵌入消息错误)
错误原因分析
你遇到的DiscordAPIError[50035]是因为发送的嵌入消息(Embed)包含Discord API不接受的无效值,同时歌词分割逻辑存在小问题:
- Embed字段值为null:Discord API不允许Embed的
title字段设为null,你当前代码对非第一个Embed设置title: null,触发了表单验证错误。 - 换行替换逻辑错误:分割函数中使用字符串
'/\\n/g'作为replace的第一个参数,这只会替换匹配到的第一个该字符串,而非所有换行符,导致分割后的歌词格式混乱。
修正方案
1. 修正Embed创建逻辑
移除title: null的设置,仅在第一个Embed中添加title字段,其他Embed不包含该字段:
return new EmbedBuilder({ ...(isFirst && { title: `${data.title} - ${data.author}` }), description: value, });
使用扩展运算符...结合条件判断,只有当isFirst为true时才将title属性加入Embed配置,避免传递null值。
2. 修复歌词分割函数的换行替换
将字符串形式的正则改为真正的正则表达式,确保替换所有换行符:
function substring(length, value){ const replaced = value.replace(/\n/g, '--'); // 去掉引号,使用正则表达式 const regex = `.{1,${length}}`; const lines = replaced .match(new RegExp(regex, "g")) .map(line => line.replace(/--/g, '\n')); return lines; }
3. 完整修正后的代码
let title = interaction.options.getString('song'); await interaction.deferReply(); if(!title){ if(!queue.playing()){ return await interaction.followUp( 'Please provide a valid song and try again!' ) } title = queue.nowPlaying(); } function substring(length, value){ const replaced = value.replace(/\n/g, '--'); const regex = `.{1,${length}}`; const lines = replaced .match(new RegExp(regex, "g")) .map(line => line.replace(/--/g, '\n')); return lines; } const songTitle = title; const url = new URL('https://some-random-api.ml/lyrics'); url.searchParams.append('title', songTitle); console.log("url: ", url); try{ const { data } = await axios.get(url.href); const embeds = substring(500, data.lyrics).map((value, index) => { const isFirst = index === 0; return new EmbedBuilder({ ...(isFirst && { title: `${data.title} - ${data.author}` }), description: value, }) }); // 确保embeds数组不为空再发送 if (embeds.length === 0) { return await interaction.followUp({ content: 'No lyrics found for this song.' }); } return await interaction.followUp({ embeds }); } catch(err){ console.log(err) await interaction.followUp({ content: 'Sorry but I am not able to find lyrics for that song title' }); }
额外注意事项
- Discord API限制单次消息最多包含10个Embed,如果歌词分割后超过10段,需要分多次调用
followUp发送。 - 每个Embed的
description字段最大支持2048字符,你当前设置的500字符分割是安全的,也可以根据需求调整到接近2048的数值(比如2000)减少消息数量。
内容的提问来源于stack exchange,提问作者vixitu
相关产品推荐
相关产品推荐

