查询/响应,是/否与Javascript / jQuery接口

时间:2017-12-08 19:07:21

标签: javascript jquery sms chatbot

我是StackOverflow社区的菜鸟,就像我们作为javascript / jquery菜鸟一样。我正在尝试将一个类似于SMS文本消息的聊天界面放在一起。我目前正在允许用户输入文本输入,并让javascript查找指定的关键字(是/否)并在我的html中显示特定的隐藏div来模拟响应。

我一直在尝试利用CodePen示例(https://codepen.io/adobewordpress/pen/wGGMaV),这让我走得很远。但我也在寻找用户的重复是/否回复,如果用户说“是”"对于多个问题,javascript正在提供FIRST是/否响应。

我需要一种方法来包装我的问题并查找每个问题的特定用户输入答案,一旦收到输入,提供正确的响应 - 然后移动到下一个问题,这也将寻找是/否的回答用户。根据他们的回复,然后通过javascript提供问题2回复。转到问题3,查找是/否响应。等

非常感谢任何和所有帮助。希望即使作为一个菜鸟我也能理解并通过任何有用的回应。

我当前的CodePen(https://codepen.io/therise03/pen/bYXVLK)正在使用上面的逻辑解释,但希望它使用我的条件工作流程,如下面所示。

所需流程

条件1 [     问题:您想继续订阅杂志吗?文本CONTINUE继续或NO停止{

If Yes: go to Condition2
If No: “Thanks you are not subscribed”

}]

条件2 [     问题:您的总金额为$ XXXX.XX。您是否愿意使用存储卡支付订单?文本是继续或否定停止。 {

If Yes: go to Condition3
If No: “OK we will not use card on file”

条件3 [     问题3:我们需要确认此订单的送货地址。是123大街; O'Fallon,MO 63368对吗?文本是继续或否定停止。 {

If Yes: “OK address confirmed”
If No: “Address not confirmed”

1 个答案:

答案 0 :(得分:0)

在评论中我们进行了对话后,我以为我会提交答案。

我认为为我建立一个解决方案对我来说是一个很好的练习,虽然不干净,它可以工作,你可以改进它。

我只是从您的代码库中对JS进行了更改。

  

codepen:codepen.io/anon/pen/POMbNw?editors=0010

以下是代码不再可用的代码:

JS:

/* START: HELPERS */

function appendFromThem(msg){ // append a "fromThem" msg
  $('<div class="message"><div class="fromThem"><p>'+msg+'</p></div></div>').insertAfter('.message:last');
}

function appendFromMe(msg){ // append a "myMessage" msg
  $('form.chat div.messages').append('<div class="message"><div class="myMessage"><p>' + msg + '</p></div></div>');
}

function isString(str){ // check if param is a string
  return jQuery.type(str) === "string";
}

function areEqual(str1, str2){ // check if strings are the same after trimming and setting to lower case
  if(!isString(str1) || !isString(str1)) return str1 === str2; // either of them is not a string, use the normal "==="
  return str1.trim().toLowerCase() === str2.trim().toLowerCase();
}

/* END: HELPERS */

// workflow types
var WF_TYPE = {
  Q: "question",
  END: "end",
  NEW: "new" // start new workflow after cuttent one
}

/*
 * The workflow object
 * each sub-object should have a "msg" and responses typically "yes" and "no"
 */
var wf = {
  type:WF_TYPE.Q,
  msg:"Would you like to continue your magazine subscription? Text CONTINUE to continue or NO to stop.",
  continue:{
    type: WF_TYPE.Q,
    msg:"Your total will be $XXXX.XX. Would you like to pay for your order with your card on file? Text YES to continue or NO to stop.",
    yes:{
      type:WF_TYPE.Q,
      msg:"We need to confirm your shipping address for this order.  Is 123 Main Street; O’Fallon, MO  63368 correct? Text YES to continue or NO to stop.",
      yes: {
        endMsg: "OK address confirmed",
        msg: "some new question?",
        type : WF_TYPE.NEW,
        yes:{
          msg: "OK cool.",
          type: WF_TYPE.END
        },
        no:{
          msg: "NOT cool...",
          type: WF_TYPE.END
        }

      },
      no: {
        msg:"Address not confirmed",
        type:WF_TYPE.END
      }
    },
    no:{
      msg: "OK we will not use card on file",
      type: WF_TYPE.END
    }
  },
  no:{
    msg:"Thanks you are not subscribed",
    type: WF_TYPE.END
  }
}

/*
 * Transitions current workflow to the next based on user response
 * @param msgFromUser the msg that user typed
 * @returns a response object containing the new workflow, response and other options
 */
function transition(currentWorkflow, msgFromUser){
  console.log('getResponse start', currentWorkflow, msgFromUser);
  if (currentWorkflow.type === WF_TYPE.END){
    return {
      wf: $.extend({}, currentWorkflow)
    }
  }
  else if (currentWorkflow.type === WF_TYPE.Q){
    var newWorkflow;
    var found = false; // if a user reponse was found in current workflow
    $.each(currentWorkflow, function(key, val){ 
      if(!found && key !== "msg" && areEqual(key, msgFromUser)){ // check if user msg matches any of the valid responses
        newWorkflow = $.extend({}, val); // cone the value
        console.log("found it", newWorkflow)
        found = true;
      }
    });

    return {
      wf: newWorkflow ? newWorkflow : $.extend({}, currentWorkflow),
      errorResponse: found ? undefined : "Sorry, we didn’t understand your response. Please try again."
    }
  }
  else if(currentWorkflow.type === WF_TYPE.NEW){
    return {
      wf: $.extend({}, currentWorkflow)
    }
  }
}


function scrollDown() {
  var focusBottom = document.getElementById("textMessage");
  focusBottom.scrollTop = focusBottom.scrollHeight;
}


$("input").keypress(function(event) {
  if (event.which == 13) { // if user clicked enter, submit
    event.preventDefault();
    $('form.chat input[type="submit"]').click();
  }
});

//appendFromThem(wf.msg);
$('form.chat input[type="submit"]').click(function(event) {
  $input = $('form.chat input[type="text"]');
  event.preventDefault();
  var message = $input.val();
  appendFromMe(message);
  $defered = $.Deferred();
  var responseAndWf = transition(wf, message); // get response from workflow
  if(responseAndWf){
     wf = responseAndWf.wf;
     var response = responseAndWf.errorResponse ? responseAndWf.errorResponse : wf.msg;
     setTimeout(function() {
       if(wf.type !== WF_TYPE.NEW){
         appendFromThem(response);
       }
       scrollDown();
       $defered.resolve();
     }, 1500); 
  }

  if(wf.type === WF_TYPE.NEW){

    $defered.then(function(){
      appendFromThem(wf.endMsg);
      wf.type = WF_TYPE.Q;
      setTimeout(function() {
      appendFromThem(wf.msg);
      },2000)
    });
  }
  $input.val('');
  scrollDown();
});

CSS:

input, textarea, [contenteditable] {
    color: #666;
    caret-color: blue;
}

body {
    background: #fff; /* For browsers that do not support gradients */
    font-family: 'Rubik';
    font-weight: 300;
    color: #fff;
    font-size:16px;


}

h1 {
    color: #fff;
    font-family: 'Rubik';
    font-weight: 400;
}


::-webkit-input-placeholder { /* WebKit, Blink, Edge */
 color:    #cdced2;
}
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
 color:    #cdced2;
 opacity:  1;
}
::-moz-placeholder { /* Mozilla Firefox 19+ */
 color:    #cdced2;
 opacity:  1;
}
:-ms-input-placeholder { /* Internet Explorer 10-11 */
 color:    #cdced2;
}
::-ms-input-placeholder { /* Microsoft Edge */
 color:    #cdced2;
}
form.chat .myMessage, form.chat .fromThem {
    max-width: 90%;
}



form.chat *{
  transition:all .5s;
  box-sizing:border-box;
  -webkit-box-sizing:border-box;
  -moz-box-sizing:border-box;
}

form.chat {
  margin:0;
  cursor:default;
  position:absolute;
  left:0;
  right:0;
  bottom:0;
  top:0;
  -webkit-touch-callout: none; /* iOS Safari */
  -webkit-user-select: none;   /* Chrome/Safari/Opera */
  -khtml-user-select: none;    /* Konqueror */
  -moz-user-select: none;      /* Firefox */
  -ms-user-select: none;       /* IE/Edge */
  user-select: none;   
    border:0 none;
}

form.chat span.spinner{
  -moz-animation: loading-bar 1s 1;
  -webkit-animation: loading-bar 1s 1;
  animation: loading-bar 1s 1;
  display: block;
  height: 2px;
  background-color: #00e34d;
  transition: width 0.2s;
  position:absolute;
  top:0; left:0; right:0;
  z-index:4
}

form.chat .messages{
  display:block;
  overflow-x: hidden;
  overflow-y: scroll;
  position:relative;
  height:90%;
  width:100%;
  padding:1% 3% 7% 3%;
  border:0 none;

}

form.chat ::-webkit-scrollbar {width: 3px; height:1px;transition:all .5s;z-index:10;}
form.chat ::-webkit-scrollbar-track {background-color: white;}
form.chat ::-webkit-scrollbar-thumb {
  background-color: #bec4c8; 
  border-radius:3px;
}

form.chat .message{
  display:block;
  width:98%;
  padding:0.5%;
}

form.chat .message p{
  margin:0;
}

form.chat .myMessage,
form.chat .fromThem {
  max-width: 50%;
  word-wrap: break-word;
  margin-bottom: 20px;
}



form.chat .myMessage,.fromThem{
  position: relative;
  padding: 10px 20px;
  color: white;
  border-radius: 25px;
  clear: both;
  font: 400 15px 'Open Sans', sans-serif;
}

form.chat .myMessage {
  background: #00e34d;
  color:white;
  float:right;
  clear:both;
  border-bottom-right-radius: 20px 0px\9;
}

form.chat .myMessage:before {
  content: "";
  position: absolute;
  z-index: 1;
  bottom: -2px;
  right: -8px;
  height: 19px;
  border-right: 20px solid #00e34d;
  border-bottom-left-radius: 16px 14px;
  -webkit-transform: translate(0, -2px);
  transform: translate(0, -2px);
  border-bottom-left-radius: 15px 0px\9;
  transform: translate(-1px, -2px)\9;
}

form.chat .myMessage:after {
  content: "";
  position: absolute;
  z-index: 1;
  bottom: -2px;
  right: -42px;
  width: 12px;
  height: 20px;
  background: white;
  border-bottom-left-radius: 10px;
  -webkit-transform: translate(-30px, -2px);
  transform: translate(-30px, -2px);
}

form.chat .fromThem {
  background: #E5E5EA;
  color: black;
  float: left;
  clear:both;
  border-bottom-left-radius: 30px 0px\9;
}
form.chat .fromThem:before {
  content: "";
  position: absolute;
  z-index: 2;
  bottom: -2px;
  left: -7px;
  height: 19px;
  border-left: 20px solid #E5E5EA;
  border-bottom-right-radius: 16px 14px;
  -webkit-transform: translate(0, -2px);
  transform: translate(0, -2px);
  border-bottom-right-radius: 15px 0px\9;
  transform: translate(-1px, -2px)\9;
}

form.chat .fromThem:after {
  content: "";
  position: absolute;
  z-index: 3;
  bottom: -2px;
  left: 4px;
  width: 26px;
  height: 20px;
  background: white;
  border-bottom-right-radius: 10px;
  -webkit-transform: translate(-30px, -2px);
  transform: translate(-30px, -2px);
}

form.chat date {
  position:absolute;
  top: 10px;
  font-size:14px;
  white-space:nowrap;
  vertical-align:middle;
  color: #8b8b90;
  opacity: 0;
  z-index:4;
}

form.chat .myMessage date {
  left: 105%;
}

form.chat .fromThem date {
  right: 105%;
}

form.chat input{
  /* font: 400 13px 'Open Sans', sans-serif; */
  font: 400 1em 'Open Sans', sans-serif;
    border:0;
 /* padding:0 15px; */
    padding: 15px 15px 0 15px;
  height:10%;
  outline:0;
}

form.chat input[type='text']{
  width:73%;
  float:left;
}

form.chat input[type='submit']{
  width:23%;
  background:transparent;
  color:#00E34D;
  font-weight:700;
  text-align:right;
  float:right;
}

  form.chat .myMessage,form.chat .fromThem{
    font-size:1.1em;

  }



  form.chat .myMessage,
  form.chat .fromThem {
    max-width: 90%;
  }

@-moz-keyframes loading-bar {
  0% {
    width: 0%;
  }
  90% {
    width: 90%;
  }
  100% {
    width: 100%;
  }
}

@-webkit-keyframes loading-bar {
  0% {
    width: 0%;
  }
  90% {
    width: 90%;
  }
  100% {
    width: 100%;
  }
}

@keyframes loading-bar {
  0% {
    width: 0%;
  }
  90% {
    width: 90%;
  }
  100% {
    width: 100%;
  }
}

/* DEMO */
.iphone{
  /* 
    width:300px;
  height:609px;
  background-image:url('http://www.adobewordpress.com/tasarim/images/iphone6.png');
  background-size:100% 100%;
  margin:0 auto;
    */
    width:100%;

}

.border{
    /* position:absolute;
    top:12.3%;right:7%;left:7%;bottom:12%;
    overflow:hidden; */
}

a.article{
  position:fixed;
  bottom:15px;left:15px;
  display:table;
  text-decoration:none;
  color:white;
  background-color:#00e34d;
  padding: 10px 20px;
  border-radius: 25px;
  font: 400 15px 'Open Sans', sans-serif;
}

HTML:

<div class="iphone">
  <div class="imessage-header"></div>
  <div class="border">
    <form class="chat">
      <span></span>
      <div class="messages" id="textMessage">
        <div class="message">
          <div class="fromThem">
            <p>Would you like to continue your magazine subscription? Text CONTINUE to continue or NO to stop.</p>
          </div>
        </div>
        <div class="message magPrice" style="display:none;">
          <div class="fromThem new">
            <p>Your total will be $XXXX.XX. Would you like to pay for your order with your card on file? Text YES to continue or NO to stop.</p>
          </div>
        </div>
        <div class="message addressVerification" style="display:none;">
          <div class="fromThem new">
            <p>We need to confirm your shipping address for this order.  Is 123 Main Street; O’Fallon, MO  63368 correct? Text YES to continue or NO to stop.</p>
          </div>
        </div>
        <div class="message goToWeb" style="display:none;">
          <div class="fromThem new">
              <p>To change your shipping address go to this <a href="#">website</a>.</p>
          </div>
        </div>
      </div>
      <div style="position:fixed;bottom:0;left:0;border:1px solid #ddd;width:100%;z-index:101;background-color:#fff;height:50px;">
        <input type="text" placeholder="Your message" autofocus style="height:auto;">
        <input type="submit" value="Send" style="height:auto;">
      </div>
    </form>
  </div>
</div>