Before You Start
One of the key concepts to understand if your website will receive a series of messages. These messages by default know nothing about the previous chain between the user and bot. It is important to know how to store a state or "where we left off" so the user doesn't get stuck in a loop of repeated questions. There are some useful properties you can use to track users, the Conversation (unique id) and the From (A user's address on a channel) You can also use they together if you like.
So how to do you put and get information about the state of the ongoing conversation?
State Methods
The Bot State service exposes the following methods
Method | Scoped to | Use cases |
---|---|---|
GetUserData() | User | Remembering context object with a user |
GetConversationData() | Conversation | Remembering context object with a conversation |
GetPrivateConversationData() | User & Conversation | Remembering context object with a person in a conversation |
SetUserData() | User | Remembering context object with a user |
SetConversationData() | Conversation | Remembering context object with a conversation |
SetPrivateConversationData() | User & Conversation | Remembering context object with a person in a conversation |
DeleteStateForUser() | User | When the user requests data be deleted or removes the bot contact |
StateClient stateClient = activity.GetStateClient();
Setting the State
BotData userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);
userData.SetProperty<bool>("SentGreeting", true);
await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);
Getting the State
BotData userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);
if (userData.GetProperty<bool>("SentGreeting"))
... do something ...;
Setting a Complex Type
BotState botState = new BotState(stateClient);
BotData botData = new BotData(eTag: "*");
botData.SetProperty<BotState>("UserData", myUserData);
BotData response = await stateClient.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, botData);
Getting a Complex Type
MyUserData addedUserData = new MyUserData();
BotData botData = await botState.GetUserDataAsync(activity.ChannelId, activity.From.Id);
myUserData = botData.GetProperty<MyUserData>("UserData");
So now that we know how to read and save, next week we can begin to have a conversation with someone trying to order a sandwich. If you would like to play with a bot I designed I have added it below.
Doug Routledge, C# Lync, Skype for Business, SQL, Exchange, UC,
Full Stack Developer BridgeOC Bridge Operator Console Twitter - @droutledge @ndbridge |
What is the purpose of DeleteStateForUser?
ReplyDeleteIf you had a bot asking a series of questions, and a user wanted to start over, this would clear the state you are using to store the responses.
Delete