discord.js如何实现机器人仅在消息同时含两组指定关键词时自动回复
Discord机器人多关键词匹配自动回复解决方案
原代码问题
String.includes()仅支持传入单个字符串做匹配,你直接传入数组会触发隐式类型转换,将数组转为逗号拼接的字符串,无法匹配正常用户消息,所以不会触发回复- 此前用
indexOf全触发是匹配逻辑编写错误,未按「两类关键词各命中至少一个」的规则做判断
正确实现方案
用Array.some()方法遍历关键词数组,判断是否命中任意对应类别的关键词,再做联合判断即可实现需求,完整代码如下:
// 两类关键词统一转小写,避免大小写匹配失败 const helpDemandKeywords = ["help", "problems", "problem", "error", "issue"].map(k => k.toLowerCase()) const targetModuleKeywords = ["psutil", "pyinstaller"].map(k => k.toLowerCase()) const messageContent = message.content.toLowerCase() // 分别判断是否命中求助类关键词、指定模块类关键词 const hasHelpDemand = helpDemandKeywords.some(keyword => messageContent.includes(keyword)) const hasTargetKeyword = targetModuleKeywords.some(keyword => messageContent.includes(keyword)) if (hasHelpDemand && hasTargetKeyword) { const embed = new MessageEmbed() .setAuthor(`I'm here to help ${message.author.tag}!`,'https://img.icons8.com/fluency/48/000000/help.png',`${client.config.links.website}`) .setDescription(`**I think you need help with python and before asking more questions make sure to check out these pages/channels**\n\n> <#905804981368664075>\n> <#905224439736705087>`) // discord.js v13及以上版本需使用如下格式发送embed message.channel.send({ embeds: [embed] }) // 若为v12及以下版本,可替换为 message.channel.send(embed) }
内容的提问来源于stack exchange,提问作者TestUser404
相关产品推荐
相关产品推荐

