如何使用message.content存储Discord聊天消息及解决消息响应异常问题
Discord机器人问题修复方案
- 开启消息内容权限
进入Discord开发者平台的机器人应用后台,在Bot设置页开启Message Content Intent开关,否则机器人无法读取普通用户消息的content字段值。 - 修正打印逻辑
原代码打印的是完整Message对象,需要指定打印message.content才能获取用户发送的文本内容。 - 修正匹配逻辑
toLowerCase是可执行方法,必须加括号()才会返回小写转换后的结果,且转换为小写后要和小写的目标字符串对比,否则匹配永远为假。 - 修正消息发送语法
原代码message.channel.send(...) + message.author语法无效,需要把@用户的逻辑拼接进发送参数中。 - 补充防死循环逻辑
新增忽略机器人自身消息的判断,避免机器人触发自己的监听逻辑形成死循环。
修复后完整代码:
var name = "Poker Bot"; var allIn = "PUSH ALL IN"; var fold = "FOLD"; var tripleBBRaise = "3 BB RERAISE" let usersHand; //starts the bot and sets activity to a funny quote. it also will give a command prompt notification that the bot is online client.on("ready", () => { console.log(`Bot is online: ${name} !`); client.user.setActivity('Burning The Darn Casino Down'); }); //check discord chat to see if a user has posted. client.on("messageCreate", message => { // 忽略机器人自身发送的消息 if(message.author.bot) return; /*test to see if the chat input works.if working the users message will be saved as a string and then written in the console*/ console.log(`The user has said: ${message.content} `); // 保存用户消息到指定变量 usersHand = message.content; const lowerContent = message.content.toLowerCase() //Users input will be a poker hand. If it is one of the 3 below then tell the user the given string if (lowerContent == '/ak' || lowerContent == '/aa' || lowerContent == '/kk'){ message.channel.send(`<@${message.author.id}> RECOMMENDED PLAY: ${allIn}`) } });
内容的提问来源于stack exchange,提问作者npmackay
相关产品推荐
相关产品推荐

