Simple Session Management in Microsoft's Bot Framework with Azure...

by Michael Szul on

No ads, no tracking, and no data collection. Enjoy this article? Buy us a ☕.

The Bot Framework used to give you session storage out-of-the-box for free, including once it had been deployed to Azure. With the recent changes to the Bot Framework and Azure that saw the launch of the Azure Bot Service, you have to manage your own storage. This is especially important for session storage, since you will utilize the session in order to store information about the user, helping bot interaction.

Luckily, storage management is easy, especially since Microsoft provides libraries for you to easily manage your bot storage in Azure. The first thing you will need to do is download the appropriate Node.JS module:

npm install botbuilder-azure --save
      

Then we will add the triple slash directive at the top of the file:

/// <reference path="../node_modules/botbuilder-azure/lib/botbuilder-azure.d.ts" />
      

…and of course, then we need to import:

import * as azure from "botbuilder-azure";
      

==As of the time of this writing, there is a noted bug in the type definition for the botbuilder-azure module that will cause TypeScript transpilation to fail. If you have this issue, instead of import you will need to do a standard JavaScript require(), which will mean no language service support.==

The other thing you are going to want to do is set up some environment variables. This will rely on the dotenv-extended module:

npm install dotenv-extended --save
      

…and then require it:

require("dotenv-extended").load();
      

==As of the time of this writing, the dotenv module does not have a TypeScript definition file.==

Underneath your require() statement, you can then create a couple of constants:

const TABLENAME = process.env.TABLENAME;
      const STORAGENAME = process.env.STORAGENAME;
      const STORAGEKEY = process.env.STORAGEKEY;
      

The TABLENAME is the table storage you create in your Azure Storage instance to house this data. The STORAGENAME is the name of your storage instance. Lastly, the STORAGEKEY is one of the keys provided in the properties tab of your storage instance.

To instantiate this storage for your bot, right before you create your UniversalBot object, add the following lines of code:

var tableClient = new azure.AzureTableClient(TABLENAME, STORAGENAME, STORAGEKEY);
      var tableStorage = new azure.AzureBotStorage({ gzipData: false }, tableClient);
      

After that, it is just a matter of setting the storage on the bot:

var bot = new builder.UniversalBot(conn).set("storage", tableStorage);
      

The added bonus of setting up your own storage is that if you are hosting your bot on Azure through their Bot Service, and you are using their Azure Storage solution, you can make sure that your storage is in the same region as your bot, which will make performance faster.