Как я могу создать индивидуальные карточки ответов для моего чат-бота

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

Я уже пробовал, но карты начальной загрузки здесь не работают. Я делаю 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);
    }

person gourabk    schedule 25.04.2019    source источник


Ответы (1)


person    schedule
comment
Я думаю, у меня проблема с интеграцией вашего кода, не могли бы вы помочь - person Gourab Konar; 25.04.2019
comment
@GourabKonar С какой проблемой вы столкнулись? - person Jayram Kumar; 25.04.2019
comment
Я даю ответ примерно так: - chatitem ['htmlContent'] = '‹span class = chat-response pull-right›' + msg ['message'] + '‹/span› ‹br› ‹br›'; - person Gourab Konar; 25.04.2019
comment
@GourabKonar Вы пробовали разобрать JSON? Надеюсь, msg - это проанализированный JSON. Вы получили chatitem с document.document.getElementById("card")? Если это так, то chatitem.innerHtml = '<span>...<br>' должно работать. Я никогда не использовал htmlContent. - person Jayram Kumar; 25.04.2019
comment
Вы можете увидеть мой код, что я сделал сейчас, можете ли вы предложить мне решение - person gourabk; 25.04.2019
comment
@Jayram Kumar, можете ли вы помочь мне с моим текущим кодом? Я поделился своим кодом - person Gourab Konar; 26.04.2019