如何正确格式化Slack chat.postMessage的附件数据

时间:2018-11-15 21:48:21

标签: c# slack slack-api

我正在尝试使用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);

1 个答案:

答案 0 :(得分:0)

“笨拙”的语法是手工制作的JSON,更好的方法是将附件构造为C#对象,然后根据API的要求将其转换为JSON。

我的示例使用外部库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数组转换为API的JSON:

var attachmentsJson = JsonConvert.SerializeObject(attachments);

有关完整示例,另请参见this answer