Microsoft Azure Bot Framework SDK 4: Send proactive message to specific users from bot using Node js

拈花ヽ惹草 提交于 2019-12-13 02:58:18

问题


I am able to send message to specific users with older botbuilder SDK 3.13.1 by saving message.address field in database.

    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);

How can this be done with botbuilder SDK 4? I am aware of the Rest API but want to achieve this with the SDK itself because the SDK is the more preferred way of communication between the bot and user.

Thanks in advance.


回答1:


Proactive Messages in the BotFramework v4 SDK enable you to continue conversations with individual users or send them notifications.

First, you need to import TurnContext from the botbuilder library so you can get the conversation reference.

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

Then, in the onTurn method, you can call the getConversationReference method from TurnContext and save the resulting reference in a database.

/**
 * @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 
    ...
}

Finally, you can retrieve the reference from the database and call the continueConversation method from the adapter to send specific users a message or notification.

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

For more information about proactive messages, take a look at the documentation or this example on GitHub. Hope this is helpful.



来源:https://stackoverflow.com/questions/53424861/microsoft-azure-bot-framework-sdk-4-send-proactive-message-to-specific-users-fr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!