编程的新手,我正在制作一个Twitch聊天机器人,我想添加一个命令,使该机器人以文本文件中的随机行作为响应,而我正在努力寻找要使用的变量和/或模块
答案 0 :(得分:0)
mydata.json
带有字符串数组的JSON文件。
[
"This is a message",
"Where are you?",
"I'm calling from inside the house..."
]
main.js
const fs = require('fs');
// Read and parese the JSON file
const messages = JSON.parse(fs.readFileSync('mydata.json','utf8'));
// get a random message
function getRandomMessage() {
return messages[ Math.floor( Math.random() * messages.length ) ];
}
console.log(getRandomMessage());
因此,您希望它与短语匹配吗?我可以做得更好。通过使用regular expression,同一封邮件可以匹配多个短语。我还允许同一短语匹配多个消息,并且它随机选择匹配的消息之一。
random_messages.js
const fs = require('fs');
function readMessages(filename) {
// Read and parese the JSON file
const messages = JSON.parse(fs.readFileSync(filename,"utf8"));
// compile the regular expressions, case insensitive
for (const message of messages) message.match = new RegExp( message.match, "i" );
return messages;
}
// get a random message
function getRandomMessage(messges, phrase) {
// Get a list of all matching messages
const list = messages.filter( message => message.match.test( phrase ) );
// Return null if there was no matching messages
if (!list.length) return null;
// Select a random message from the list of matching messages
return list[ Math.floor( Math.random() * list.length ) ].text;
}
function test(messages) {
console.log(getRandomMessage(messages, "Hello everyone!"));
for (let i = 1; i <= 65536; i*=2) {
const phrase = `I have ${i} bottles`;
const response = getRandomMessage(messages, phrase);
console.log( "User:", phrase);
if (response) console.log("Bot", response);
}
}
// Read all the messages ( you should do that one time at program startup. NOT for every chat message)
const messages = readMessages("random_messages.json");
test(messages);
random_messages.json
[
{
"text": "This is a message",
"match": "^what is this\\?"
},
{
"text": "Where are you?",
"match" : "^hello\\b"
},
{
"text": "Who are you?",
"match" : "^hello\\b"
},
{
"text": "Hello!!!!",
"match" : "^hello\\b"
},
{
"text": "Hello!!!! Nice to meet you!",
"match" : "^hello\\b"
},
{
"text": "Hello!!! There you are! I'm been waiting for you!",
"match" : "^hello\\b"
},
{
"text": "Wow! That is plenty of bottles!",
"match" : "\\b(:?[1-9]\\d+|[5-9]) bottles\\b"
}
]