aslebedev
aslebedev

Reputation: 31

Bot Builder SDK 4 How to work with attachments?

Bot Builder SDK 4 (dotnet) How to work with attachments ? I tried to use the example of BotBuilder-Samples 15.handling-attachments, but got 401 Unauthorized error with Skype channel.

foreach (var file in activity.Attachments)
{
    // Determine where the file is hosted.
    var remoteFileUrl = file.ContentUrl;

    // Save the attachment to the system temp directory.
    var localFileName = Path.Combine(Path.GetTempPath(), file.Name)

    // Download the actual attachment
    using (var webClient = new WebClient())
    {
        webClient.DownloadFile(remoteFileUrl, localFileName); <-- 401 here
    }

Upvotes: 2

Views: 454

Answers (1)

Ferdinand Fejskid
Ferdinand Fejskid

Reputation: 537

I have discovered solution at github.com discussion Skype Can not receive attachment? #3623 which I also have just tested with success.

I see minimal modification to your code sample as follows:

string channelToken = null;

if ((activity.ChannelId.Equals("skype", StringComparison.InvariantCultureIgnoreCase)) 
{
    var credentials = new MicrosoftAppCredentials(youBotAppId, yourBotAppPassword);

    channelToken = await credentials.GetTokenAsync();
}

foreach (var file in activity.Attachments)
{
    // Determine where the file is hosted.
    var remoteFileUrl = file.ContentUrl;

    // Save the attachment to the system temp directory.
    var localFileName = Path.Combine(Path.GetTempPath(), file.Name)

    // Download the actual attachment
    using (var webClient = new WebClient())
    {
        if (!string.IsNullOrWhiteSpace(channelToken))
        {
            webClient.DefaultRequestHeaders.Authorization = 
                new AuthenticationHeaderValue("Bearer", channelToken);
        }

        webClient.DownloadFile(remoteFileUrl, localFileName);
    }

Upvotes: 1

Related Questions