[Discord] A tool for anyone who needs it


#1

Hey guys,

Just for some context, My corporation lives in a wormhole, and we needed a viable way to ensure we captured any traffic through our wormhole, as well as keeping track of any cosmic signatures etc. So I have developed a bot that will do this for me. However since I had so much difficulty making the program post to discord, I figured I’d post what I had for you guys here just to help out.

The below method is what I use to post to my discord server. To use it you need to be the administrator of your discord server. Next, you should create a new webhook on that server.

Once you have assigned the webhook a username, and obtained its web address you are are ready to use the below code. (NOTE: you will have to change the username property within the Json variable to match your chosen username)

The use of the function should be self explanatory once you’ve setup the webhook and changed the username as needed.

public static async Task<bool> SendDiscord(String webhook, String message)
    {
        try
        {
            HttpClient client = new HttpClient();

            Dictionary<string, string> Json = new Dictionary<string, string>
            {
               { "username", "Cookie Monster" },
               { "avatar_url", @"http://www.good-collective.co.uk/wp-content/themes/we3/assets/images/cookie-monster.png" },
               { "content", message }
            };

            HttpContent content = new FormUrlEncodedContent(Json);

            var response = await client.PostAsync(webhook, content);
            var responseStr = await response.Content.ReadAsStringAsync();

            Console.WriteLine(responseStr);

            return true;
        }
        catch (Exception e)
        {
            Console.WriteLine("ERROR: " + e.StackTrace);
            return false;
        }
    }