我们如何在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.
非常感谢,因为 TranscriptLoggerMiddleware 已经存在.
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.