机器人回复建议的操作时如何隐藏/显示发件箱 [英] How to Hide / Show the Sendbox whenever the bot replies with the suggested action

查看:89
本文介绍了机器人回复建议的操作时如何隐藏/显示发件箱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Azure Chat bot(v4 MS bot框架)并应用于直接线路渠道,而且我正在发送

I'm using Azure Chat bot (v4 MS bot framework) and applied in Direct line channel, and also I'm sending

建议的操作在某些地方,在这种情况下,我想禁用/隐藏发送框-输入文本框

suggestedActions on certain places, on such time i want to disable/hide the sendbox - the input text box

以下是我在前端的完整代码.

(async function bot() {



 const activityMiddleware = () => next => card => {
      const { activity: { suggestedActions } } = card;
      const toggleSendBoxEvent = new Event('ToggleSendBoxEvent')
      if (suggestedActions) {
        toggleSendBoxEvent.data = "none";
        window.dispatchEvent(toggleSendBoxEvent);
      } else {
        toggleSendBoxEvent.data = "flex";
        window.dispatchEvent(toggleSendBoxEvent);
      }

      return next(card);

    };

    const styleOptions = 
    {
        hideUploadButton: true,
        bubbleBackground: '#D8F4FF',
        bubbleFromUserBackground: '#E8E8E8',
        botAvatarImage: 'img',
        botAvatarInitials: 'bot',
        userAvatarInitials: initial,
        userAvatarImage: userimg,
        rootHeight: '100%',
        rootWidth: '50%'

    };

    const styleSet = window.WebChat.createStyleSet({
        bubbleBackground: 'rgba(0, 0, 255, .1)',
        bubbleFromUserBackground: 'rgba(0, 255, 0, .1)'
    });


    styleSet.textContent = {
        fontFamily: "'Comic Sans MS', 'Arial', sans-serif",
        fontWeight: 'bold'
    };
    const secret = 'token';
    const res = await fetch('../generate',
        {
            headers: {
                Authorization: `Bearer ${secret}`,
            },
            method: 'POST'
        });
    const { token } = await res.json();

    const store = window.WebChat.createStore(
        {},
        ({ dispatch }) => next => action => {
            if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
                dispatch({
                    type: 'WEB_CHAT/SEND_EVENT',
                    payload: {
                        name: 'webchat/join',
                        value:{
                            parms
                        },

                    }
                });
            }
            return next(action);
        }
    );

    window.WebChat.renderWebChat({
        directLine: window.WebChat.createDirectLine({ token }),
        activityMiddleware: activityMiddleware,
        store,
        styleOptions,
        userID: emailid,
        username: fullname,
        locale: 'en-US',
        userAvatarInitials: initial
    }, document.getElementById('webchat'));


    document.querySelector('#webchat > *').focus();
    document.querySelectorAll('[aria-label="Sendbox"]')[0].placeholder = "Type your question and press enter";

    window.addEventListener('ToggleSendBoxEvent', ( { data } ) => {
      const sendBoxes = document.getElementsByClassName("main");
      let send_Box;
      for (let sendBox of sendBoxes) {
        send_Box = sendBox;
      }
      send_Box.setAttribute('style', `display:${ data }`)
    });

    $('.css-115fwte').on('click',removequestion);

    const sendbox = document.querySelector("[aria-label='Sendbox']");


function removeQuestions() {
    const questionDivs = document.querySelectorAll('#ques');
    questionDivs.forEach((div) => {div.remove();})

    }    

  sendbox.addEventListener('keyup', (eventObject) => 
            {
                if (sendbox.defaultValue.length > 3)
                 {
                    getquestion(sendbox.value+eventObject.key,product,releaseval);
                 } 
                 else 
                 {
                    removeQuestions();
                 }
            });



function send(question) 
 {
    store.dispatch({
    type: 'WEB_CHAT/SEND_MESSAGE',
    payload: { text: question }

     });
                event.currentTarget.remove();
                removeQuestions();
                document.querySelector("[aria-label='Sendbox']").value =""; 
   }

function getquestion(value,prod,release) {
    var token = 'token';
    var questionquery =
    {
        question: value,
        top: 2,
        scoreThreshold: 50,
        "strictFilters": [
            {
                "name": prod,
                "value":release
            }],
    }
    $.ajax({
        type: "POST",
         url: ".../generateAnswer",


        data: JSON.stringify(questionquery),
        beforeSend: function (xhr) {
              xhr.setRequestHeader('Authorization','id');

        },
        dataType: "json",
        contentType: "application/json",
        success: function (data) {

            console.log(data);
            console.log(data.answers[0].answer);

            var countofques = data.answers[0].questions.length;
            var questions = "";
            $('#ques').remove();

            for (var i = 0; i < data.answers.length; i++) 
            {
                for(var j=0;j<3;j++)
                    {
                        if (data.answers[i].questions[j] != null && data.answers[i].questions[j] != 'undefined')
                        questions = questions + "<div class='probing'>" + data.answers[i].questions[j] + "</div>";
                    }   
            }

            $('.content').last().append("<div id='ques'>" + questions + "</div>");

            $('div.probing').click(function () {
            send(this.innerText);

            });

        },
        error: function (data) {
            alert(data.responseText);
        }
    });
}


function removequestion()
{
    $('#ques').remove();


}

  })().catch(err => console.error(err));

 }

在后端使用c#代码,我正在发送建议的操作.下面是相同的代码.

in the back end using c# code, I'm sending the suggested actions.below is the code for the same.

私有静态异步任务messageSuggestedActionsAsync(ITurnContext turnContext,CancellationToken cancelToken) { mPrevUserMssg = turnContext.Activity.Text;

private static async Task messageSuggestedActionsAsync(ITurnContext turnContext, CancellationToken cancellationToken) { mPrevUserMssg = turnContext.Activity.Text;

    if (mPrevUserMssg == turnContext.Activity.Text)
    {
        var reply = turnContext.Activity.CreateReply("Did you find this helpful?");
        reply.SuggestedActions = new SuggestedActions()
        {
            Actions = new List<CardAction>()
        {

            new CardAction() { Title = "Yes", Type = ActionTypes.ImBack, Value = "Yes" },
            new CardAction() { Title = "No", Type = ActionTypes.ImBack, Value = "No" },


        },
        };

        await turnContext.SendActivityAsync(reply, cancellationToken);
    }
    else { }
}

请帮助我进行代码中的任何修改以满足我的要求.

Please help with any modification required in my code to achieve my requirements.

推荐答案

在意识到没有针对此问题的解决方案之后,他们仍在努力在MS bot框架中实现此功能,

After realizing that there is no solutions for this issue and still they are working to implement this feature in MS bot framework,

我使用以下简单的JavaScript方法来满足我的要求

I used the following simple JavaScript method to achieve my requirement

function hidesendbox()
{
    var suggestion = $('div.css-6p8cnn').length;

    if(suggestion > 0)
    {
        $(".main").hide();
    }else
    {
        $(".main").show();
    }
 }

尽管很简单,但实际上对我有用.

though its simple, it actually worked for me.

这篇关于机器人回复建议的操作时如何隐藏/显示发件箱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆