我有一个问题。我使用聊天机器人,我想添加更多的单词,但它不起作用。我如何使用带有单词的数组?
感谢您的帮助。
function bot(message) {
var words = ['hello', 'hi', 'hey'];
if(wordChecker(message, words)) {
var messageArray = [
'Hello to you too!',
'I said hello first :)',
'Greeting, human.'
];
sendMessage(messageArray);
}
else if (wordChecker(message, words)) {
var words = ['1', '2', '3'];
var messageArray = [
'Word1',
'Word2',
'Word3'
];
sendMessage(messageArray);
}
else if (message.indexOf('good fine') >= 0) {
var messageArray = [
'Okay, so what do you want to talk about?',
'Okay, what is your problem? Tell me.',
'Do you have something to say? Say it. Let it out your chest.'
];
sendMessage(messageArray);
}
WordChecker功能:
function wordChecker(message, words){
var has = false;
for (var i = 0; i < words.length; i++) {
if(message.indexOf(words[i])) {
has = true;
}
}
return has;
}
答案 0 :(得分:1)
您希望扩展代码,我在一开始就添加了database
数组,以将您的代码和数据部分分开。
function bot(message) {
var database = {
'hello|hi|hey' : ['Hello to you too!','I said hello first :)','Greeting, human.'], //Separate with | if you want output when any one of all is match
'mango|banan' : ['I am mango man!','I Love Mango :)','Mangoes are my favrout.'], // Another words' set
'price' : ['What is price of your services!','What best price you can give me :)','My price is unbearable.','Can you give me down time'] // Single Varialbe
};
var output = [];
for (var words in database) {
if (database.hasOwnProperty(words)) {
$constraint_or = words.split("|");
for (i=0; i<$constraint_or.length; ++i)
if(message.indexOf($constraint_or[i]) >= 0){
output = output.concat(database[words]);
break;
}
}
}
console.log(output); // For testing output
if(output.length>0)
sendMessage(output);
}
bot("hi hello"); // Calling for test
答案 1 :(得分:0)
function bot(message) {
if (message.indexOf('hello') >= 0) {
var messageArray = [
'Hello to you too!',
'I said hello first :)',
'Greeting, human.'
];
return messageArray;
}
}
console.log(bot("hello ok "));
你错过了分号吗?
答案 2 :(得分:0)
我并不完全确定我的理解是否正确,但从我的解释来看,这听起来就像你只需要&#34;或&#34;操作
if (message.indexOf('hello') >= 0 || message.indexOf('hi') >= 0 || message.indexOf('sup') >= 0) {
// Other logic
}
编辑:
改为使用函数:
// First argument is you message
// Second argument is your array of words
function wordChecker(message, words){
var has = false;
for (var i = 0; i < words.length; i++) {
if(message.indexOf(words[i])) {
has = true;
}
}
return has;
}
然后使用该功能你可以做:
var words = ['hello', 'hi', 'hey'];
if(wordChecker(message, words)) {
// other logic here
}