我正在使用 botframework 、 c# 创建一个机器人。我也在使用 qnamaker。我的问题是如何将用户的问题和答案存储在数据库中。目前我只能将用户发送的消息存储在日志表中,如下所示:
消息控制器.cs:
// if (activity.Type == ActivityTypes.Message)
{
*************************
// Log to Database
// *************************
// Instantiate the BotData dbContext
Model.qnamakerbotdataEntities DB = new Model.qnamakerbotdataEntities();
// 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);
// Add the UserLog object to UserLogs
DB.UserLogs.Add(NewUserLog);
// Save the changes to the database
DB.SaveChanges();
您知道如何存储用户发送的消息和机器人的响应吗?
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("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);
}
private async Task QnADialog(IDialogContext context, IAwaitable<object> result)
{
var activityResult = await result as Activity;
var query = activityResult.Text;
var qnaResult = QnaApi.GetFirstQnaAnswer(query);
if (qnaResult == null)
{
string message = $"Sorry, I did not understand . Please
reformulate your question";
}
else
{
await context.PostAsync(qnaResult.answers[0].answer);
}
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;
}
}
}