Persisting Chat History of Bot Framework Bots Across a User Session Using JavaScript

Joe Herres
AtBot

--

Recently we had a customer who was asking if a user’s chat history can follow them as they navigated around their site and the bot would follow them. I found a lot of information about the topic on the WebChat V4 GitHub project but no definite way of doing it. Turns out is actually really easy to do and just takes a few lines of JavaScript in our WebChat embed code.

In this example, I am use JS-Cookie for storing the session data, but you can use whatever fits the technology of your site. The following code is slight modifications to the embed code you download for you bots from https://admin.atbot.io.

We start by changing the declaration of the bot connection to conditionally include a conversationId and watermark based on the existence of a cookie value.

Once we have this in place, we need to add the setting of that cookie. The Conversation ID does not exist at the time _botConnection is created, so to set it for the first time, we will do so in our ChatActivity method which is attached to _botConnection.activity$.subscribe().

That’s it! Once this code is in place, the chat history will persist for the user for a day (notice the expires:1).

A few things to note:

  1. Setting watermark=”0" will attempt to get all messages since the initiation of the conversation. You can always check the _botConnection.watermark for the current watermark if you wish to store a particular point in time as the history starting point.
  2. There is no guarantee that DirectLine will have all messages since the beginning of the conversation. It keeps a buffer, and will load them in order, but they do get removed at some point based on age.
  3. You can clear a users chat history by calling Cookies.remove(“AtBotCID”);

AtBot brings AI within reach

AtBot is the premiere bot-as-a-service solution for the Microsoft cloud. Built completely within Azure, AtBot is your out-of-the-box, easy-to-configure bot for Teams, SharePoint, or the web. Teach AtBot tasks using Power Automate, make him your corporate source of knowledge with QnA Maker, help him understand almost anything your colleagues could ask thanks to LUIS, and manage his features with the AtBot Admin Portal. Get going with AtBot Free or start your free trial of AtBot Premium today.

--

--