Akshay Akshay - 1 year ago 136
C# Question

Is there a way to accept file as an attachment in bot framework?

I have published my bot on Microsoft teams. Now I want to include a functionality in which, a user can upload a file as an attachment & bot will upload it on blob storage, How to handle this in bot framework?

Answer Source

The attachments sent by the user will end up in the Attachments collection of the IMessageActivity. There you will find the URL of the attachment the user sent.

Then, you will have to download the attachment and add your logic to upload it to Blob storage or any other storage you would like to use.

Here is a C# example showing how to access and download the attachments sent by the user. Added the code below for your reference:

public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument)
    var message = await argument;

    if (message.Attachments != null && message.Attachments.Any())
        var attachment = message.Attachments.First();
        using (HttpClient httpClient = new HttpClient())
            // Skype attachment URLs are secured by a JwtToken, so we need to pass the token from our bot.
            if (message.ChannelId.Equals("skype", StringComparison.InvariantCultureIgnoreCase) && new Uri(attachment.ContentUrl).Host.EndsWith("skype.com"))
                var token = await new MicrosoftAppCredentials().GetTokenAsync();
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            var responseMessage = await httpClient.GetAsync(attachment.ContentUrl);

            var contentLenghtBytes = responseMessage.Content.Headers.ContentLength;

            await context.PostAsync($"Attachment of {attachment.ContentType} type and size of {contentLenghtBytes} bytes received.");
        await context.PostAsync("Hi there! I'm a bot created to show you how I can receive message attachments, but no attachment was sent to me. Please, try again sending a new message including an attachment.");

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download