K48 K48 - 1 year ago 302
C# Question

How to schedule tasks in Microsoft Bot Framework + C#?

I am building a test bot using Microsoft's Bot Framework / Bot Builder for C#.NET / LUIS. It is deployed on Azure. The idea for my test project is to send a reminder to the user.

For example, when the user asks "remind me in two hours to buy milk", it should initiate a conversation or send a reply to the existing conversation in two hours.

I have no problem parsing natural language into date and task using LUIS, however I have no idea how to schedule a task so that the framework would somehow send a reply to the user later on.

I've read the docs and checked the examples at https://docs.botframework.com/en-us/csharp/builder/sdkreference/, and also searched on StackOverflow, but it seems that the framework doesn't support it. I've also looked at Azure Scheduler, but it seems insanely expensive, even if my bot would only have 100 users with one scheduled task each.

What is another way to schedule tasks so that the bot sends a message to the user at an appointed time?

Answer Source

So if I understand correctly, your question involves two parts:

1. How to start a conversation

In v3.0, MS introduced a new way to start a new conversation (group or 1-on-1). Reference: https://docs.botframework.com/en-us/csharp/builder/sdkreference/routing.html#conversation

Sample code:

var connector = new ConnectorClient(incomingMessage.ServiceUrl);
var ConversationId = await connector.Conversations.CreateDirectConversationAsync(incomingMessage.Recipient, incomingMessage.From);
IMessageActivity message =  Activity.CreateMessageActivity();
message.From = botChannelAccount;
message.Recipient = new ChannelAccount() { name: "Larry", "id":"@UV357341"};
message.Conversation = new ConversationAccount(id: ConversationId.Id);
message.Text = "Hello";
message.Locale = "en-Us";
var reply = await connector.Conversations.ReplyToActivityAsync(message);

2. How to schedule a job

There are multiple ways of doing it, you can use an external queue service, Azure web jobs, web roles, or try to register in the ASP.NET itself.

Hangfire (http://hangfire.io/) is what I'm using for my bot.

Code sample:

() => TriggerConversation(), // <= the start conversation code here
TimeSpan.FromDays(1)); // <= when the job should be ran
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download