I am trying to upload attachment from user to Bot, I tried to write the code as straight forward and test it on Microsoft Bot Emulator. the problem is I am getting error (Send failed) POST 400 directline/conversations//upload
This is the code I am using.
public class AttachmentsBot : ActivityHandler
{
private readonly IHttpClientFactory _httpClientFactory;
public AttachmentsBot(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
{
var attachments = turnContext.Activity.Attachments;
if (attachments != null && attachments.Count > 0)
{
foreach (var attachment in attachments)
{
await ProcessAttachmentAsync(turnContext, attachment, cancellationToken);
}
}
else
{
await turnContext.SendActivityAsync(MessageFactory.Text("Please attach a file."), cancellationToken);
}
}
private async Task ProcessAttachmentAsync(ITurnContext turnContext, Attachment attachment, CancellationToken cancellationToken)
{
var client = _httpClientFactory.CreateClient();
try
{
// Log the ContentUrl for debugging purposes
Console.WriteLine($"Attachment URL: {attachment.ContentUrl}");
// Download the file from the given ContentUrl
var response = await client.GetAsync(attachment.ContentUrl, cancellationToken);
if (response.IsSuccessStatusCode)
{
var fileBytes = await response.Content.ReadAsByteArrayAsync(cancellationToken);
var fileName = attachment.Name ?? "unknown";
var contentType = attachment.ContentType;
// Save the file locally (for example purposes)
var filePath = Path.Combine(Path.GetTempPath(), fileName);
await File.WriteAllBytesAsync(filePath, fileBytes, cancellationToken);
// Respond to the user
await turnContext.SendActivityAsync(
MessageFactory.Text($"Attachment '{fileName}' of type '{contentType}' has been saved to {filePath}."),
cancellationToken);
}
else
{
// Log the error response
Console.WriteLine($"Failed to download attachment. HTTP Status: {response.StatusCode}");
await turnContext.SendActivityAsync(
MessageFactory.Text($"Failed to download attachment: {attachment.Name}. HTTP Status: {response.StatusCode}"),
cancellationToken);
}
}
catch (Exception ex)
{
await turnContext.SendActivityAsync(
MessageFactory.Text($"An error occurred while processing the attachment: {ex.Message}"),
cancellationToken);
}
}
}
I expect to get the attachment and process it in the code.