我正在为聊天机器人编程,我希望用户上传图像,以便该机器人可以接收它并将图像保存到用户配置文件数据中。但是我在C#中还很陌生,我有点迷路了...
我正在使用MS Bot Framework。要构建对话框,我使用Waterfall步骤,并使用提示来捕获用户答复。为了接收附件,我在MS文档上看到它存在一个AttachmentPrompt类。但是我对如何使用它以及如何将文件保存在用户配置文件中感到困惑。
这就是我构建瀑布对话框的方式:
public class MainDialog : ComponentDialog
{
// Prompts names
private const string PhotoPrompt = "PhotoPrompt";
// Dialog IDs
private const string ProfileDialog = "profileDialog";
public MainDialog(IStatePropertyAccessor<IncidentFile> IncidentFileStateAccessor, ILoggerFactory loggerFactory)
: base(nameof(MainDialog))
{
IncidentFileAccessor = IncidentFileStateAccessor ?? throw new ArgumentNullException(nameof(IncidentFileStateAccessor));
// Add control flow dialogs
var waterfallSteps = new WaterfallStep[]
{
InitializeStateStepAsync,
PromptForPhotoStepAsync,
DisplayGreetingStateStepAsync,
};
AddDialog(new WaterfallDialog(ProfileDialog, waterfallSteps));
AddDialog(new AttachmentPrompt(PhotoPrompt));
}
然后,这是捕获提示的功能:
private async Task<DialogTurnResult> PromptForPhotoStepAsync(WaterfallStepContext stepContext,CancellationToken cancellationToken)
{
var IncidentState = await IncidentFileAccessor.GetAsync(stepContext.Context);
if (string.IsNullOrWhiteSpace(IncidentState.Photo))
{
// prompt for Photo, if missing in User profil
var opts = new PromptOptions
{
Prompt = new Activity
{
Type = ActivityTypes.Message,
Text = "Can you send me a photo please?",
},
};
return await stepContext.PromptAsync(PhotoPrompt, opts);
}
else
{
return await stepContext.NextAsync();
}
}
这就是我保存用户数据的方式:
public class IncidentFile
{
public string Name { get; set; }
public string Photo { get; set; }
}
我不知道我是否正确使用了AttachmentPrompt类。我也不知道附件提示是如何将图像发送到机器人的,因此在IncidentFile中,我为Photo放置了“ public string”,但是我不知道它是否应该是字节数组或路径图像位置的位置。 但是无论如何,在我对其进行测试并上传了照片之后,该机器人回答说出了问题...
谢谢您的时间!
答案 0 :(得分:3)
您是如此亲密!用户上传照片后,您可以使用stepContext.Result
在下一个Waterfall步骤中访问它:
如您所见,类型为Microsoft.Bot.Schema.Attachment
,因此将您的IncidentFile
更改为:
using Microsoft.Bot.Schema;
namespace <your-namespace>
{
public class IncidentFile
{
public string Name { get; set; }
public Attachment Photo { get; set; }
}
}
您可以在上传步骤之后的步骤中使用以下方式保存该信息:
// Load the IncidentFile
var incidentFile = await IncidentFileAccessor.GetAsync(stepContext.Context);
// Save the photo
incidentFile.Photo = ((List<Attachment>)stepContext.Result)[0];
await IncidentFileAccessor.SetAsync(stepContext.Context, incidentFile);
结果: