-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSlackClient.cs
47 lines (40 loc) · 1.6 KB
/
SlackClient.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace SlackWebApiMessageClient
{
public class SlackClient
{
public SlackClient(string token, HttpClientHandler handler = null)
{
Token = token;
HttpClient = handler == null ? new HttpClient() : new HttpClient(handler);
}
private string Token { get; set; }
private HttpClient HttpClient { get; set; }
public Task<HttpResponseMessage> SendMessageAsync(Message message)
{
if (message == null)
{
return null;
}
var formUrlEncodedContent = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("token", Token)
};
// Serialize to json so that only the assigned values get serialized.
// We do not want any unassigned value being sent to Slack.
// Deserialize into a dictionary and add each value to the form.
// NOTE: This may just be me not knowing how to do this better.
var json = JsonConvert.SerializeObject(message);
var messageDictionary = JObject.Parse(json);
foreach (var entry in messageDictionary)
{
formUrlEncodedContent.Add(new KeyValuePair<string, string>(entry.Key, entry.Value.ToString()));
}
return HttpClient.PostAsync("https://slack.com/api/chat.postMessage", new FormUrlEncodedContent(formUrlEncodedContent));
}
}
}