首页 > 解决方案 > Microsoft Azure Bot Framework SDK 4:使用 Node js 从 bot 向特定用户发送主动消息

问题描述

通过在数据库中保存 message.address 字段,我可以使用较旧的 bo​​tbuilder SDK 3.13.1 向特定用户发送消息。

    var connector = new builder.ChatConnector({
        appId: process.env.MicrosoftAppId,
        appPassword: process.env.MicrosoftAppPassword,
        openIdMetadata: process.env.BotOpenIdMetadata
    });
    var bot = new builder.UniversalBot(connector);
    var builder = require('botbuilder');
    var msg = new builder.Message().address(msgAddress);
    msg.text('Hello, this is a notification');
    bot.send(msg);

botbuilder SDK 4 如何做到这一点?我知道 Rest API,但希望通过 SDK 本身来实现这一点,因为 SDK 是机器人和用户之间更优选的通信方式。

提前致谢。

标签: node.jsbotframework

解决方案


BotFramework v4 SDK 中的主动消息使您能够继续与个人用户对话或向他们发送通知。

首先,您需要TurnContextbotbuilder库中导入,以便获取对话参考。

const { TurnContext } = require('botbuilder');

然后,在该onTurn方法中,您可以调用该getConversationReference方法TurnContext并将结果引用保存在数据库中。

/**
 * @param {TurnContext} turnContext A TurnContext object representing an incoming message to be handled by the bot.
 */
async onTurn(turnContext) {
    ...
    const reference = TurnContext.getConversationReference(turnContext.activity);
    //TODO: Save reference to your database 
    ...
}

最后,您可以从数据库中检索引用并continueConversation从适配器调用该方法以向特定用户发送消息或通知。

await this.adapter.continueConversation(reference, async (proactiveTurnContext) => {
    await proactiveTurnContext.sendActivity('Hello, this is a notification')
});

有关主动消息的更多信息,请查看GitHub 上的文档或此示例。希望这会有所帮助。


推荐阅读