Search code examples
c#slackslack-api

Implement conversations.create in C#


I am looking at Slack’s documentation on conversations.create and I’m not sure how to integrate it in C#. Do I need to import their Slack API solution into my code to use it? Any help would be great!


Solution

  • To create a channel with C# all you need to do is make a POST request to the respective API method. channels.create will work, but I recommend the newer conversations.create API method.

    There are many way how to you can make a POST request in C#. Here is an example using HttpClient, which is the preferred approach. Check out this post for alternatives.

    Here is an example:

    using System;
    using System.Net.Http;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    
    namespace SlackExamples
    {
        class CreateChannels
        {
            private static readonly HttpClient client = new HttpClient();
    
            static async Task CreateChannel()
            {
                var values = new Dictionary<string, string>
                {
                    { "token", Environment.GetEnvironmentVariable("SLACK_TOKEN") },
                    { "name", "cool-guys" }
                };
    
                var content = new FormUrlEncodedContent(values);
                var response = await client.PostAsync("https://slack.com/api/conversations.create", content);
                var responseString = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseString);
            }
    
            static void Main(string[] args)
            {
                CreateChannel().Wait();
            }
        }
    }
    
    

    Note: The token you need it kept in an environment variable for security purposes, which is good practice.