Search code examples
c#.net-corebotframework

How to manage and store TurnState without using TurnContext object


In following piece of code, TurnContext object is required to fetch the underlying Bot State from Cosmos and save it back -

//Get the TurnContext from the Dictionary
TurnContextReferences.TryGetValue(sessionStateChangedEventData.SessionId, out ITurnContext turnContext);
if (turnContext != null)
{
    var conversationData = await BotStateAccessors
                      .ConversationStateAccessor
                      .GetAsync(turnContext, () => new ConversationStateDataModel());
    if (!conversationData.LiveAgentChatClosed)
    {
        conversationData.LiveAgentChatClosed = true;
        await BotStateAccessors.ConversationStateAccessor.SetAsync(turnContext, conversationData);
        await BotConversationState.SaveChangesAsync(turnContext);
    }
}

Is there any possible way to achieve same without using TurnContext directly?


Solution

  • All the information you need to access bot state and send messages to a user is in a conversation reference. You can build a turn context out of a saved conversation reference using the ContinueConversationAsync method. You can see how to do this in the proactive messages sample:

    await ((BotAdapter)_adapter).ContinueConversationAsync(_appId, conversationReference, BotCallback, default(CancellationToken));
    

    A turn context is not meant to exist outside of its associated turn. You should be saving conversation references instead of turn contexts.