forked from Inumedia/SlackAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SlackClient.cs
753 lines (595 loc) · 30.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using SlackAPI.RPCMessages;
namespace SlackAPI
{
/// <summary>
/// SlackClient is intended to solely handle RPC (HTTP-based) functionality. Does not handle WebSocket connectivity.
///
/// For WebSocket connectivity, refer to <see cref="SlackAPI.SlackSocketClient"/>
/// </summary>
public class SlackClient
{
readonly string APIToken;
bool authWorks = false;
const string APIBaseLocation = "https://slack.com/api/";
const int Timeout = 5000;
const char StartHighlight = '\uE001';
const char EndHightlight = '\uE001';
static List<Tuple<string, string>> replacers = new List<Tuple<string, string>>(){
new Tuple<string,string>("&", "&"),
new Tuple<string,string>("<", "<"),
new Tuple<string,string>(">", ">")
};
//Dictionary<int, Action<ReceivingMessage>> socketCallbacks;
public Self MySelf;
public User MyData;
public Team MyTeam;
public List<string> starredChannels;
public List<User> Users;
public List<Channel> Channels;
public List<Channel> Groups;
public List<DirectMessageConversation> DirectMessages;
public Dictionary<string, User> UserLookup;
public Dictionary<string, Channel> ChannelLookup;
public Dictionary<string, Channel> GroupLookup;
public Dictionary<string, DirectMessageConversation> DirectMessageLookup;
public Dictionary<string, Conversation> ConversationLookup;
//public event Action<ReceivingMessage> OnUserTyping;
//public event Action<ReceivingMessage> OnMessageReceived;
//public event Action<ReceivingMessage> OnPresenceChanged;
//public event Action<ReceivingMessage> OnHello;
public SlackClient(string token)
{
APIToken = token;
}
public virtual void Connect(Action<LoginResponse> onConnected = null, Action onSocketConnected = null)
{
EmitLogin((loginDetails) =>
{
if( loginDetails.ok ) {
Connected( loginDetails );
onConnected?.Invoke( loginDetails );
}
});
}
protected virtual void Connected(LoginResponse loginDetails)
{
MySelf = loginDetails.self;
MyData = loginDetails.users.First((c) => c.id == MySelf.id);
MyTeam = loginDetails.team;
Users = new List<User>(loginDetails.users.Where((c) => !c.deleted));
Channels = new List<Channel>(loginDetails.channels);
Groups = new List<Channel>(loginDetails.groups);
DirectMessages = new List<DirectMessageConversation>(loginDetails.ims.Where((c) => Users.Exists((a) => a.id == c.user) && c.id != MySelf.id));
starredChannels =
Groups.Where((c) => c.is_starred).Select((c) => c.id)
.Union(
DirectMessages.Where((c) => c.is_starred).Select((c) => c.user)
).Union(
Channels.Where((c) => c.is_starred).Select((c) => c.id)
).ToList();
UserLookup = new Dictionary<string, User>();
foreach (User u in Users) UserLookup.Add(u.id, u);
ChannelLookup = new Dictionary<string, Channel>();
ConversationLookup = new Dictionary<string, Conversation>();
foreach (Channel c in Channels)
{
ChannelLookup.Add(c.id, c);
ConversationLookup.Add(c.id, c);
}
GroupLookup = new Dictionary<string, Channel>();
foreach (Channel g in Groups)
{
GroupLookup.Add(g.id, g);
ConversationLookup.Add(g.id, g);
}
DirectMessageLookup = new Dictionary<string, DirectMessageConversation>();
foreach (DirectMessageConversation im in DirectMessages)
{
DirectMessageLookup.Add(im.id, im);
ConversationLookup.Add(im.id, im);
}
}
internal static Uri GetSlackUri(string path, Tuple<string, string>[] getParameters)
{
string parameters = getParameters
.Where(x => x.Item2 != null)
.Select(new Func<Tuple<string, string>, string>(a =>
{
try
{
return string.Format("{0}={1}", Uri.EscapeDataString(a.Item1), Uri.EscapeDataString(a.Item2));
}
catch (Exception ex)
{
throw new InvalidOperationException(string.Format("Failed when processing '{0}'.", a), ex);
}
}))
.Aggregate((a, b) =>
{
if (string.IsNullOrEmpty(a))
return b;
else
return string.Format("{0}&{1}", a, b);
});
Uri requestUri = new Uri(string.Format("{0}?{1}", path, parameters));
return requestUri;
}
public static void APIRequest<K>(Action<K> callback, Tuple<string, string>[] getParameters, Tuple<string, string>[] postParameters)
where K : Response
{
RequestPath path = RequestPath.GetRequestPath<K>();
//TODO: Custom paths? Appropriate subdomain paths? Not sure.
//Maybe store custom path in the requestpath.path itself?
Uri requestUri = GetSlackUri(Path.Combine(APIBaseLocation, path.Path), getParameters);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUri);
//This will handle all of the processing.
RequestState<K> state = new RequestState<K>(request, postParameters, callback);
state.Begin();
}
public static void APIGetRequest<K>(Action<K> callback, params Tuple<string, string>[] getParameters)
where K : Response
{
APIRequest<K>(callback, getParameters, new Tuple<string, string>[0]);
}
public void APIRequestWithToken<K>(Action<K> callback, params Tuple<string,string>[] getParameters)
where K : Response
{
Tuple<string, string>[] tokenArray = new Tuple<string, string>[]{
new Tuple<string,string>("token", APIToken)
};
if (getParameters != null && getParameters.Length > 0)
tokenArray = tokenArray.Concat(getParameters).ToArray();
APIRequest(callback, tokenArray, new Tuple<string, string>[0]);
}
[Obsolete("Please use the OAuth method for authenticating users")]
public static void StartAuth(Action<AuthStartResponse> callback, string email)
{
APIRequest(callback, new Tuple<string, string>[] { new Tuple<string, string>("email", email) }, new Tuple<string, string>[0]);
}
public static void FindTeam(Action<FindTeamResponse> callback, string team)
{
//This seems to accept both 'team.slack.com' and just plain 'team'.
//Going to go with the latter.
Tuple<string, string> domainName = new Tuple<string, string>("domain", team);
APIRequest(callback, new Tuple<string, string>[] { domainName }, new Tuple<string, string>[0]);
}
public static void AuthSignin(Action<AuthSigninResponse> callback, string userId, string teamId, string password)
{
APIRequest(callback, new Tuple<string, string>[] {
new Tuple<string,string>("user", userId),
new Tuple<string,string>("team", teamId),
new Tuple<string,string>("password", password)
}, new Tuple<string, string>[0]);
}
public void TestAuth(Action<AuthTestResponse> callback)
{
APIRequestWithToken(callback);
}
public void GetUserList(Action<UserListResponse> callback)
{
APIRequestWithToken(callback);
}
public void ChannelsCreate(Action<ChannelCreateResponse> callback, string name) {
APIRequestWithToken(callback, new Tuple<string, string>("name", name));
}
public void GetChannelList(Action<ChannelListResponse> callback, bool ExcludeArchived = true)
{
APIRequestWithToken(callback, new Tuple<string, string>("exclude_archived", ExcludeArchived ? "1" : "0"));
}
public void GetGroupsList(Action<GroupListResponse> callback, bool ExcludeArchived = true)
{
APIRequestWithToken(callback, new Tuple<string, string>("exclude_archived", ExcludeArchived ? "1" : "0"));
}
public void GetDirectMessageList(Action<DirectMessageConversationListResponse> callback)
{
APIRequestWithToken(callback);
}
public void GetFiles(Action<FileListResponse> callback, string userId = null, DateTime? from = null, DateTime? to = null, int? count = null, int? page = null, FileTypes types = FileTypes.all)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
if (!string.IsNullOrEmpty(userId))
parameters.Add(new Tuple<string,string>("user", userId));
if (from.HasValue)
parameters.Add(new Tuple<string, string>("ts_from", from.Value.ToProperTimeStamp()));
if (to.HasValue)
parameters.Add(new Tuple<string, string>("ts_to", to.Value.ToProperTimeStamp()));
if (!types.HasFlag(FileTypes.all))
{
FileTypes[] values = (FileTypes[])Enum.GetValues(typeof(FileTypes));
StringBuilder building = new StringBuilder();
bool first = true;
for (int i = 0; i < values.Length; ++i)
{
if (types.HasFlag(values[i]))
{
if (!first) building.Append(",");
building.Append(values[i].ToString());
first = false;
}
}
if (building.Length > 0)
parameters.Add(new Tuple<string, string>("types", building.ToString()));
}
if (count.HasValue)
parameters.Add(new Tuple<string, string>("count", count.Value.ToString()));
if (page.HasValue)
parameters.Add(new Tuple<string, string>("page", page.Value.ToString()));
APIRequestWithToken(callback, parameters.ToArray());
}
void GetHistory<K>(Action<K> historyCallback, string channel, DateTime? latest = null, DateTime? oldest = null, int? count = null)
where K : MessageHistory
{
List<Tuple<string,string>> parameters = new List<Tuple<string,string>>();
parameters.Add(new Tuple<string, string>("channel", channel));
if(latest.HasValue)
parameters.Add(new Tuple<string, string>("latest", latest.Value.ToProperTimeStamp()));
if(oldest.HasValue)
parameters.Add(new Tuple<string, string>("oldest", oldest.Value.ToProperTimeStamp()));
if(count.HasValue)
parameters.Add(new Tuple<string,string>("count", count.Value.ToString()));
APIRequestWithToken(historyCallback, parameters.ToArray());
}
public void GetChannelHistory(Action<ChannelMessageHistory> callback, Channel channelInfo, DateTime? latest = null, DateTime? oldest = null, int? count = null)
{
GetHistory(callback, channelInfo.id, latest, oldest, count);
}
public void GetDirectMessageHistory(Action<MessageHistory> callback, DirectMessageConversation conversationInfo, DateTime? latest = null, DateTime? oldest = null, int? count = null)
{
GetHistory(callback, conversationInfo.id, latest, oldest, count);
}
public void GetGroupHistory(Action<GroupMessageHistory> callback, Channel groupInfo, DateTime? latest = null, DateTime? oldest = null, int? count = null)
{
GetHistory(callback, groupInfo.id, latest, oldest, count);
}
public void MarkChannel(Action<MarkResponse> callback, string channelId, DateTime ts)
{
APIRequestWithToken(callback,
new Tuple<string, string>("channel", channelId),
new Tuple<string, string>("ts", ts.ToProperTimeStamp())
);
}
public void GetFileInfo(Action<FileInfoResponse> callback, string fileId, int? page = null, int? count = null)
{
List<Tuple<string,string>> parameters = new List<Tuple<string,string>>();
parameters.Add(new Tuple<string,string>("file", fileId));
if(count.HasValue)
parameters.Add(new Tuple<string,string>("count", count.Value.ToString()));
if (page.HasValue)
parameters.Add(new Tuple<string, string>("page", page.Value.ToString()));
APIRequestWithToken(callback, parameters.ToArray());
}
#region Groups
public void GroupsArchive(Action<GroupArchiveResponse> callback, string channelId)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId));
}
public void GroupsClose(Action<GroupCloseResponse> callback, string channelId)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId));
}
public void GroupsCreate(Action<GroupCreateResponse> callback, string name)
{
APIRequestWithToken(callback, new Tuple<string, string>("name", name));
}
public void GroupsCreateChild(Action<GroupCreateChildResponse> callback, string channelId)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId));
}
public void GroupsInvite(Action<GroupInviteResponse> callback, string userId, string channelId)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("user", userId));
APIRequestWithToken(callback, parameters.ToArray());
}
public void GroupsKick(Action<GroupKickResponse> callback, string userId, string channelId)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("user", userId));
APIRequestWithToken(callback, parameters.ToArray());
}
public void GroupsLeave(Action<GroupLeaveResponse> callback, string channelId)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId));
}
public void GroupsMark(Action<GroupMarkResponse> callback, string channelId, DateTime ts)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId), new Tuple<string, string>("ts", ts.ToProperTimeStamp()));
}
public void GroupsOpen(Action<GroupOpenResponse> callback, string channelId)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId));
}
public void GroupsRename(Action<GroupRenameResponse> callback, string channelId, string name)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("name", name));
APIRequestWithToken(callback, parameters.ToArray());
}
public void GroupsSetPurpose(Action<GroupSetPurposeResponse> callback, string channelId, string purpose)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("purpose", purpose));
APIRequestWithToken(callback, parameters.ToArray());
}
public void GroupsSetTopic(Action<GroupSetPurposeResponse> callback, string channelId, string topic)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("topic", topic));
APIRequestWithToken(callback, parameters.ToArray());
}
public void GroupsUnarchive(Action<GroupUnarchiveResponse> callback, string channelId)
{
APIRequestWithToken(callback, new Tuple<string, string>("channel", channelId));
}
#endregion
public void SearchAll(Action<SearchResponseAll> callback, string query, SearchSort? sorting = null, SearchSortDirection? direction = null, bool enableHighlights = false, int? count = null, int? page = null)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("query", query));
if (sorting.HasValue)
parameters.Add(new Tuple<string, string>("sort", sorting.Value.ToString()));
if (direction.HasValue)
parameters.Add(new Tuple<string, string>("sort_dir", direction.Value.ToString()));
if (enableHighlights)
parameters.Add(new Tuple<string, string>("highlight", "1"));
if (count.HasValue)
parameters.Add(new Tuple<string, string>("count", count.Value.ToString()));
if (page.HasValue)
parameters.Add(new Tuple<string, string>("page", page.Value.ToString()));
APIRequestWithToken(callback, parameters.ToArray());
}
public void SearchMessages(Action<SearchResponseMessages> callback, string query, SearchSort? sorting = null, SearchSortDirection? direction = null, bool enableHighlights = false, int? count = null, int? page = null)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("query", query));
if (sorting.HasValue)
parameters.Add(new Tuple<string, string>("sort", sorting.Value.ToString()));
if (direction.HasValue)
parameters.Add(new Tuple<string, string>("sort_dir", direction.Value.ToString()));
if (enableHighlights)
parameters.Add(new Tuple<string, string>("highlight", "1"));
if (count.HasValue)
parameters.Add(new Tuple<string, string>("count", count.Value.ToString()));
if (page.HasValue)
parameters.Add(new Tuple<string, string>("page", page.Value.ToString()));
APIRequestWithToken(callback, parameters.ToArray());
}
public void SearchFiles(Action<SearchResponseFiles> callback, string query, SearchSort? sorting = null, SearchSortDirection? direction = null, bool enableHighlights = false, int? count = null, int? page = null)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("query", query));
if (sorting.HasValue)
parameters.Add(new Tuple<string, string>("sort", sorting.Value.ToString()));
if (direction.HasValue)
parameters.Add(new Tuple<string, string>("sort_dir", direction.Value.ToString()));
if (enableHighlights)
parameters.Add(new Tuple<string, string>("highlight", "1"));
if (count.HasValue)
parameters.Add(new Tuple<string, string>("count", count.Value.ToString()));
if (page.HasValue)
parameters.Add(new Tuple<string, string>("page", page.Value.ToString()));
APIRequestWithToken(callback, parameters.ToArray());
}
public void GetStars(Action<StarListResponse> callback, string userId = null, int? count = null, int? page = null){
List<Tuple<string,string>> parameters = new List<Tuple<string,string>>();
if(!string.IsNullOrEmpty(userId))
parameters.Add(new Tuple<string,string>("user", userId));
if(count.HasValue)
parameters.Add(new Tuple<string,string>("count", count.Value.ToString()));
if(page.HasValue)
parameters.Add(new Tuple<string,string>("page", page.Value.ToString()));
APIRequestWithToken(callback, parameters.ToArray());
}
public void DeleteMessage(Action<DeletedResponse> callback, string channelId, DateTime ts)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>()
{
new Tuple<string,string>("ts", ts.ToProperTimeStamp()),
new Tuple<string,string>("channel", channelId)
};
APIRequestWithToken(callback, parameters.ToArray());
}
public void EmitPresence(Action<PresenceResponse> callback, Presence status)
{
APIRequestWithToken(callback, new Tuple<string, string>("presence", status.ToString()));
}
public void GetPreferences(Action<UserPreferencesResponse> callback)
{
APIRequestWithToken(callback);
}
#region Users
public void GetCounts(Action<UserCountsResponse> callback)
{
APIRequestWithToken(callback);
}
public void GetPresence(Action<UserGetPresenceResponse> callback, string user)
{
APIRequestWithToken(callback, new Tuple<string, string>("user", user));
}
public void GetInfo(Action<UserInfoResponse> callback, string user)
{
APIRequestWithToken(callback, new Tuple<string, string>("user", user));
}
#endregion
public void EmitLogin(Action<LoginResponse> callback, string agent = "Inumedia.SlackAPI")
{
APIRequestWithToken(callback, new Tuple<string, string>("agent", agent));
}
public void Update(
Action<UpdateResponse> callback,
string ts,
string channelId,
string text,
string botName = null,
string parse = null,
bool linkNames = false,
Attachment[] attachments = null,
bool as_user = false)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
parameters.Add(new Tuple<string, string>("ts", ts));
parameters.Add(new Tuple<string, string>("channel", channelId));
parameters.Add(new Tuple<string, string>("text", text));
if (!string.IsNullOrEmpty(botName))
parameters.Add(new Tuple<string, string>("username", botName));
if (!string.IsNullOrEmpty(parse))
parameters.Add(new Tuple<string, string>("parse", parse));
if (linkNames)
parameters.Add(new Tuple<string, string>("link_names", "1"));
if (attachments != null && attachments.Length > 0)
parameters.Add(new Tuple<string, string>("attachments", JsonConvert.SerializeObject(attachments)));
parameters.Add(new Tuple<string, string>("as_user", as_user.ToString()));
APIRequestWithToken(callback, parameters.ToArray());
}
public void JoinDirectMessageChannel(Action<JoinDirectMessageChannelResponse> callback, string user)
{
var param = new Tuple<string, string>("user", user);
APIRequestWithToken(callback, param);
}
public void PostMessage(
Action<PostMessageResponse> callback,
string channelId,
string text,
string botName = null,
string parse = null,
bool linkNames = false,
Attachment[] attachments = null,
bool unfurl_links = false,
string icon_url = null,
string icon_emoji = null,
bool as_user = false)
{
List<Tuple<string,string>> parameters = new List<Tuple<string,string>>();
parameters.Add(new Tuple<string,string>("channel", channelId));
parameters.Add(new Tuple<string,string>("text", text));
if(!string.IsNullOrEmpty(botName))
parameters.Add(new Tuple<string,string>("username", botName));
if (!string.IsNullOrEmpty(parse))
parameters.Add(new Tuple<string, string>("parse", parse));
if (linkNames)
parameters.Add(new Tuple<string, string>("link_names", "1"));
if (attachments != null && attachments.Length > 0)
parameters.Add(new Tuple<string, string>("attachments",
JsonConvert.SerializeObject(attachments, Formatting.None,
new JsonSerializerSettings // Shouldn't include a not set property
{
NullValueHandling = NullValueHandling.Ignore
})));
if (unfurl_links)
parameters.Add(new Tuple<string, string>("unfurl_links", "1"));
if (!string.IsNullOrEmpty(icon_url))
parameters.Add(new Tuple<string, string>("icon_url", icon_url));
if (!string.IsNullOrEmpty(icon_emoji))
parameters.Add(new Tuple<string, string>("icon_emoji", icon_emoji));
parameters.Add(new Tuple<string, string>("as_user", as_user.ToString()));
APIRequestWithToken(callback, parameters.ToArray());
}
public void AddReaction(
Action<ReactionAddedResponse> callback,
string name = null,
string channel = null,
string timestamp = null)
{
List<Tuple<string, string>> parameters = new List<Tuple<string, string>>();
if (!string.IsNullOrEmpty(name))
parameters.Add(new Tuple<string, string>("name", name));
if (!string.IsNullOrEmpty(channel))
parameters.Add(new Tuple<string, string>("channel", channel));
if (!string.IsNullOrEmpty(timestamp))
parameters.Add(new Tuple<string, string>("timestamp", timestamp));
APIRequestWithToken(callback, parameters.ToArray());
}
public void UploadFile(Action<FileUploadResponse> callback, byte[] fileData, string fileName, string[] channelIds, string title = null, string initialComment = null, bool useAsync = false, string fileType = null)
{
Uri target = new Uri(Path.Combine(APIBaseLocation, useAsync ? "files.uploadAsync" : "files.upload"));
List<string> parameters = new List<string>();
parameters.Add(string.Format("token={0}", APIToken));
//File/Content
if (!string.IsNullOrEmpty(fileType))
parameters.Add(string.Format("{0}={1}", "filetype", fileType));
if (!string.IsNullOrEmpty(fileName))
parameters.Add(string.Format("{0}={1}", "filename", fileName));
if (!string.IsNullOrEmpty(title))
parameters.Add(string.Format("{0}={1}", "title", title));
if (!string.IsNullOrEmpty(initialComment))
parameters.Add(string.Format("{0}={1}", "initial_comment", initialComment));
parameters.Add(string.Format("{0}={1}", "channels", string.Join(",", channelIds)));
using(HttpClient client = new HttpClient())
using (MultipartFormDataContent form = new MultipartFormDataContent())
{
form.Add(new ByteArrayContent(fileData), "file", fileName);
HttpResponseMessage response = client.PostAsync(string.Format("{0}?{1}", target, string.Join("&", parameters.ToArray())), form).Result;
string result = response.Content.ReadAsStringAsync().Result;
callback(result.Deserialize<FileUploadResponse>());
}
}
private static string BuildScope(SlackScope scope)
{
var builder = new StringBuilder();
if ((int)(scope & SlackScope.Identify) != 0)
builder.Append("identify");
if ((int)(scope & SlackScope.Read) != 0)
{
if(builder.Length > 0)
builder.Append(",");
builder.Append("read");
}
if ((int)(scope & SlackScope.Post) != 0)
{
if(builder.Length > 0)
builder.Append(",");
builder.Append("post");
}
if ((int)(scope & SlackScope.Client) != 0)
{
if(builder.Length > 0)
builder.Append(",");
builder.Append("client");
}
if ((int)(scope & SlackScope.Admin) != 0)
{
if(builder.Length > 0)
builder.Append(",");
builder.Append("admin");
}
return builder.ToString();
}
public static Uri GetAuthorizeUri(string clientId, SlackScope scopes, string redirectUri = null, string state = null, string team = null)
{
string theScopes = BuildScope(scopes);
return GetSlackUri("https://slack.com/oauth/authorize", new Tuple<string, string>[] { new Tuple<string, string>("client_id", clientId),
new Tuple<string, string>("redirect_uri", redirectUri),
new Tuple<string, string>("state", state),
new Tuple<string, string>("scope", theScopes),
new Tuple<string, string>("team", team)});
}
public static void GetAccessToken(Action<AccessTokenResponse> callback, string clientId, string clientSecret, string redirectUri, string code)
{
APIRequest<AccessTokenResponse>(callback, new Tuple<string, string>[] { new Tuple<string, string>("client_id", clientId),
new Tuple<string, string>("client_secret", clientSecret), new Tuple<string, string>("code", code),
new Tuple<string, string>("redirect_uri", redirectUri) }, new Tuple<string, string>[] {});
}
public static void RegisterConverter(JsonConverter converter)
{
if (converter == null)
{
throw new ArgumentNullException("converter");
}
Extensions.Converters.Add(converter);
}
}
}