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

get attachment from Bot user and store for future use

我正在开发一个机器人,我需要从用户那里收集一些信息来创建订单和附件。我正在使用表单流来收集信息并使用这些信息来创建 Ticket/Order。如何从接收方接收附件并将其与其他信息一起用于处理订单。

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

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

如何接收附件?

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

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

你能试试下面这段代码吗

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

}`