我已经使用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记录用户消息。
我希望同时记录用户和漫游器的响应。
答案 0 :(得分:1)
非常感谢,这很容易,因为ItranscriptLogger和TranscriptLoggerMiddleware已经存在。
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());
}
}
}
}
[...]
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);
[...]
这可能是最简单/最佳的方法。但是,您也可以使用OnTurnAsync()
在turnContext.OnSendActivities()
下捕获传出活动,然后将传出活动也写入存储。