Как я могу сделать пользовательские карты ответа для моего чат-бота - PullRequest
2 голосов
/ 25 апреля 2019

Я хочу создать пользовательскую карточку ответа, используя html, css и js, чтобы дать пользователю возможность выбрать. Я сделал лямбду, т.е. подключился к моему lex chatbot через API-интерфейс шлюза API, и он возвращает карточку ответа json все, что мне нужно это преобразовать это в мою карточку ответа для моих сайтов chatbot

Я уже пробовал, но карты начальной загрузки здесь не работают. Я делаю jquery ajax POST, чтобы получить мой json из лямбды. Пожалуйста, помогите заранее спасибо

{
    "ResponseMetadata": {
        "RequestId": "65e1b452-65e4-11e9-ab8a-d328589017aa",
        "HTTPStatusCode": 200,
        "HTTPHeaders": {
            "content-type": "application/json",
            "date": "Tue, 23 Apr 2019 16:25:25 GMT",
            "x-amzn-requestid": "65e1b452-65e4-11e9-ab8a-d328589017aa",
            "content-length": "709",
            "connection": "keep-alive"
        },
        "RetryAttempts": 0
    },
    "intentName": "HotelReservation",
    "slots": {
        "FromDate": null,
        "Location": null,
        "adultCount": null,
        "checkOutDate": null,
        "childCount": null,
        "childExists": null,
        "noOfRooms": null,
        "searchHotel": null,
        "welcome": null
    },
    "sessionAttributes": {},
    "message": "I am iSearchBot,I can help you book a hotel",
    "messageFormat": "PlainText",
    "dialogState": "ElicitSlot",
    "slotToElicit": "welcome",
    "responseCard": {
        "version": "1",
        "contentType": "application/vnd.amazonaws.card.generic",
        "genericAttachments": [
            {
                "title": "Do you want to book a Hotel",
                "imageUrl": "https://pbs.twimg.com/profile_images/1034820690463997957/TZEsJwEa_400x400.jpg",
                "buttons": [
                    {
                        "text": "Yes",
                        "value": "Yes"
                    },
                    {
                        "text": "No",
                        "value": "No"
                    }
                ]
            }
        ]
    }
}

Это мой код jquery, пожалуйста, помогите мне: -

function getChatResponse(requestStringForChat){

                var value={

                  'DestinationBot': "iSearchBot",

                  'SenderID': "12345",

                  'botAlias': "iSearchBotBeta",

                  'message': {

                                'text': requestStringForChat

                  }

                };

                console.log(value);

                value=JSON.stringify(value);

                $.ajax({

                  url:'https://ym4j4pt5mf.execute-api.us-east-1.amazonaws.com/Beta/',

                  method:'POST',

                  dataType:'application/json',

                  data:value,

                  dataType: 'json',

                  success:function(msg){
                            console.log(msg);
                            console.log('inside getchatresponse: ',requestStringForChat);
                            chat_id++;
                            var chatitem={};
                            chatitem['chatID']=chat_id;
                            chatitem['chatType']='Response';
                            chatitem['chatText']=msg['message'];
    //                      const content = 
    //     `<h4>${data.message}</h4>
    //     ${data.responseCard.genericAttachments.map(attachment => 
    //     `<div class="card" style="width: 18rem;">
    //       <img class="card-img-top" src="${attachment.imageUrl}" alt="Card image cap">
    //       <div class="card-body">
    //         <h5 class="card-title">Card title</h5>
    //         <p class="card-text">${attachment.title}</p>
    //         ${attachment.buttons.map(button => `<a href="#" class="btn btn-primary">${button.text}</a>`).join('')}
    //       </div>
    //     </div>`).join('')}`;
    // $("#card").html(content)
                            // console.log("Response card value="+msg["responseCard"]["contentType"]);
                            // if(msg["responseCard"]["contentType"]!=null)
                            // {
                            //  chatitem['htmlContent']='<span class="chat-response pull-right">'+msg['message']+'<br/><br/>'+msg["responseCard"]["contentType"]["genericAttachments"]["title"]+'</span><br><br>';
                            // }
                            // else{
                                chatitem['htmlContent']='<span class="chat-response pull-right">'+msg['message']+'</span><br><br>';
                            // }
                            chat.push(chatitem);
                            console.log(chat);
                            print();
                            //return chat;


            }});



    }

    function iChat(){    
        var chatMsg=$("#input-chat-text").val();    
        console.log($('#input-chat-text').val());
        chat_id++;
        var chatitem={};

        chatitem['chatID']=chat_id;
        chatitem['chatType']='Request';
        chatitem['chatText']=$('#input-chat-text').val();
        chatitem['htmlContent']='<span class="chat-request pull-left">'+$('#input-chat-text').val()+'</span><br><br>';
        chat.push(chatitem);
        console.log(chat);
        getChatResponse(chatMsg);
    }
    $('#chat-button-send').click(function(){
        iChat();
        console.log('clicked!')
        //console.log('chat is = '+JSON.stringify(iChat()));
        var msgBody='';
        console.log(chat.length);
        for(var myobject in chat){
            console.log(chat[myobject]["htmlContent"]);
            msgBody+=chat[myobject]["htmlContent"];
        }
        console.log('Printing msgBody'+msgBody)
        $('.chat-body').html(msgBody);
        $('#input-chat-text').val('');
    });
    function print()
    {
        var msgBody='';
        console.log(chat.length);
        for(var myobject in chat){
            console.log(chat[myobject]["htmlContent"]);
            msgBody+=chat[myobject]["htmlContent"];
        }
        console.log('Printing msgBody'+msgBody)
        $('.chat-body').html(msgBody);
    }

1 Ответ

1 голос
/ 25 апреля 2019
const data = JSON.parse(data_from_jqery_ajax);
    const content = 
        `<h4>${data.message}</h4>
        ${data.responseCard.genericAttachments.map(attachment => 
        `<div class="card" style="width: 18rem;">
          <img class="card-img-top" src="${attachment.imageUrl}" alt="Card image cap">
          <div class="card-body">
            <h5 class="card-title">Card title</h5>
            <p class="card-text">${attachment.title}</p>
            ${attachment.buttons.map(button => `<a href="#" class="btn btn-primary">${button.text}</a>`).join('')}
          </div>
        </div>`).join('')}`;
    $("#card").html(content);

<div id="card"></div>
...