How to: Save conversation data in an Microsoft Chatbot
Tags: tutorial, chatbot, beginners, csharp
Published: 2021-12-08 23:13:30

If you liked what you read feel free to connect with me on [linkedin](https://www.linkedin.com/in/albert-bennett/) or follow me on dev.to :)
<br/>

Hi and welcome to my blog post.
Today I'd like to show you how to get started with saving conversation data with chatbots using the Microsoft bot framework.
Feel free to check out the repo for a working sample: 
https://github.com/Albert-Bennett/state-management-chatbot
<br/>

**Getting Started**
To get us started you need to create an object to hold the data that you need to persist throughout the conversation. In the repo above I've used this one:
```csharp
    public class ConversationData
    {
        public ConverstationStates CurrentState { get; set; } = ConverstationStates.Welcome;
        public string Name { get; set; }
        public string Age { get; set; }
    }
```
The enum in my class (ConverstationStates) is just used to keep track of what response to return to the user after certain stages of the conversation. For the sample bot all that is kept track of is the users name, age and the current conversation state, although you can use this technique to store more complex data types.
<br/>

**Modifying the Startup.cs class**
Next you'll need to modify your startup.cs class to be make the ConversationState object injectable into the chatbot. We need to be able to do this to use it later on when we want to save the data.
```csharp
        private static void CreateConversationalState(IServiceCollection services)
        {
            var storage = new MemoryStorage();

            var conversationState = new ConversationState(storage);
            services.AddSingleton(conversationState);
        }
``` 
This method needs to get called at the end of your ConfigureServices method. The main take away from this is the creation of the MemoryStorage object, this is just a reference to local storage to store the conversation data in. Also note the creation of the ConversationState object, this object is kind of like a wrapper that allows us to access read and write for our conversation data. Thus letting us persist the data for the duration of the users session.
<br/>

**Getting our Data**
This is two lines of code for us.
```csharp
var conversationStateAccessors = _conversationState.CreateProperty<ConversationData>(nameof(ConversationData));
var conversationData = await conversationStateAccessors.GetAsync(turnContext, () => new ConversationData());
```
It is worth noting that I am injecting in the ConversationState (_conversationState) object into the bot class and utilizing it here to either create a new ConversationData object or get the current one that the user is using. 
<br/>

**Saving the Data**
The last task that we need to do to persist the users data is to save it. Below I have put this logic in the OnTurnTask method of the bot.
```csharp
        public override async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default)
        {
            await base.OnTurnAsync(turnContext, cancellationToken);

            await _conversationState.SaveChangesAsync(turnContext, false, cancellationToken);
        }
```
This method gets called when there is something happening in the bot such as sending out a response and is normally one of the last methods to finish execution before returning back to the user. I have placed the logic here to make sure that the conversation data is getting saved in one place.
<br/>

**Sample in Action**
If you'd to see the bot in action, I have linked the video of it working below.
[![conversation state management microsoft bot framework tutorial](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/03w7y64cdw700s5xgc8z.png)](https://www.youtube.com/watch?v=THg3qtONEGI)
 Also feel free to check out the repo if you want to try it yourself. The link is here: https://github.com/Albert-Bennett/state-management-chatbot
You'll also need to download the [bot framework emulator v4](https://github.com/Microsoft/BotFramework-Emulator/releases/tag/v4.14.1) to get the bot running locally.

That's about it for persisting conversation data in a chat bot. Of course there are ways of persisting the data for longer that the users session, maybe by using something like CosmosDB. But, I think that the snippets of code that I have shown, show off the basics of how the process works.
<br/>

Thanks for reading and I'll see you in the next one!
<br/>

If you like this post and are interested in learning a little more about the Microsoft bot framework feel free to look through my other blog posts:
- [How to: Connect a MS Bot Framework Chatbot to MS Teams](https://dev.to/albertbennett/how-to-connect-a-ms-bot-framework-chatbot-to-ms-teams-193d)
- [How to: Adaptive Cards and the Bot Framework](https://dev.to/albertbennett/how-to-adaptive-cards-and-the-ms-bot-framework-25km)
- [How to: Natural Language Processing and the Microsoft Bot Framework](https://dev.to/albertbennett/how-to-natural-language-processing-and-the-microsoft-bot-framework-1oob)