Search code examples
c#botframework

Routing using Activity.text in Microsoft Bot Framework


I know there are other ways of chaining Dialogs in Microsoft Bot Framework but I am trying to understand why I cannot route to Dialogs using the Activity text.

Can someone shed so light on it, please? I am possibly overlooking something stupid because I am running on caffeine at the moment

public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
    if (activity.Type == ActivityTypes.Message)
    {
        if (activity.Text == "Hello")
        {
            await Conversation.SendAsync(activity, () => new Dialogs.HelloDialog());
        }
        else
        {
            await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
        }
    }
    else
    {
        HandleSystemMessage(activity);
    }
    var response = Request.CreateResponse(HttpStatusCode.OK);
    return response;
}

Solution

  • I've marked this as a duplicate of Bot Framework Dialog Leakage Issue because it relates to the same basic misunderstanding. Conversation.SendAsync doesn't forward a message to the dialog you've specified, it just sends the message to the conversation which automatically uses whatever dialog is on top of the stack. Here's the relevant piece of my answer to the other question:

    I think you may be misunderstanding the purpose of Conversation.SendAsync(). The MakeRoot delegate isn't a function to navigate to whatever dialog you want. It's only called at the start of the conversation and it's used to create the conversation's root dialog. If a conversation is already underway, Conversation.SendAsync() sends the activity to whatever dialog is on top of the stack and the MakeRoot delegate is ignored. You can read more about dialogs and conversation flow here: https://learn.microsoft.com/en-us/azure/bot-service/bot-service-design-conversation-flow?view=azure-bot-service-3.0

    If you want to start a dialog in the middle of a conversation you should do it from within another dialog and not from your messages controller. A typical way of doing this is to use context.Forward(): https://learn.microsoft.com/en-us/azure/bot-service/dotnet/bot-builder-dotnet-manage-conversation-flow?view=azure-bot-service-3.0#invoke-the-new-order-dialog