将用户状态数据存储在Microsoft Bot

时间:2018-08-28 13:54:46

标签: c# azure botframework azure-cosmosdb

  public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
    {
        ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

        if (activity.Type == ActivityTypes.Message)
        {
            Activity isTypingReply = activity.CreateReply();
            isTypingReply.Type = ActivityTypes.Typing;
            await connector.Conversations.ReplyToActivityAsync(isTypingReply);
            StateClient sc = activity.GetStateClient();
            BotData userData = await sc.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id); // have to check on monday

            if (!userData.GetProperty<bool>("ChannelUserData"))
            { // fetch user details    

MS Bot SDK 1.x应用程序中的上述代码片段以更新状态下的用户数据。现在,我正在尝试将旧的bot应用程序升级到Microsoft Bot SDK3.x。我正在使用Cosmos Db来存储状态值。

如何使用channelId和From Id存储或更新用户数据?提取用户详细信息后,我会将其更新为
await sc.BotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, userData);

一年后,正在重新打开Microsoft应用程序,并对它进行很多更改。因此,我无法获取适当的文档。有人可以使用Cosmos DB帮助/指导我状态存储过程吗?

遵循基本设置https://docs.microsoft.com/en-us/azure/bot-service/dotnet/bot-builder-dotnet-state-azure-cosmosdb?view=azure-bot-service-3.0

1 个答案:

答案 0 :(得分:2)

请注意:activity.GetStateClient();返回的旧StateClient已过时。

要使用CosmosDb,请遵循您提到的文档(https://docs.microsoft.com/en-us/azure/bot-service/dotnet/bot-builder-dotnet-state-azure-cosmosdb?view=azure-bot-service-3.0#modify-your-bot-code),在该文档中您将CosmosDb注册为IBotDataStore<BotData>

然后,当您要使用它时,例如获取属性:

using (ILifetimeScope scope = DialogModule.BeginLifetimeScope(Conversation.Container, activity))
{
    var address = Address.FromActivity(activity);
    IBotDataStore<BotData> botDataStore = scope.Resolve<IBotDataStore<BotData>>();
    BotData botData = await botDataStore.LoadAsync(address, destination, CancellationToken.None);
    return botData.GetProperty<T>(propertyName);
}

这里的方法Address.FromActivity(activity);自动获取正确的键以指向正确的项目。