How to upload any file on Slack via Slack-App in c#

后端 未结 3 962
挽巷
挽巷 2020-12-02 02:48

I need help with uploading files to Slack.

I have a Slack-App that is working with my code(below) so far. But all I can do is post messages. I can not attach images

3条回答
  •  执笔经年
    2020-12-02 03:30

    Here is a shorter working example showing how to just upload any file to Slack with C# only. The example will also automatically share the file the given channel.

    I have included the logic to convert the API response from JSON, which will always be needed to determine if the API call was successful.

    Note: This example requires Newtonsoft.Json

    using System;
    using System.Net;
    using System.Collections.Specialized;
    using System.Text;
    using Newtonsoft.Json;
    
    public class SlackExample
    {
        // classes for converting JSON respones from API method into objects
        // note that only those properties are defind that are needed for this example
    
        // reponse from file methods
        class SlackFileResponse
        {
            public bool ok { get; set; }
            public String error { get; set; }
            public SlackFile file { get; set; }
        }
    
        // a slack file
        class SlackFile
        {
            public String id { get; set; }
            public String name { get; set; }        
        }
    
        // main method with logic
        public static void Main()
        {
            var parameters = new NameValueCollection();
    
            // put your token here
            parameters["token"] = "xoxp-YOUR-TOKEN";
            parameters["channels"] = "test";
    
            var client = new WebClient();
            client.QueryString = parameters;
            byte[] responseBytes = client.UploadFile(
                    "https://slack.com/api/files.upload",
                    "D:\\temp\\Stratios_down.jpg"
            );
    
            String responseString = Encoding.UTF8.GetString(responseBytes);
    
            SlackFileResponse fileResponse =
                JsonConvert.DeserializeObject(responseString);
        }
    }
    

    About content types: Those are part of the header of a HTTP request and can be set manually in the WebClient object (see also this answer). However, for our case you can ignore it, because the default content types that WebClient is using for the POST request will work just fine.

    Also see this answer on how to upload files with the WebClient class.

提交回复
热议问题