3

I'm trying to use chat.postMesage with Slack's API but can't send an attachment as part of the message. I thought I can use image_url as part of the attachment object in order to show an image as part of my message.

I'm not getting any error in the response but either don't see any attachment. The message is being posted but no attachments at all.

Here's what I'm trying to do

public async Task<string>  PostMessage()
{
    var response = string.Empty;

    var slacAttributes = new stackAttributes
    {
        channel = "testapp",
        text = $" {DateTime.Now} > {Environment.NewLine} Good Morning all!!!{Environment.NewLine} new line",
        attachments = new slackAttachments { fallback = "exception", text = "image text",title="kuku", image_url = "https://i.imgur.com/jO9N3eJ.jpg" }
    };

    try
    {
        using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "xoxp-927360717313-937536168112-927367533025-c1065234477a3de10257bc69f523f789");
            var atttrJson = slacAttributes;
        var json = new JavaScriptSerializer().Serialize(atttrJson);
        var buffer = System.Text.Encoding.UTF8.GetBytes(json);
        var byteContent = new ByteArrayContent(buffer);
        byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        HttpResponseMessage result =  await client.PostAsync("https://slack.com/api/chat.postMessage", byteContent);
        if(result.IsSuccessStatusCode)
        {
            var content = await result.Content?.ReadAsByteArrayAsync();
            response = Encoding.UTF8.GetString(content, 0, content.Length);
        }
    }
    }
    catch(Exception e)
    {
        throw new Exception($"An error occured while Posting to slack.{e}");
    }

    return response;  
}
Robert
  • 2,407
  • 1
  • 24
  • 35
JumpIntoTheWater
  • 1,306
  • 2
  • 19
  • 46
  • `attachments` has to be an array of attachments. From your code it looks like you are only providing a single attachment. To be sure please add the JSON to your question. For comparison: Here is a working example in C#: https://stackoverflow.com/a/53328625/4379151 – Erik Kalkoken Feb 13 '20 at 13:04
  • it looks like sending the attachment as an array is my issue. I need to change it to an array and try it. – JumpIntoTheWater Feb 13 '20 at 13:15
  • @Rob yes. definitely did the job – JumpIntoTheWater Feb 13 '20 at 14:22

1 Answers1

1

The attachments property has to be an array of attachment objects. From your code it looks like you are only providing a single attachment object, but not an array.

Erik Kalkoken
  • 30,467
  • 8
  • 79
  • 114