我们如何在Microsoft bot框架中将用户消息和bot消息都记录到comos db [英] How can we log both user and bot messages to comos db in microsoft bot framework

查看:114
本文介绍了我们如何在Microsoft bot框架中将用户消息和bot消息都记录到comos db的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have created a chat bot using microsoft bot framework v4 sdk. I wanted to log bot user and bot messages to cosmos db.

我只能使用下面的博客

i am able to log only user messages using below blog 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 .

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

I expect to log both user and bot responses.

推荐答案

非常感谢,因为

Thankfully, this is pretty easy since ItranscriptLogger and TranscriptLoggerMiddleware already exist.

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);
[...]

结果:

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

This is probably the easiest/best way to do it. However, you can also capture outgoing activities under OnTurnAsync() using turnContext.OnSendActivities() and then write the outgoing activity to storage, as well.

这篇关于我们如何在Microsoft bot框架中将用户消息和bot消息都记录到comos db的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆