如何使用松弛C#

时间:2019-06-23 17:08:46

标签: c# slack

我想在我的后消息通话中添加多个附件。

我正在使用本文中的示例代码 How to upload any file on Slack via Slack-App in c#

    public class SlackAttachment
    {
        public string fallback { get; set; }
        public string color { get; set; }
        public string pretext { get; set; }
        public string author_name { get; set; }
        public string author_link { get; set; }
        public string author_icon { get; set; }
        public string title { get; set; }
        public string title_link { get; set; }
        public string text { get; set; }
        public string image_url { get; set; }
        public string thumb_url { get; set; }
        public string footer { get; set; }
        public string footer_icon { get; set; }
    }


    public static void SlackPoster(string imgUrl, string channelName){

        string postedMessage = "MessageText";
        var sampleAttachment = new SlackAttachment[]

    {
     new SlackAttachment {
                fallback = "",
                text = "",
                color = "134f46",
                pretext = "",
                author_name = "",
                author_icon = "",
                author_link = "",
                title = $"",
                title_link = "",
                image_url = imgUrl,
             thumb_url = @"https://i.imgur.com/aFAA6tj.png\",
                footer = $"Posted at {DateTime.Now.Day}/" +
           $"{DateTime.Now.Month}/{DateTime.Now.Year}/ " +
           $"{DateTime.Now.Hour}:{DateTime.Now.Minute }",
                footer_icon = ""
                         }
    };

        var attachmentsJson = JsonConvert.SerializeObject(sampleAttachment);
        var data = new NameValueCollection();
        data["token"] = myToken;
        data["channel"] = channelName;
        data["as_user"] = "true";
        data["text"] = postedMessage;
        data["attachments"] = attachmentsJson;
        var client = new WebClient();
        var response = client.UploadValues("https://slack.com/api/chat.postMessage", "POST", data);
        string responseInString = Encoding.UTF8.GetString(response);
        Console.WriteLine(responseInString);

我创建另一个附件变量sampleAttachment2并 序列化它:

var attachmentsJson2 = JsonConvert.SerializeObject(sampleAttachment2);

但是我不知道将两个附件都添加到

的正确语法
data["attachments"] object 

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

sampleAttachment是SlackAttachment对象的数组。 要添加更多附件,只需向该数组添加更多SlackAttachment对象。

示例:

var sampleAttachment = new SlackAttachment[]
{
    new SlackAttachment {
            fallback = "",
            text = "1st attachment"
    },
    new SlackAttachment {
            fallback = "",
            text = "2nd attachment",
    }
};

API参数附件的正确语法是附件数组作为JSON字符串的数组。