Reputation: 1336
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;
}
Upvotes: 3
Views: 1821
Reputation: 32757
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.
Upvotes: 1