我们如何在Microsoft bot框架中将用户消息和bot消息都记录到comos db

时间:2019-05-07 05:57:41

标签: c# logging botframework

我已经使用Microsoft bot框架v4 sdk创建了聊天机器人。我想将机器人用户和机器人消息记录到cosmos db。

我只能使用下面的博客https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-v4-storage?view=azure-bot-service-4.0&tabs=csharp#using-cosmos-db记录用户消息。

我希望同时记录用户和漫游器的响应。

1 个答案:

答案 0 :(得分:1)

非常感谢,这很容易,因为ItranscriptLoggerTranscriptLoggerMiddleware已经存在。

创建您的TranscriptStore类(新的类文件)

using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Azure;
using Microsoft.Bot.Schema;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace QuickTestBot_CSharp
{
    public class CosmosTranscriptStore : ITranscriptLogger
    {
        private CosmosDbStorage _storage;

        public CosmosTranscriptStore(CosmosDbStorageOptions config)
        {
            _storage = new CosmosDbStorage(config);
        }
        public async Task LogActivityAsync(IActivity activity)
        {
            // activity only contains Text if this is a message
            var isMessage = activity.AsMessageActivity() != null ? true : false;
            if (isMessage)
            {
                // Customize this to save whatever data you want
                var data = new
                {
                    From = activity.From,
                    To = activity.Recipient,
                    Text = activity.AsMessageActivity().Text,
                };
                var document = new Dictionary<string, object>();
                // activity.Id is being used as the Cosmos Document Id
                document.Add(activity.Id, data);
                await _storage.WriteAsync(document, new CancellationToken());
            }
        }
    }
}

创建和添加中间件(在Startup.cs中)

[...]
var config = new CosmosDbStorageOptions
{
    AuthKey = "<YourAuthKey>",
    CollectionId = "<whateverYouWant>",
    CosmosDBEndpoint = new Uri("https://<YourEndpoint>.documents.azure.com:443"),
    DatabaseId = "<whateverYouWant>",
};

var transcriptMiddleware = new TranscriptLoggerMiddleware(new CosmosTranscriptStore(config));

var middleware = options.Middleware;
middleware.Add(transcriptMiddleware);
[...]

结果:

enter image description here

enter image description here

注意:

这可能是最简单/最佳的方法。但是,您也可以使用OnTurnAsync()turnContext.OnSendActivities()下捕获传出活动,然后将传出活动也写入存储。