You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.js@v12:基于代码词参数单条消息构建RichEmbed的问题

解决方案:用正则表达式一次性提取多标记内容

我完全懂你的需求——想要通过单条消息里的title:、desc:、field1:标记,快速提取RichEmbed需要的三个部分,同时支持带空格的长文本,还得对普通用户友好。之前的单参数处理方式确实不够用,这里给你一个更优雅的实现方案:

核心思路

利用正则表达式的非贪婪匹配和正向预查特性,直接从完整的message.content里精准捕获每个标记对应的内容,不需要拆分args或者分步收集,完美适配你想要的输入语法。

完整代码实现

// 先定义你的命令前缀
const commandPrefix = '/commandname';
// 提取命令之后的所有内容(去掉前缀)
const inputContent = message.content.slice(commandPrefix.length).trim();

// 匹配title: 到下一个标记(desc:或field1:)或结尾的内容
const titleMatch = inputContent.match(/title:(.*?)(?=\sdesc:|\sfield1:|$)/);
const embed_title = titleMatch ? titleMatch[1].trim() : null;

// 匹配desc: 到field1:或结尾的内容
const descMatch = inputContent.match(/desc:(.*?)(?=\sfield1:|$)/);
const embed_desc = descMatch ? descMatch[1].trim() : null;

// 匹配field1: 到结尾的所有内容
const fieldMatch = inputContent.match(/field1:(.*)/);
const embed_field = fieldMatch ? fieldMatch[1].trim() : null;

// 用提取到的内容创建RichEmbed
if (embed_title && embed_desc && embed_field) {
  const embed = new Discord.MessageEmbed()
    .setTitle(embed_title)
    .setDescription(embed_desc)
    .addField('自定义字段标题', embed_field); // 这里替换成你需要的固定字段标题
  
  message.channel.send(embed);
} else {
  // 处理用户漏填参数的情况
  message.reply('请按照格式输入:`/commandname title:你的标题 desc:你的描述 field1:字段内容`');
}

代码细节说明

  1. 非贪婪匹配(.*?):确保只捕获当前标记到下一个标记之间的内容,不会把后面的参数错误包含进来(比如不会把desc:的内容抓到title:里)
  2. 正向预查(?=\sdesc:|\sfield1:|$):精准定位匹配的结束位置——要么是空格加下一个标记,要么是消息结尾,完美适配用户的输入习惯
  3. trim()处理:自动去除内容前后的多余空格,避免用户输入时的格式误差

示例测试

如果用户输入:

/commandname title:My awesome title! desc:This is a long description with multiple words and sentences. field1:Here's the field content that can also have spaces!

你会得到:

  • embed_title: "My awesome title!"
  • embed_desc: "This is a long description with multiple words and sentences."
  • embed_field: "Here's the field content that can also have spaces!"

这个方案完全满足你的需求:单条消息输入、支持长文本、语法清晰易懂,比分步收集或空格/换行分隔高效太多。

内容的提问来源于stack exchange,提问作者totalepremisere

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:02:51