websocket 在Microsoft Bot Builder中建立Web Socket连接时,为多个用户创建和处理多个会话

mspsb9vt  于 2022-11-11  发布在  其他
关注(0)|答案(1)|浏览(128)

我是Microsoft Bot Framework的新手。我已经使用Microsoft Bot Framework创建了一个bot。如何为单个用户创建会话。目前我面临的问题是,每当多个用户创建连接时,变量中的值会被覆盖,从而为用户提供错误的值。
下面是代码

if (turnContext.activity.text === 'CCP') {
const url = await this.connectToAgent(members);
const initialMessage = {
    topic: "aws/subscribe",
    content: {
        topics: ["aws/chat"]
    }
};
ws = new WebSocket(url[1]);
ws.addEventListener("open", () => {
    ws.send(JSON.stringify(initialMessage));
});
await turnContext.sendActivity("Please wait while we connect you to an agent.");
conversationReferences[currentUser] = TurnContext.getConversationReference(turnContext.activity);
adapter = turnContext.adapter;
ws.addEventListener('message', async function (event) {
    const msg = JSON.parse(event.data);

});
let sendChatHistory = (function() {
    let executed = false;
    return function() {
        if (!executed) {
            executed = true;
            const param = {
                ConnectionToken: connectionToken, /* required */
                Content: sendHistory, /* required */
                ContentType: 'text/plain', /* required */
            };
            connectparticipant.sendMessage(param,async function (err, data) {
                chatHistory = '';
                sendHistory = '';
                if (err) {
                    errorMsg = "Error while sending a message";
                }
            });
        }
    };
})();
sendChatHistory();   
}
mqxuamgl

mqxuamgl1#

根据官方的documentation,我们有StateClient的程序,我们可以为每个用户给予单独的活动保持器。当我们创建多个连接的多个用户时,这是有效的。

StateClient sc = activity.GetStateClient();
        userData.SetProperty<string>("MyDetails", < some value >);
        // How to save the BotUserData 
        await sc.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
        // Getting User data from bot 
        BotData userData = await sc.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

由于这是一个并行操作,因此需要使用方法Async来同时获取用户的数据。

相关问题