Botframework 如何记录历史

Botframework how log history

您知道如何记录所有 outgoing/incoming 消息吗?我不确定如何捕获外发消息。

我使用链条和表格。 例如

await Conversation.SendAsync(activity, rootDialog.BuildChain);

activity.CreateReply(.....);

我好像无法记录外发消息。

我修改了SDK源码

在Conversations.cs

中添加事件

比如这样。

  public delegate void MessageSendedEventHandler(object sender, Activity activity, string conversationId);
    public static event MessageSendedEventHandler MessageSended;

并在每个 Send....HttpMessagesAsync 方法中添加 这个MessageSended?.Invoke(this, activity, conversationId);

这不是很好的解决方案。但它的工作

我找到了更好的解决方案

    public class BotToUserLogger : IBotToUser
{
    private readonly IMessageActivity _toBot;
    private readonly IConnectorClient _client;

    public BotToUserLogger(IMessageActivity toBot, IConnectorClient client)
    {
        SetField.NotNull(out _toBot, nameof(toBot), toBot);
        SetField.NotNull(out _client, nameof(client), client);
    }

    public IMessageActivity MakeMessage()
    {
        var toBotActivity = (Activity)_toBot;
        return toBotActivity.CreateReply();
    }

    public async Task PostAsync(IMessageActivity message, CancellationToken cancellationToken = default(CancellationToken))
    {
        await _client.Conversations.ReplyToActivityAsync((Activity)message, cancellationToken);
    }
}

public class BotToUserDatabaseWriter : IBotToUser
{
    private readonly IBotToUser _inner;
    public BotToUserDatabaseWriter(IBotToUser inner)
    {
        SetField.NotNull(out _inner, nameof(inner), inner);
    }
    public IMessageActivity MakeMessage()
    {
        return _inner.MakeMessage();
    }

    public async Task PostAsync(IMessageActivity message, CancellationToken cancellationToken = default(CancellationToken))
    {
        // loging outgoing message
        Debug.WriteLine(message.Text);

        //TODO log message for example into DB

        await _inner.PostAsync(message, cancellationToken);
    }

控制器使用中

 public MessagesController()
    {
        var builder = new ContainerBuilder();
        builder.RegisterType<BotToUserLogger>()
            .AsSelf()
            .InstancePerLifetimeScope();

        builder.Register(c => new BotToUserTextWriter(c.Resolve<BotToUserLogger>()))
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();
        builder.Update(Microsoft.Bot.Builder.Dialogs.Conversation.Container);
    }