简体   繁体   中英

How to use a nested array to make a chatbot that can send messages based on your response?

I'm trying to make a simple chatbot in JavaScript that can send messages based on the user's input through an input field. How can I make it so the bot moves the conversation to the next array if it recognizes the correct response from the user?

Eg if you respond with pizza , it would continue with story2 . But if you respond with salads , it would pick story3 .

The conversations should be linear, so you cannot suddenly skip to story4 if you respond with medium while still at story1 .

var story1 = [
  { m: 'Hello!'},
  { m: 'Should I eat pizza or salads?'}, 
  { options: [
    { response: 'pizza', next: story2},
    { response: 'salads', next: story3},
  ]},
];

var story2 = [
  { m: 'Pizza it is!'},
  { m: 'What size pizza do you want?'},
  { options: [
    { response: 'medium', next: story4},
    { response: 'large', next: story5},
  ]},
];

var story3 = [
  { m: 'Salad it is!'},
];

var story4 = [
  { m: 'Ok! Medium pizza!'},
];

var story5 = [
  { m: 'Ok! Large pizza!'},
];

i think with object will be more easier than arrays... try this


    const response = userAnswer;

u will retrieve like this: obj[response].m or what ever you want


    const obj = {
    pizza: {
    key: 'story1,'
       m: 'Should I eat pizza or salads?', 
       options: [
         {response: 'pizza', next: story2},
        {response: 'salads', next: story3},
      ],
    },
    salads: {
      key: 'story3',
      m: 'Salad it is!',
    }
    }

Perhaps something like this:

const step = 0

const stories = [
    story1,
    story2,
    story3,
    ...
]

function triggerStepAction(e) {
    const currentStory = stories[step];
    const userInput = e.value;

    // Compare user input to possible responses
    // Trigger matching response and set step to next key story index
}

Your message structure could be simplified further to better match the approach. For example turning the "bot messages" in an array of messages, adding the options key to the top level of the object and making the story an object, like so:

const story = {
    messages: ['Hello!'],
    options: {
      "pizza": 2,
      "salads": 3 // Index of next story
    }
}

This way you can easily print out the messages by looping the messages array and select the picked option by using currentStory.options[userInput] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM