Search code examples
c#botframeworkformflow

get attachment from Bot user and store for future use


I am working on a bot where I need to collect some information from the user to create an order along with the attachment. I am using form flow to collect the information and using the information for creating the Ticket/Order. How can I receive attachment from the receiver and use it with other infoirmation for processing order.

Below is the form code I'm currently working with

 [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();
    }
}

How can I receive attachement with it.?


Solution

  • Can you try this below piece of code

    `   [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;
        }
    
    }`