【发布时间】:2020-02-13 12:44:59
【问题描述】:
我正在尝试将 chat.postMesage 与 Slack 的 API 一起使用,但无法将附件作为消息的一部分发送。
我想我可以使用image_url 作为attachment 对象的一部分,以便在我的消息中显示图像。
我在回复中没有收到任何错误,但也没有看到任何附件。 消息正在发布,但根本没有附件。
这就是我想要做的事情
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;
}
【问题讨论】:
-
attachments必须是附件数组。从您的代码看来,您只提供了一个附件。可以肯定的是,请将 JSON 添加到您的问题中。为了比较:这是 C# 中的一个工作示例:stackoverflow.com/a/53328625/4379151 -
看来将附件作为数组发送是我的问题。我需要将其更改为数组并尝试一下。
-
@Rob 是的。绝对做到了