如何正确格式化 Slack 的附件数据 chat.postMessage
How to properly format attachment data for Slack chat.postMessage
我正在尝试使用 Slack 机器人应用程序 API 将 slack 通知合并到我的 C# 应用程序中。下面的代码工作正常,但是用于 attachments
字段的格式使得编辑和维护变得非常困难......必须有更简单的方法来填充 json 数组吗?
我尝试了多种方式来编写它,但除了使用这种笨拙的语法外,我无法使其正常工作。
var data = new NameValueCollection
{
["token"] = "token", // Removed my actual token from here obviously
["channel"] = "channel", // Same with the channel
["as_user"] = "true",
["text"] = "test message 2",
["attachments"] = "[{\"fallback\":\"dummy\", \"text\":\"this is an attachment\", \"color\":\"#F35A00\", \"title\" : \"Title\", \"title_link\": \"http://www.google.com\"}]"
};
var client = new WebClient();
var response = client.UploadValues("https://slack.com/api/chat.postMessage", "POST", data);
"unwieldy" 语法是手工编写的 JSON,更好的方法是将附件构造为 C# 对象,然后将它们转换为 JSON 作为 API 需要。
我的示例使用外部库 Json.NET 进行 JSON 转换。
C# 对象示例:
// a slack message attachment
public class SlackAttachment
{
public string fallback { get; set; }
public string text { get; set; }
public string image_url { get; set; }
public string color { get; set; }
}
创建新 attachments
数组的示例:
var attachments = new SlackAttachment[]
{
new SlackAttachment
{
fallback = "this did not work",
text = "This is attachment 1",
color = "good"
},
new SlackAttachment
{
fallback = "this did not work",
text = "This is attachment 2",
color = "danger"
}
};
最后,将 attachments
数组转换为 JSON 以获得 API:
var attachmentsJson = JsonConvert.SerializeObject(attachments);
另请参阅 以获取完整示例。
我正在尝试使用 Slack 机器人应用程序 API 将 slack 通知合并到我的 C# 应用程序中。下面的代码工作正常,但是用于 attachments
字段的格式使得编辑和维护变得非常困难......必须有更简单的方法来填充 json 数组吗?
我尝试了多种方式来编写它,但除了使用这种笨拙的语法外,我无法使其正常工作。
var data = new NameValueCollection
{
["token"] = "token", // Removed my actual token from here obviously
["channel"] = "channel", // Same with the channel
["as_user"] = "true",
["text"] = "test message 2",
["attachments"] = "[{\"fallback\":\"dummy\", \"text\":\"this is an attachment\", \"color\":\"#F35A00\", \"title\" : \"Title\", \"title_link\": \"http://www.google.com\"}]"
};
var client = new WebClient();
var response = client.UploadValues("https://slack.com/api/chat.postMessage", "POST", data);
"unwieldy" 语法是手工编写的 JSON,更好的方法是将附件构造为 C# 对象,然后将它们转换为 JSON 作为 API 需要。
我的示例使用外部库 Json.NET 进行 JSON 转换。
C# 对象示例:
// a slack message attachment
public class SlackAttachment
{
public string fallback { get; set; }
public string text { get; set; }
public string image_url { get; set; }
public string color { get; set; }
}
创建新 attachments
数组的示例:
var attachments = new SlackAttachment[]
{
new SlackAttachment
{
fallback = "this did not work",
text = "This is attachment 1",
color = "good"
},
new SlackAttachment
{
fallback = "this did not work",
text = "This is attachment 2",
color = "danger"
}
};
最后,将 attachments
数组转换为 JSON 以获得 API:
var attachmentsJson = JsonConvert.SerializeObject(attachments);
另请参阅