0

MessagesController.cs我的代码中,我添加了一个部分来保存用户日志数据,如用户 ID、用户名、频道、日期、消息......我还想保存机器人的答案吗?但我不知道该怎么做。数据库是天蓝色的。

这是代码:MessagesController.cs

    using System.Net.Http;
   using System.Threading.Tasks;
     using System.Web.Http;
  using Microsoft.Bot.Builder.Dialogs;
 using Microsoft.Bot.Connector;
 using System;
 using System.Net;

 namespace QnABot
 {
[BotAuthentication]
public class MessagesController : ApiController
{
    /// <summary>
    /// POST: api/Messages
    /// Receive a message from a user and reply to it
    /// </summary>
    public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
    {

        #region Set CurrentBaseURL and ChannelAccount
        // Get the base URL that this service is running at
        // This is used to show images
        string CurrentBaseURL =

     this.Url.Request.RequestUri.AbsoluteUri.Replace(@"api/messages", "");

        // Create an instance of BotData to store data
        BotData objBotData = new BotData();

        // Instantiate a StateClient to save BotData            
        StateClient stateClient = activity.GetStateClient();

        // Use stateClient to get current userData
        BotData userData = await stateClient.BotState.GetUserDataAsync(
            activity.ChannelId, activity.From.Id);

        // Update userData by setting CurrentBaseURL and Recipient
        userData.SetProperty<string>("CurrentBaseURL", CurrentBaseURL);

        // Save changes to userData
        await stateClient.BotState.SetUserDataAsync(
            activity.ChannelId, activity.From.Id, userData);
        #endregion

        if (activity.Type == ActivityTypes.Message)
        {



            //*************************
            //Log to Database
            // *************************

            //// Instantiate the BotData dbContext
            Model.qnamakerentitiesEntities DB = new 
           Model.qnamakerentitiesEntities();
            // Create a new UserLog object
            Model.UserLog NewUserLog = new Model.UserLog();

            // Set the properties on the UserLog object
            NewUserLog.Channel = activity.ChannelId;
            NewUserLog.UserID = activity.From.Id;
            NewUserLog.UserName = activity.From.Name;
            NewUserLog.created = DateTime.UtcNow;
            NewUserLog.Message = activity.Text.Truncate(500);
            //   NewUserLog.Response = activity.AsMessageActivity()?.Text;



            // Add the UserLog object to UserLogs
            DB.UserLogs.Add(NewUserLog);
            // Save the changes to the database
            DB.SaveChanges();


            await Conversation.SendAsync(activity, () => new 
        Dialogs.QnADialog());
        }
        else
        {
            await HandleSystemMessage(activity);
        }
        var response = Request.CreateResponse(HttpStatusCode.OK);
        return response;
    }

    private async Task<Activity> HandleSystemMessage(Activity message)
    {
        if (message.Type == ActivityTypes.DeleteUserData)
        {
            // Implement user deletion here
            // If we handle user deletion, return a real message
        }
        else if (message.Type == ActivityTypes.ConversationUpdate)
        {
            IConversationUpdateActivity iConversationUpdated = message as 
       IConversationUpdateActivity;
            if (iConversationUpdated != null)
            {
            }
        }
        else if (message.Type == ActivityTypes.ContactRelationUpdate)
        {
            // Handle add/remove from contact lists
            // Activity.From + Activity.Action represent what happened
        }
        else if (message.Type == ActivityTypes.Typing)
        {
            // Handle knowing tha the user is typing
        }
        else if (message.Type == ActivityTypes.Ping)
        {
        }

        return null;
         }
       }
     }

RootDialog.cs 是这样的:

  using System;
  using System.Threading.Tasks;
  using Microsoft.Bot.Builder.Dialogs;
  using Microsoft.Bot.Connector;
  using QnABot.API;
  using Microsoft.Bot.Builder.Dialogs.Internals;

  namespace QnABot.Dialogs
  {
  [Serializable]
  public class RootDialog : IDialog<object>
   {
    public Task StartAsync(IDialogContext context)
    {
        context.Wait(MessageReceivedAsync);

        return Task.CompletedTask;
    }

    private async Task MessageReceivedAsync(IDialogContext context, 
     IAwaitable<object> result)
    {
        //var activity = await result as Activity;

        //// Prompt text
        //await context.PostAsync("Welcome Feel free to ask me ");

        //var privateData = context.PrivateConversationData;
        //var privateConversationInfo = IncrementInfoCount(privateData, 
   BotStoreType.BotPrivateConversationData.ToString());
        //var conversationData = context.ConversationData;
        //var conversationInfo = IncrementInfoCount(conversationData, 
   BotStoreType.BotConversationData.ToString());
        //var userData = context.UserData;
        //var userInfo = IncrementInfoCount(userData, 
     BotStoreType.BotUserData.ToString());
        //context.Wait(QnADialog);



  //privateData.SetValue(BotStoreType.BotPrivateConversationData.ToString(), 
      privateConversationInfo);

   //conversationData.SetValue(BotStoreType.BotConversationData.ToString(), conversationInfo);
        //userData.SetValue(BotStoreType.BotUserData.ToString(), userInfo);
        Activity replyToConversation = (Activity)context.MakeMessage();
        replyToConversation.Recipient = replyToConversation.Recipient;
        replyToConversation.Type = "message";
    }

    private async Task QnADialog(IDialogContext context, IAwaitable<object> 
    result)
    {
        var activityResult = await result as Activity;
        var query = activityResult.Text;
        var reply = activityResult.CreateReply();

        var qnaResult = QnaApi.GetFirstQnaAnswer(query);
        string message = "";

        if (qnaResult == null)
        {
             message = $"Sorry, I did not understand . Please reformulate 
        your question";

        }
        else
        {
            message = qnaResult.answers[0].answer;
        }



        // *************************
        // Log to Database
        // *************************
        Activity replyToConversation = (Activity)context.MakeMessage();
        // Instantiate the BotData dbContext
        Model.qnamakerentitiesEntities DB = new 
        Model.qnamakerentitiesEntities();
        // Create a new UserLog object
        Model.UserLog NewUserLog = new Model.UserLog();

        // Set the properties on the UserLog object
        NewUserLog.Channel = replyToConversation.ChannelId;
        NewUserLog.UserID = replyToConversation.From.Id;
        NewUserLog.UserName = replyToConversation.From.Name;
        NewUserLog.created = DateTime.UtcNow;
        // This logs the message being sent to the user
        NewUserLog.Message = qnaResult.answers[0].answer;
        //  NewUserLog.Response= qnaResult.answers[0].answer;

        // Add the UserLog object to UserLogs
        DB.UserLogs.Add(NewUserLog);
        // Save the changes to the database
        DB.SaveChanges();

        await context.PostAsync(replyToConversation);
        context.Wait(MessageReceivedAsync);
    }
    public class BotDataInfo
    {
        public int Count { get; set; }
    }

    private BotDataInfo IncrementInfoCount(IBotDataBag botdata, string key)
    {
        BotDataInfo info = null;
        if (botdata.ContainsKey(key))
        {
            info = botdata.GetValue<BotDataInfo>(key);
            info.Count++;
        }
        else
            info = new BotDataInfo() { Count = 1 };

        return info;
    }
}
}

我尝试按照您的指示进行操作,但仍有问题。我可以存储在数据库 ID、UserId、ChannelID、created、消息中,但不能存储响应(在我的所有测试中响应为 null)。

你能帮我做什么吗?

4

1 回答 1

1

一种方法是实现一个IActivityLogger检查传入和传出消息的方法。在core-Middleware示例中,您将看到有关如何执行此操作的示例。

public class DebugActivityLogger : IActivityLogger
    {
        public async Task LogAsync(IActivity activity)
        {
            Debug.WriteLine($"From:{activity.From.Id} - To:{activity.Recipient.Id} - Message:{activity.AsMessageActivity()?.Text}");
        }
    }

此外,您可能会遇到知道消息何时来自机器人的问题。在这种情况下,我建议您阅读Know if IActivity is from bot or user in IActivityLogger

于 2017-08-24T10:35:04.800 回答