从Bot用户那里获取附件并存储以备将来使用

时间:2018-10-31 05:45:06

标签: c# botframework formflow

我在一个机器人上工作,我需要从用户那里收集一些信息来创建带有附件的订单。我正在使用表单流来收集信息,并使用该信息来创建工单/订单。如何从接收方接收附件并将其与其他信息一起用于处理订单。

下面是我目前正在使用的表单代码

 [Serializable]
public class SupportTicketForm
{

    [Prompt("Please choose # category... {||}", ChoiceStyle = ChoiceStyleOptions.Buttons)]
    public string Category;

    [Prompt("Please choose  # sub category... {||}", ChoiceStyle = ChoiceStyleOptions.Buttons)]
    public string Subcategory;

    [Prompt("We need some more details to create the request, provide me your **Contact Number**...")]
    //[Pattern(Validations.Phone)]
    [Required(ErrorMessage = "Contact Number is required")]
    public int ContactNumber;

    [Prompt("Please provide **Details** for the technician to diagnose probolem ...")]
    public string Description;

    [Prompt("Please provide **Justification**...")]
    public string Justification;

    //[Optional]
    //[AttachmentContentTypeValidator(ContentType = "png")]
    //public AwaitableAttachment AttachImage;


    public static IForm<SupportTicketForm> BuildForm()
    {
        List<Category> categories = CategoryDataService.GetCategories() ?? new List<Category>();

        return new FormBuilder<SupportTicketForm>()
                 .Field(new FieldReflector<SupportTicketForm>(nameof(Category))
                .SetType(null)
                .SetDefine(async (state, field) =>
                {
                    try
                    {
                        categories.ForEach(x =>
                        {
                            field.AddDescription(x.Name, x.Name).AddTerms(x.Name, x.Name);
                        });
                    }
                    catch (Exception exception)
                    {

                    }
                    return true;
                }))
                .Field(new FieldReflector<SupportTicketForm>(nameof(Subcategory))
                .SetType(null)
                .SetDefine(async (state, field) =>
                {
                    try
                    {
                        if (!string.IsNullOrEmpty(state.Category))
                        {
                            categories.FirstOrDefault(x => x.Name.Equals(state.Category)).Subcategories.ToList().ForEach(x =>
                              {
                                  field.AddDescription(x, x).AddTerms(x, x);
                              });
                        }
                    }
                    catch (Exception exception)
                    {

                    }
                    return true;
                }))
                .Field(nameof(ContactNumber))
                .Field(nameof(Description))
                .Field(nameof(Justification))
               // .Field(nameof(AttachImage))

                .Confirm(async (state) =>
                {
                    return new PromptAttribute("**Please review your selection, I'll create a ticket for you..!!**" +
                         " \r\n\r\n Category : {Category}," +
                         " \r\n\r\n SubCategory : {Subcategory}," +
                         " \r\n\r\n Contact Number : {ContactNumber}," +
                         " \r\n\r\n Description : {Description}, " +
                         " \r\n\r\n Justification : {Justification}." +
                         " \r\n\r\n Do you want to continue? {||}");
                })
                .Build();
    }
}

我如何获得附件??

2 个答案:

答案 0 :(得分:0)

您已注释掉的AwaitableAttachment应该可以正常工作。我猜想您遵循了this sample,但如果您没有,请看看。

如果遇到错误,不是因为您的AwaitableAttachment,而是因为您的Confirm()步骤。继续,将.AddRemainingFields()放在前面。

答案 1 :(得分:0)

您可以在下面的代码段中尝试一下吗

`   [Serializable]
public class ImagesForm : IDialog<ImagesForm>
{
    [AttachmentContentTypeValidator(ContentType = "pdf")]
    [Prompt("please, provide the file")]
    public AwaitableAttachment file_attachment;


    public async Task StartAsync(IDialogContext context)
    {
        var state = this;
        var form = new FormDialog<ImagesForm>(state, BuildForm, FormOptions.PromptInStart);
        context.Call(form, AfterBuildForm);
    }

    private async Task AfterBuildForm(IDialogContext context, IAwaitable<ImagesForm> result)
    {
        context.Done(result);
    }

    public static IForm<ImagesForm> BuildForm()
    {
        OnCompletionAsyncDelegate<ImagesForm> onFormCompleted = async (context, state) =>
        {

            var botAccount = new ChannelAccount(name: $"{ConfigurationManager.AppSettings["BotId"]}", id: $"{ConfigurationManager.AppSettings["BotEmail"]}".ToLower());
            var userAccount = new ChannelAccount(name: "Name", id: $"{ConfigurationManager.AppSettings["UserEmail"]}");
            MicrosoftAppCredentials.TrustServiceUrl(@"https://email.botframework.com/", DateTime.MaxValue);
            var connector = new ConnectorClient(new Uri("https://email.botframework.com/" ));
            var conversationId = await connector.Conversations.CreateDirectConversationAsync(botAccount, userAccount);
            IMessageActivity message = Activity.CreateMessageActivity();
            message.From = botAccount;
            message.Recipient = userAccount;
            message.Conversation = new ConversationAccount(id: conversationId.Id);

            var myfile= state.file_attachment;
            message.Attachments = new List<Attachment>();
            message.Attachments.Add(myfile);

            try
            {
                await connector.Conversations.SendToConversationAsync((Activity)message);
            }
            catch (ErrorResponseException e)
            {
                Console.WriteLine("Error: ", e.StackTrace);
            }


            var resumeSize = await RetrieveAttachmentSizeAsync(state.file_attachment);
        };
        return new FormBuilder<ImagesForm>()
                    .Message("Welcome")
                    .OnCompletion(onFormCompleted)
                    .Build();
    }

    private static async Task<long> RetrieveAttachmentSizeAsync(AwaitableAttachment attachment)
    {
        var stream = await attachment;
        return stream.Length;
    }

}`