【问题标题】:How to properly format attachment data for Slack chat.postMessage如何正确格式化 Slack chat.postMessage 的附件数据
【发布时间】:2018-11-15 21:48:20
【问题描述】:

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

【问题讨论】:

    标签: c# slack slack-api


    【解决方案1】:

    “笨拙”的语法是手工制作的 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

    【讨论】:

    • 做到了!感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多