Search code examples
c#imagepostslackslack-api

How to post Slack formated message with local attachment?


Basically I want to post local image files into slack. The method only accepts URL parameters but I want to pass the path of the file. Is there a way to achieve this using formatted message ? I had the example from this site by the way :

 public class SlackAttachment
    {
        public string fallback { get; set; }
...
        public string author_name { get; set; }
        public string image_url { get; set; }

    } 
public static void SendMessageToSlack()
        {

            string token= "myTokenHere";


            var sampleAttachment = new SlackAttachment[]

            {
                new SlackAttachment {

                    fallback = "this did not work",
                    text = "text here",
                    color = "0b7c1e",
                    pretext = "",
                    author_name = "myName",
                    author_icon =  @"https://i.imgur.com/02sddfQMt9p.png",
                    author_link = "",
                    title = "no title",
                    title_link = "Title link here",
                  //image_url = @"https://i.imgur.com/U9S0CDG.png",
                  // cannot replace this with 
                  //   C:\Users\Public\image.png

                    thumb_url = @"",
                    footer = "footer here",
                    footer_icon =  migrationIcon

                             },
        };

            var attachmentsJson = JsonConvert.SerializeObject(sampleAttachment);
            var data = new NameValueCollection();
            data["token"] = token;
            data["channel"] = channelName;
            data["as_user"] = "true";          
            data["text"] = "";
            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);
        }

Solution

  • In order to attach a local image file to a message you need to first upload it so you get a public URL. Then you can use that URL in your message attachment.

    This works with any public image service (e.g. imgur.com) and you can also use any Slack workspace as host for public image files.

    Check out this answer for details including a complete example in C#.