15.QUIZ微信ロボットのダイナミック機能

5378 ワード

今日の質問:微信ロボットに話を教える
微信ロボットの会話を教える機能を作りましょう.

HTML

<div class="container">
        <div class="box-1">
            뀨ㅋ
        </div>
        <div class="box-2">
            <p>🦧</p>
        </div>
        <div class="box-3">
            <input type="text" class="chat_input"><br/>
            <button class="chat_btn">시키기</button>
        </div>
        
        <!-- <p>ex. 불꺼줘,불켜줘,따라해봐,그만해 뀨ㅋ</p> -->
    </div>

JS

//챗봇만들기
const body = document.getElementById('body');
const chat = document.querySelector('.box-1');
const chatInput = document.querySelector('.chat_input');
const chatBtn = document.querySelector('.chat_btn');
var question = '';
var answer = '';
var key = 0;

var json = 
[
  {
    'question' : '안녕',
    'answer' : 'ㅎㅇ!'
  },
  {
    'question' : '나이',
    'answer' : '비밀~'
  },
  {
    'question' : '이름',
    'answer' : '스펀지밥!'
  }
]

chatBtn.addEventListener('click',()=>{ 
    value = chatInput.value;

    if(key == 1){
      if(value == 'Yes'){
        chat.innerHTML = '대답을 입력해주셈!'
        key = 2;
      }else{
        chat.innerText = '?!'
        key = 0;
      }
      return;
    }if(key == 2){
      answer = value;
      push_json()
      return;
    }

  for(let i = 0; i < json.length; i++){
    if(value === json[i].question){
      chat.innerText = json[i].answer;
      return;
    }
  }

  chat.innerText = value+'??? 대답 가르쳐 주셈!(Yes or No)'
  question = value;
  key = 1;

 })

 function push_json(){
   json.push( { question : `${question}`, answer : `${answer}` } );
   console.log(json)
   chat.innerHTML = '습득완료'
   key = 0;
 }