Reactjs 如何通过单击Botframework Webchat中的建议发送消息?

Reactjs 如何通过单击Botframework Webchat中的建议发送消息?,reactjs,botframework,chatbot,web-chat,Reactjs,Botframework,Chatbot,Web Chat,我希望我的机器人在单击所需建议时发送消息。i、 e.我希望发送消息-当我单击建议或使用箭头键选择建议,然后按enter键时。但是现在,如果我单击或使用箭头键选择建议,建议值将显示在文本框中,然后我必须按enter键发送消息。我只是想改变这一点。 任何帮助都将不胜感激 我的代码如下: import React from 'react'; import { DirectLine, ConnectionStatus } from 'botframework-directlinejs'; import

我希望我的机器人在单击所需建议时发送消息。i、 e.我希望发送消息-当我单击建议或使用箭头键选择建议,然后按enter键时。但是现在,如果我单击或使用箭头键选择建议,建议值将显示在文本框中,然后我必须按enter键发送消息。我只是想改变这一点。 任何帮助都将不胜感激

我的代码如下:

import React from 'react';
import { DirectLine, ConnectionStatus } from 'botframework-directlinejs';
import ReactWebChat from 'botframework-webchat';
import './ChatComponent.css';

var val;
var apiParameters = [];
var currentFocus = -1;
export default class extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            token: '',
            conversationId: '',
            directLine: {},
            view: false,
            feedBack: null,
            value: '',
            popupContent: '',
            storeValue: '',
            suggestions: [],
            suggestionCallback: '',
            suggestionTypedText: "",
            typingChecking: "false",

        };
        this.handleTokenGeneration = this.handleTokenGeneration.bind(this);
        this.handleChange = this.handleChange.bind(this);
        this.handleSaveFeedback = this.handleSaveFeedback.bind(this);
        this.handleSuggestion = this.handleSuggestion.bind(this);
        this.handleClose = this.handleClose.bind(this);
        this.handleSuggestionClick = this.handleSuggestionClick.bind(this);
        this.handleKeyDown = this.handleKeyDown.bind(this);

        this.moveHighlight = this.moveHighlight.bind(this);

        this.getSuggestionHtml = this.getSuggestionHtml.bind(this);
    }


    getSuggestionHtml(suggestion) {
        const lowerCaseSuggestion = suggestion.toLowerCase();
        return {
            __html: lowerCaseSuggestion.includes(this.state.suggestionTypedText) ? lowerCaseSuggestion
                .replace(this.state.suggestionTypedText, `<b>${this.state.suggestionTypedText}</b>`) : lowerCaseSuggestion
        };
    }
    handleTokenGeneration = async () => {
        console.log("11111");
        const response = await fetch(`api/TokenGenerationService/GetToken`);
        const data = await response.json();
        this.setState({ token: data.categoryObject.token, conversationId: data.categoryObject.conversationId });
        this.state.directLine = new DirectLine({ token: this.state.token });
        this.setState({ view: true });
        this.setState({ typingChecking: "true" });

        console.log("conversationId");
    };
    async handleSuggestion(val, store) {
        if (val === "") {
            this.setState({
                suggestions: []
            });
        }
        else {
            apiParameters = [];
            var valuess = null;
            const response = await fetch(`api/TokenGenerationService/GetAzureSearch?myparam1=${val}`);
            const data = await response.json();
            var values = ["Hello", "yes", "no", "exit", "Welcome", "Thank You", "Approve", "Apply leave", "Reject", "Absence Balance", "Leave Balance", "Upcoming Holidays", "Apply Comp-Off", "Approve Leave", "Raise Incident Tickets", "Project Allocation Info", "Reporting Manager Change", "Reporting Manager Approval", "Approve Isolve Tickets", "My Manager", "My Account Manager", "Generate Salary Certificate", "Isolve Ticket Status", "Internal Job Posting", "My Designation", "My Joining Date", "RM Approval", "RM Change", "Resource Allocation", "ESettlement Approval", "SO Approval", "Cash advance Approval", "Purchase Request Approval", "Referral status", "HR Ticket", "Platinum Support"];
            valuess = values.filter(s =>
                s.toLocaleLowerCase().startsWith(val.toLowerCase())
            );
            valuess = valuess.concat(data.az_search);
            this.setState({
                suggestions: valuess,
                suggestionCallback: store,
                suggestionTypedText: val.toLowerCase()
            });

            var totCount = data.az_search;
            console.log("kkkkkk" + totCount);

            var myNode = document.getElementById('Suggestion1');
        }
    }
    getSuggestionCss(index) {
        var HIGHLIGHTED_CSS = "HIGHLIGHTED_CSS";
        var SUGGESTION_CSS = "SUGGESTION_CSS";
        console.log("jioouu" + this.state.highlightedIndex);
        return index === this.state.highlightedIndex ? HIGHLIGHTED_CSS : SUGGESTION_CSS;
    }

    moveHighlight(event, direction) {
        event.preventDefault();

        const { suggestions, highlightedIndex=-1 } = this.state;
        if (!suggestions.length) return;
        let newIndex = (highlightedIndex + direction + suggestions.length) % suggestions.length;
        console.log("lokkkk" + direction)
        if (newIndex !== highlightedIndex) {
            console.log("kkkkkkkkkkkkkkkkkkk")
            this.setState({
                highlightedIndex: newIndex,
            });
        }
    }
    keyDownHandlers = {

        ArrowDown(event) {

            this.moveHighlight(event, 1);
        },
        ArrowUp(event) {

            this.moveHighlight(event, -1);
        },
        Enter(event) {
            const { suggestions } = this.state;
            if (!suggestions.length) {
                // menu is closed so there is no selection to accept -> do nothing
                return
            }
            event.preventDefault()
            this.applySuggestion(suggestions[this.state.highlightedIndex]);
        },
    }

    handleKeyDown(event) 
        if (this.keyDownHandlers[event.key])
            this.keyDownHandlers[event.key].call(this, event)
    }

    async handleSuggestionClick(event) {
        await this.applySuggestion(event.currentTarget.textContent);
    }

    async applySuggestion(newValue) {
        await this.setState({ typingChecking: "false", suggestions: [], highlightedIndex: 0 });
        this.state.suggestionCallback.dispatch({
            type: 'WEB_CHAT/SET_SEND_BOX',
            payload: {
                text: newValue,
            }
        });
        await this.setState({ typingChecking: "true" });
    }

    handleClose(elmnt) {
        var x = document.getElementsByClassName("autocomplete-items");
        for (var i = 0; i < x.length; i++) {
            if (elmnt !== x[i]) {
                x[i].parentNode.removeChild(x[i]);
            }
        }

    }

    async componentDidMount() {

        try {
            await this.handleTokenGeneration();

            const store =
                window.WebChat.createStore(
                    {},
                    ({ getState }) => next => action => {
                        this.state.directLine.connectionStatus$
                            .subscribe(connectionStatus => {

                                //console.log("connect" + connectionStatus);
                                //console.log("LOP" + ConnectionStatus.ExpiredToken);
                                if (connectionStatus === ConnectionStatus.ExpiredToken) {
                                    console.log("expired");
                                }

                                if (action.type === 'WEB_CHAT/SET_SEND_BOX') {
                                    const val = action.payload.text;
                                    if (this.state.typingChecking === "true") {
                                        this.setState({
                                            highlightedIndex: -1,
                                        });
                                        console.log(this.state.typingChecking);
                                        this.handleSuggestion(val, store);
                                    }
                                }

                                if (action.type === 'DIRECT_LINE/DISCONNECT_FULFILLED') {
                                    console.log("final" + connectionStatus);
                                    console.log("finalexpired" + ConnectionStatus.ExpiredToken);
                                    console.log("final");
                                    this.handleTokenGeneration();
                                    // fetch('api/TokenGenerationService/GetToken').then(conversation => this.state.directLine.reconnect(conversation))
                                }
                            });

                        return next(action)
                    }
                );

            this.setState({ storeValue: store });
        } catch (error) {
            console.log("error in fetching token");
            console.log(error);
        }
        this.state.directLine.activity$
            .filter(activity => activity.type === 'message')
            .subscribe(function (activity)
            {
                //console.log("oooooooooooooooooooooo");
            }
               // message => console.log("received message ", message.text)
            );
    }

    handleSaveFeedback(ans) {

        var userID = "U92656";
        var feedbackmsg = this.state.value;
        var feedbacktype = this.state.feedBack;
        var convId = this.state.conversationId;
        fetch('api/Feedback/SaveFeedback',
            {
                method: "POST",
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ Uid: userID, FeedbackMessage: feedbackmsg, Convid: convId, FeedbackType: feedbacktype })
            }).
            then(response => response.text())
            .then(data => {

                console.log(data.getResult);
            });

        this.setState({ value: '' });
    }
    feedback(ans) {
        this.setState({ feedBack: ans });

        if (ans === "Send") {
            this.handleSaveFeedback(ans);
        }
        else if (ans === "Yes") {
            this.setState({ popupContent: "How was your experience?" });
            // console.log(this.state.value)
        }
        else if (ans === "No") {
            this.setState({ popupContent: "What went wrong?" });
            // console.log(this.state.value)
        }
    }

    handleChange = (event) => {
        this.setState({ value: event.target.value });
    }

    render() {

        if (!this.state.view) {
            return <div />
        } else {
            const filteredSuggestions = this.state.suggestions.filter(
                suggestion =>
                    suggestion.toLowerCase().indexOf(this.state.suggestionTypedText.toLowerCase()) > -1
            );

            return (
                <div className="react-container webchat" >
                    <div  onKeyDown={this.handleKeyDown.bind(this)}>
                        <div >

                    <ReactWebChat  directLine={this.state.directLine} webSocket={true} userID='U92656' username='Thomas' store={this.state.storeValue} sendTypingIndicator={true} />
                        </div>
                    </div>

                    <div className="SuggestionParent" id="Suggestion1">

                        {this.state.suggestions.map((suggestion, index)=> (
                            <div className={this.getSuggestionCss(index)} key={index}  onClick={this.handleSuggestionClick} >
                                {suggestion
                                    .toLowerCase()
                                    .startsWith(this.state.suggestionTypedText) ? (
                                        <div>

                                            <b>{this.state.suggestionTypedText}</b>
                                            {suggestion
                                                .toLowerCase()
                                                .replace(this.state.suggestionTypedText, "")}
                                        </div>
                                    ) : (
                                        <div dangerouslySetInnerHTML={this.getSuggestionHtml(suggestion)} />
                                    )}
                            </div>
                        ))}
                    </div>
                    <footer className="chat-footer" >
                        <div className="foot-footer">
                            Was I helpful ?
                            <span className="feedback" onClick={() => this.feedback("Yes")} >Yes</span><span>|</span><span className="feedback" onClick={() => this.feedback("No")}>No</span>
                            {
                                this.state.feedBack === "Yes" || this.state.feedBack === "No" ?
                                    (
                                        <div className="dialog" id="myform">
                                            <div id="textfeedback">
                                                <span id="closeFeedback" onClick={() => this.feedback("Close")}>X</span>
                                                <p>{this.state.popupContent}</p>
                                                <input type="text" id="feedbacktxtbox" required name="textfeedback" placeholder="Pleasure to hear from u!"
                                                    onChange={this.handleChange}
                                                    value={this.state.value} />
                                                <button type="button" id="btnfeedback" onClick={() => this.feedback("Send")}>send</button>
                                            </div>
                                        </div>
                                    ) : null
                            }
                        </div>
                    </footer>
                </div>
            );
        }
    }
}
从“React”导入React;
从'botframework directlinejs'导入{DirectLine,ConnectionStatus};
从“botframework webchat”导入ReactWebChat;
导入“./ChatComponent.css”;
var-val;
var-apiParameters=[];
var currentFocus=-1;
导出默认类扩展React.Component{
建造师(道具){
超级(道具);
此.state={
令牌:“”,
会话ID:“”,
直接行:{},
观点:错,
反馈:空,
值:“”,
弹出内容:“”,
storeValue:“”,
建议:[],
suggestionCallback:“”,
suggestionTypedText:“”,
输入检查:“假”,
};
this.handleTokenGeneration=this.handleTokenGeneration.bind(this);
this.handleChange=this.handleChange.bind(this);
this.handleSaveFeedback=this.handleSaveFeedback.bind(this);
this.handleSuggestion=this.handleSuggestion.bind(this);
this.handleClose=this.handleClose.bind(this);
this.handleSuggestionClick=this.handleSuggestionClick.bind(this);
this.handleKeyDown=this.handleKeyDown.bind(this);
this.moveHighlight=this.moveHighlight.bind(this);
this.getSuggestionHtml=this.getSuggestionHtml.bind(this);
}
getSuggestionHtml(建议){
const lowercasessuggestion=suggestion.toLowerCase();
返回{
__html:LowercasesSuggestion.includes(this.state.suggestionTypedText)?LowercasesSuggestion
.replace(this.state.suggestionTypedText,`${this.state.suggestionTypedText}`):小写建议
};
}
handleTokenGeneration=async()=>{
控制台日志(“11111”);
const response=wait fetch(`api/TokenGenerationService/GetToken`);
const data=wait response.json();
this.setState({token:data.categoryObject.token,conversationId:data.categoryObject.conversationId});
this.state.directLine=新的directLine({token:this.state.token});
this.setState({view:true});
this.setState({typingChecking:“true”});
console.log(“会话ID”);
};
异步handleSuggestion(val,存储){
如果(val==“”){
这是我的国家({
建议:[]
});
}
否则{
apiParameters=[];
var值=null;
const response=wait fetch(`api/TokenGenerationService/GetAzureSearch?myparam1=${val}`);
const data=wait response.json();
var值=[“您好”、“是”、“否”、“退出”、“欢迎”、“谢谢”、“批准”、“申请休假”、“拒绝”、“缺勤余额”、“休假余额”、“即将到来的假期”、“申请补假”、“批准休假”、“提出事件通知单”、“项目分配信息”、“报告经理变更”、“报告经理批准”、“批准独立通知单”、“我的经理”,“我的客户经理”、“生成工资证书”、“独立票证状态”、“内部职位公告”、“我的指定”、“我的加入日期”、“RM批准”、“RM更改”、“资源分配”、“E安装批准”、“SO批准”、“现金预付批准”、“采购申请批准”、“转介状态”、“HR票证”、“白金支持”];
valuess=values.filter(s=>
s、 toLocaleLowerCase().StartWith(val.toLowerCase())
);
valuess=valuess.concat(data.az_search);
这是我的国家({
建议:价值观,
suggestionCallback:store,
suggestionTypedText:val.toLowerCase()
});
var totCount=data.az_搜索;
console.log(“kkk”+totCount);
var myNode=document.getElementById('Suggestion1');
}
}
getSuggestionCss(索引){
var HIGHLIGHTED_CSS=“HIGHLIGHTED_CSS”;
var SUGGESTION\u CSS=“SUGGESTION\u CSS”;
log(“jioouu”+this.state.highlightedIndex);
返回索引===this.state.highlightedIndex?突出显示的\u CSS:SUGGESTION\u CSS;
}
移动突出显示(事件、方向){
event.preventDefault();
const{suggestions,highlightedIndex=-1}=this.state;
如果(!suggestions.length)返回;
让newIndex=(highlightedIndex+方向+建议.length)%suggestions.length;
console.log(“lokkk”+方向)
if(newIndex!==highlightedIndex){
console.log(“kkkkkkkkk”)
这是我的国家({
highlightedIndex:newIndex,
});
}
}
keyDownHandlers={
向下箭头(事件){
此项。移动突出显示(事件,1);
},
向上箭头(事件){
此.moveHighlight(事件-1);
},
输入(事件){
const{suggestions}=this.state;
如果(!suggestions.length){
//菜单已关闭,因此没有可接受的选择->不执行任何操作
返回
}
event.preventDefault()
this.applySuggestion(建议[this.state.highlightedIndex]);
},
}
handleKeyDown(事件)
if(this.keyDownHandlers[event.key])
this.keyDownHandlers[event.key].call(this,event)
}
异步句柄建议单击(事件){
等待这个.applySuggestion(event.currentTarget.textContent);
}
异步应用程序建议(newValue){
哦