首页 > 解决方案 > 使用 Azure 聊天机器人时如何仅存储用户响应

问题描述

我正在尝试将用户响应存储在表存储中。我只想存储他们输入的用户数据,对机器人的响应不感兴趣。这怎么可能,另外这在触发词上是否可能,例如,当用户说“不”时,它会在那里记录与机器人的第一次交互,例如“你好”。

我已经对此主题进行了大量研究,但仅存储用户输入的记录似乎较少。

对此的任何帮助将不胜感激!

标签: c#azurebotframeworkazure-table-storagechatbot

解决方案


我正在尝试将用户响应存储在表存储中。我只想存储他们输入的用户数据,对机器人的响应不感兴趣。这怎么可能,另外这在触发词上是否可能,例如,当用户说“不”时,它会在那里记录与机器人的第一次交互,例如“你好”。

您似乎只想将用户输入存储在表存储中,而不是存储机器人响应的数据。为了达到这个要求,您可以拦截用户发送的消息MessagesController(或在对话MessageReceivedAsync方法中),然后从中提取您想要的属性值activity并将值存储在表存储中。

public static string firstmessage = null;

/// <summary>
/// POST: api/Messages
/// Receive a message from a user and reply to it
/// </summary>
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
    if (activity.Type == ActivityTypes.Message)
    {
        if (firstmessage == null)
        {
            firstmessage = activity.Text?.ToString();
        }

        storeuserinput(activity);

        await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());

    }
    else
    {
        HandleSystemMessage(activity);
    }
    var response = Request.CreateResponse(HttpStatusCode.OK);
    return response;
}

private void storeuserinput(Activity activity)
{
    var uid = activity.From.Id;
    var uname = activity.From.Name;

    if (activity.Text?.ToLower().ToString() == "no")
    {
        var userinput = firstmessage;
    }

    //extract other data from "activity" object

    //your code logic here
    //store data in your table storage

    //Note: specifcial scenario of user send attachment
}

如果您想将数据存储到 Azure 表存储中,可以使用WindowsAzure.Storage 客户端库将实体存储/添加到表中。

此外, Bot Builder SDK 中的中间件功能使我们能够拦截用户和机器人之间交换的所有消息,您可以参考以下代码片段来实现相同的要求。

public class MyActivityLogger : IActivityLogger
{
    public async Task LogAsync(IActivity activity)
    {
        if (activity.From.Name!= "{your_botid_here}")
        {
            var uid = activity.From.Id;
            var uname = activity.From.Name;

            var userinput = (activity as IMessageActivity).Text?.ToString();

            //extract other data from "activity" properties

            //your code logic here
            //store data in your table storage

            //Note: specifcial scenario of user send attachment

        }
    }
}

推荐阅读