首页 > 解决方案 > 如何使用机器人框架中的每条消息创建和发送反向通道事件?

问题描述

我正在尝试从send钩子中的 botbuilder 中间件访问会话变量:

bot.use({
    botbuilder: function (session, next) {
        session.send(); // it doesn't work without this..
        session.sendTyping();
        console.log('session.userData', session.userData['UI_Changes']);
        var reply = createEvent("UI_Changes", session.userData['UI_Changes'], session.message.address);
        session.send(reply);
        // session.userData['UI_Changes'] = {};
        next();
    },
    send: function (event, next) {
        // console.log('session.userData', session.userData['UI_Changes']);
        // var reply = createEvent("UI_Changes", session.userData['UI_Changes'], session.message.address);
        // session.send(reply);
        // session.userData['UI_Changes'] = {};
        next();
    }
});

但由于session在 中不可用send,我该如何访问userData

createEvent只需创建一个backchannel事件:

//Creates a backchannel event
const createEvent = (eventName, value, address) => {
    var msg = new builder.Message().address(address);
    msg.data.type = "event";
    msg.data.name = eventName;
    msg.data.value = value;
    return msg;
}

我在stackoverflow上找到了这个答案:

send: function (message, next) {
    bot.loadSessionWithoutDispatching(message.address,function (error,session){
        console.log(session.userData);
    });

    next();
}

但是,当我尝试创建一个事件并发送它时,我无法访问该地址

bot.loadSessionWithoutDispatching(event.address, function (error,session){
            console.log('session not null?', session !== null ? "yes" : "no");
            if(session !== null){
                console.log('session.userData', session.userData['UI_Changes'], 'address:', session);
                var reply = createEvent("UI_Changes", session.userData['UI_Changes'], event.address); //undefined
                session.send(reply);
                session.userData['UI_Changes'] = {};
            }
        });

两者session.messageevent.addressundefined回调函数中。我怎么可能做一个解决方法?

event有以下内容:

event: { type: 'message',
  text: 'You reached the Greeting intent. You said \'hi\'.',
  locale: 'en-US',
  localTimestamp: '2018-06-21T14:37:12.684Z',
  from: { id: 'Steves@4MRN9VFFpAk', name: 'Steves' },
  recipient: { id: 'pruthvi', name: 'pruthvi' },
  inputHint: 'acceptingInput' }

而在loadSessionWithoutDispatching它的功能之外:

event outside { type: 'message',
  agent: 'botbuilder',
  source: 'directline',
  textLocale: 'en-US',
  address: 
   { id: 'A7nrBS4yINt2607QtKpxOP|0000048',
     channelId: 'directline',
     user: { id: 'pruthvi', name: 'pruthvi' },
     conversation: { id: 'A7nrBS4yINt2607QtKpxOP' },
     bot: { id: 'Steves@4MRN9VFFpAk', name: 'Steves' },
     serviceUrl: 'https://directline.botframework.com/' },
  text: 'You reached the Greeting intent. You said \'hi\'.' }

我用过bot.loadSession而不是loadSessionWithoutDispatching它工作正常。

标签: node.jshookbotframework

解决方案


我用过bot.loadSession而不是loadSessionWithoutDispatching它工作正常。


推荐阅读