Discord.js v14 serverinfo斜杠命令报错:字符串类型验证失败
问题分析与解决思路
问题根源
报错信息明确显示,EmbedBuilder.addFields() 中多个字段的 value 期望接收字符串原始类型,但实际传入了数字(如16、1、5等)。Discord.js 的嵌入消息字段要求 value 必须是字符串,而你的代码里以下字段直接传入了数字值:
- 各类频道的统计数量(
length返回数字) guild.memberCount(成员总数,数字类型)guild.roles.cache.size(角色数量,数字类型)
这些数字类型的值不符合字段的类型校验规则,因此触发了 CombinedPropertyError。
解决方法
将所有数字类型的 value 转换为字符串,常用两种方式:
- 调用数字的
toString()方法 - 用模板字符串
`${数字}`包裹
修改后的代码
const { SlashCommandBuilder, EmbedBuilder } = require("discord.js"); module.exports = { data: new SlashCommandBuilder() .setName("serverinfo") .setDescription("Provides information about the server.") .setDMPermission(false), async execute(client, interaction) { const { guild } = interaction; const embed = new EmbedBuilder() .setColor("#2B2D31") .setTitle(`${guild.name} - Server info`) .setThumbnail(guild.iconURL({ size: 256 })) .setImage(guild.bannerURL({ size: 256 })) .addFields( { name: "Owner", value: (await guild.fetchOwner()).user.tag, inline: true }, // 将数字转为字符串,同时用size替代toJSON().length提升效率 { name: "Text Channels", value: guild.channels.cache.filter((c) => c.type === 0).size.toString(), inline: true }, { name: "Voice Channels", value: guild.channels.cache.filter((c) => c.type === 2).size.toString(), inline: true }, { name: "Category Channels", value: guild.channels.cache.filter((c) => c.type === 4).size.toString(), inline: true }, { name: "Members", value: guild.memberCount.toString(), inline: true }, { name: "Roles", value: guild.roles.cache.size.toString(), inline: true }, // 优化角色列表输出,仅提取角色名称 { name: "Role List", value: guild.roles.cache.map(role => role.name).join(', ') } ); interaction.reply({ embeds: [embed] }); }, };
额外优化说明:
- 直接使用集合的
size属性替代toJSON().length,更高效且语义更清晰 - 角色列表通过
map(role => role.name)提取角色名称,避免直接转JSON导致的格式混乱
内容的提问来源于stack exchange,提问作者Jonny
相关产品推荐
相关产品推荐

