How to send a message to user if the bot is idle for 5 mins in botframework v4

我们两清 提交于 2021-02-10 05:15:27

问题


I want to send a prompt (I am waiting) if I don't receive any message from the user after say 5 mins in directline webchat channel.

It is Demo bot, so I am using local memory storage.

Any help would be appreciated.


回答1:


There are a couple of ways you can handle this. If you are calling this via script (using something like the botframework-webchat option using Directline channel), you can check out this answer on SO which shows you how to set it up in your HTML file.

If you want to implement this directly in your bot, you can use a time function like Sainath Reddy mentioned. However, I noticed that the context object becomes invalid, so you have to use Proactive Messaging instead. I'm not sure if this is the most efficient method, but here is how I was able to accomplish this.

First, you must import TurnContext and BotFrameworkAdapter from botbuilder

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

Then, add the following code in the onMessage function (or onTurn if you are using an earlier setup). setTimeout will run only once. You can instead use setInterval if you want it to repeat.

            // Save the conversationReference
            var conversationReference = TurnContext.getConversationReference(context.activity);

            // Reset the inactivity timer
            clearTimeout(this.inactivityTimer);
            this.inactivityTimer = setTimeout(async function(conversationReference) {
                console.log('User is inactive');
                try {
                    const adapter = new BotFrameworkAdapter({
                        appId: process.env.microsoftAppID,
                        appPassword: process.env.microsoftAppPassword
                    });
                    await adapter.continueConversation(conversationReference, async turnContext => {
                        await turnContext.sendActivity('Are you still there?');
                    });
                } catch (error) {
                    console.log(error);
                }
            }, 300000, conversationReference);

I prefer this method because it also works if you are using botframework-webchat or similar. In fact, it will work in every channel. If there are certain channels where you don't want this to happen, you'd have to add some additional logic to the function. Or, if you want it only in something like botframework-webchat, you can just use the first method I linked.



来源:https://stackoverflow.com/questions/61315710/how-to-send-a-message-to-user-if-the-bot-is-idle-for-5-mins-in-botframework-v4

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