forked from soxtoby/SlackNet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SlackBot.cs
687 lines (577 loc) · 26.7 KB
/
SlackBot.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
using SlackNet.Events;
using SlackNet.WebApi;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using System.Threading;
using System.Threading.Tasks;
namespace SlackNet.Bot
{
public interface ISlackBot : IObserver<BotMessage>
{
/// <summary>
/// Id of the bot user.
/// </summary>
string Id { get; }
/// <summary>
/// Name of the bot user.
/// </summary>
string Name { get; }
/// <summary>
/// Stream of new messages received from Slack.
/// </summary>
IObservable<IMessage> Messages { get; }
/// <summary>
/// Connect to Slack.
/// </summary>
Task Connect(CancellationToken? cancellationToken = null);
/// <summary>
/// Transform stream of incoming messages.
/// </summary>
void AddIncomingMiddleware(Func<IObservable<IMessage>, IObservable<IMessage>> middleware);
/// <summary>
/// Transform stream of outgoing messages.
/// </summary>
void AddOutgoingMiddleware(Func<IObservable<BotMessage>, IObservable<BotMessage>> middleware);
/// <summary>
/// Add a handler object for handling new messages received from Slack.
/// </summary>
void AddHandler(IMessageHandler handler);
/// <summary>
/// Fired when a new message is received from Slack.
/// </summary>
event EventHandler<IMessage> OnMessage;
/// <summary>
/// Get full list conversations the bot user has access to.
/// </summary>
Task<IReadOnlyCollection<Conversation>> GetConversations();
/// <summary>
/// Retrieve information about a conversation.
/// </summary>
Task<Conversation> GetConversationById(string conversationId);
/// <summary>
/// Find conversation with matching name.
/// </summary>
/// <param name="conversationName">Channel, group or IM name, with leading # or @ symbol as appropriate.</param>
Task<Conversation> GetConversationByName(string conversationName);
/// <summary>
/// Get and open Im by user ID.
/// </summary>
Task<Conversation> GetConversationByUserId(string userId);
/// <summary>
/// Get user information.
/// </summary>
Task<User> GetUserById(string userId);
/// <summary>
/// Get bot user information.
/// </summary>
Task<BotInfo> GetBotUserById(string botId);
/// <summary>
/// Find user by username, with or without leading @.
/// </summary>
Task<User> GetUserByName(string username);
/// <summary>
/// Get full list of users.
/// </summary>
Task<IReadOnlyList<User>> GetUsers();
/// <summary>
/// Send a message to Slack as the bot.
/// </summary>
Task Send(BotMessage message, CancellationToken? cancellationToken = null);
/// <summary>
/// Show typing indicator in Slack while performing some action.
/// </summary>
Task WhileTyping(string channelId, Func<Task> action);
/// <summary>
/// Clear bot's cache of hubs, users etc.
/// </summary>
void ClearCache();
#region Hubs
/// <summary>
/// Get information on a public or private channel, IM, or multi-person IM.
/// </summary>
[Obsolete("Use GetConversationById instead")]
Task<Hub> GetHubById(string hubId);
/// <summary>
/// Find hub with matching name.
/// </summary>
/// <param name="channel">Channel, group or IM name, with leading # or @ symbol as appropriate.</param>
[Obsolete("Use GetConversationByName instead")]
Task<Hub> GetHubByName(string channel);
/// <summary>
/// Find channel by name, with or without leading #.
/// </summary>
[Obsolete("Use GetConversationByName instead")]
Task<Hub> GetChannelByName(string name);
/// <summary>
/// Find private group by name.
/// </summary>
[Obsolete("Use GetConversationByName instead")]
Task<Hub> GetGroupByName(string name);
/// <summary>
/// Find user by name, with or without leading @.
/// </summary>
[Obsolete("Use GetConversationByName instead")]
Task<Im> GetImByName(string username);
/// <summary>
/// Get and open Im by user ID.
/// </summary>
[Obsolete("Use GetConversationByUserId instead")]
Task<Im> GetImByUserId(string userId);
/// <summary>
/// Get full list of public channels.
/// </summary>
[Obsolete("Use GetConversations instead")]
Task<IReadOnlyList<Channel>> GetChannels();
/// <summary>
/// Get list of private groups that the bot is in.
/// </summary>
[Obsolete("Use GetConversations instead")]
Task<IReadOnlyList<Channel>> GetGroups();
/// <summary>
/// Get list of multi-person IMs that the bot is in.
/// </summary>
[Obsolete("Use GetConversations instead")]
Task<IReadOnlyList<Channel>> GetMpIms();
/// <summary>
/// Get list of IMs that have been opened with the bot.
/// </summary>
[Obsolete("Use GetConversations instead")]
Task<IReadOnlyList<Im>> GetIms();
#endregion
}
public class SlackBot : ISlackBot, IDisposable
{
private readonly ISlackRtmClient _rtm;
private readonly ISlackApiClient _api;
private readonly IScheduler _scheduler;
private readonly ConcurrentQueue<IMessageHandler> _handlers = new();
private readonly ConcurrentValue<Task> _conversationsFetched = new();
private readonly ConcurrentDictionary<string, Task<Conversation>> _conversations = new();
private readonly ConcurrentDictionary<string, Task<User>> _users = new();
private readonly ConcurrentDictionary<string, Task<BotInfo>> _bots = new();
private readonly ConcurrentValue<Task<IReadOnlyList<User>>> _allUsers = new();
private readonly SyncedSubject<IMessage> _incomingMessages = new();
private readonly SyncedSubject<BotMessage> _outgoingMessages = new();
private IObservable<PostedMessage> _sentMessages;
private IObservable<IMessage> _incomingWithMiddlewareApplied;
private IObservable<BotMessage> _outgoingWithMiddlewareApplied;
private IDisposable _outgoingSubscription;
private IDisposable _incomingSubscription;
public SlackBot(string token) : this(new SlackRtmClient(token), new SlackApiClient(token)) { }
public SlackBot(ISlackRtmClient rtmClient, ISlackApiClient apiClient, IScheduler scheduler = null)
{
_rtm = rtmClient;
_api = apiClient;
_scheduler = scheduler ?? Scheduler.Default;
_incomingWithMiddlewareApplied = _rtm.Messages
.Where(m => m.GetType() == typeof(MessageEvent) || m.GetType() == typeof(Events.BotMessage))
.Where(m => m.User != Id)
.SelectMany(CreateSlackMessage);
_outgoingWithMiddlewareApplied = _outgoingMessages
.LimitFrequency(TimeSpan.FromSeconds(1), m => m.CancellationToken ?? CancellationToken.None, _scheduler);
}
/// <summary>
/// Id of the bot user.
/// </summary>
public string Id { get; private set; }
/// <summary>
/// Name of the bot user.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Connect to Slack.
/// </summary>
public async Task Connect(CancellationToken? cancellationToken = null)
{
// If already connected, client will throw
var connection = _rtm.Connect(cancellationToken: cancellationToken);
_incomingSubscription = _incomingWithMiddlewareApplied
.Subscribe(HandleMessage);
_sentMessages = _outgoingWithMiddlewareApplied
.Select(m => new PostedMessage { Message = m, Post = PostMessage(m) })
.Retry()
.Publish()
.RefCount();
_outgoingSubscription = _sentMessages.Subscribe();
var connectResponse = await connection.ConfigureAwait(false);
Id = connectResponse.Self.Id;
Name = connectResponse.Self.Name;
}
/// <summary>
/// Transform stream of incoming messages.
/// </summary>
public void AddIncomingMiddleware(Func<IObservable<IMessage>, IObservable<IMessage>> middleware)
{
if (_rtm.Connected)
throw new InvalidOperationException("Can't add more middleware after bot is connected.");
_incomingWithMiddlewareApplied = middleware(_incomingWithMiddlewareApplied);
}
/// <summary>
/// Transform stream of outgoing messages.
/// </summary>
public void AddOutgoingMiddleware(Func<IObservable<BotMessage>, IObservable<BotMessage>> middleware)
{
if (_rtm.Connected)
throw new InvalidOperationException("Can't add more middleware after bot is connected.");
_outgoingWithMiddlewareApplied = middleware(_outgoingWithMiddlewareApplied);
}
/// <summary>
/// Add a handler object for handling new messages received from Slack.
/// </summary>
public void AddHandler(IMessageHandler handler) => _handlers.Enqueue(handler);
/// <summary>
/// Fired when a new message is received from Slack.
/// </summary>
public event EventHandler<IMessage> OnMessage;
/// <summary>
/// Stream of new messages received from Slack.
/// </summary>
public IObservable<IMessage> Messages => _incomingMessages.AsObservable();
private async Task<SlackMessage> CreateSlackMessage(MessageEvent message)
{
var user = GetMessageUser(message);
var conversation = GetConversationById(message.Channel);
var hub = GetHubById(message.Channel);
return new SlackMessage(this)
{
Ts = message.Ts,
ThreadTs = message.ThreadTs,
Text = message.Text,
User = await user.ConfigureAwait(false),
Conversation = await conversation.ConfigureAwait(false),
Hub = await hub.ConfigureAwait(false),
Attachments = message.Attachments,
Files = message.Files,
Blocks = message.Blocks
};
}
private async Task<User> GetMessageUser(MessageEvent message)
{
var userId = message.User;
if (userId == null && message is Events.BotMessage b)
{
var botInfo = await GetBotUserById(b.BotId).ConfigureAwait(false);
userId = botInfo.UserId;
}
return await GetUserById(userId).ConfigureAwait(false);
}
private void HandleMessage(IMessage message)
{
OnMessage?.Invoke(this, message);
_handlers
.ToList()
.ForEach(h => h.HandleMessage(message));
_incomingMessages.OnNext(message);
}
/// <summary>
/// Retrieve information about a conversation.
/// </summary>
public async Task<Conversation> GetConversationById(string conversationId) =>
string.IsNullOrEmpty(conversationId)
? null
: await _conversations.GetOrAdd(conversationId, FetchConversation).ConfigureAwait(false);
private async Task<Conversation> FetchConversation(string conversationId) =>
await _api.Conversations.Info(conversationId).NullIfNotFound().ConfigureAwait(false);
/// <summary>
/// Find conversation with matching name.
/// </summary>
/// <param name="conversationName">Channel, group or IM name, with leading # or @ symbol or without.</param>
public async Task<Conversation> GetConversationByName(string conversationName) =>
conversationName.FirstOrDefault() == '@'
? await GetConversationByUserId((await GetUserByName(conversationName).ConfigureAwait(false)).Id).ConfigureAwait(false)
: await FindConversation(c => c.Name == conversationName.TrimStart('#')).ConfigureAwait(false);
/// <summary>
/// Get and open Im by user ID.
/// </summary>
public async Task<Conversation> GetConversationByUserId(string userId) =>
userId == null ? null
: await FindConversation(c => c.IsIm && c.User == userId).ConfigureAwait(false)
?? await OpenAndCacheImConversation(userId).ConfigureAwait(false);
private async Task<Conversation> OpenAndCacheImConversation(string userId)
{
var channel = await OpenImConversation(userId).ConfigureAwait(false);
if (channel != null)
_conversations[channel.Id] = Task.FromResult(channel);
return channel;
}
private async Task<Conversation> FindConversation(Func<Conversation, bool> predicate) =>
(await GetConversations().ConfigureAwait(false)).FirstOrDefault(predicate);
private async Task<Conversation> OpenImConversation(string userId) =>
(await _api.Conversations.OpenAndReturnInfo(new[] { userId }).NullIfNotFound().ConfigureAwait(false))?.Channel;
/// <summary>
/// Get full list conversations the bot user has access to.
/// </summary>
public async Task<IReadOnlyCollection<Conversation>> GetConversations()
{
await _conversationsFetched.GetOrCreateValue(FetchConversations).ConfigureAwait(false);
return (await _conversations.Values
.ToObservable()
.SelectMany(c => c)
.ToList()
.ToTask().ConfigureAwait(false))
.ToList();
}
private async Task FetchConversations()
{
string cursor = null;
do
{
var response = await _api.Conversations.List(
cursor: cursor,
types: new[]
{
ConversationType.PublicChannel,
ConversationType.PrivateChannel,
ConversationType.Im,
ConversationType.Mpim
}).ConfigureAwait(false);
foreach (var conversation in response.Channels)
_conversations[conversation.Id] = Task.FromResult(conversation);
cursor = response.ResponseMetadata.NextCursor;
} while (!string.IsNullOrEmpty(cursor));
}
/// <summary>
/// Get user information.
/// </summary>
public async Task<User> GetUserById(string userId) =>
string.IsNullOrEmpty(userId)
? null
: await _users.GetOrAdd(userId, _ => _api.Users.Info(userId).NullIfNotFound()).ConfigureAwait(false);
/// <summary>
/// Get bot user information.
/// </summary>
public async Task<BotInfo> GetBotUserById(string botId) =>
string.IsNullOrEmpty(botId)
? null
: await _bots.GetOrAdd(botId, _ => _api.Bots.Info(botId).NullIfNotFound()).ConfigureAwait(false);
/// <summary>
/// Find user by username, with or without leading @.
/// </summary>
public async Task<User> GetUserByName(string username) =>
await _users.Values.FirstOrDefaultAsync(u => u.Name == WithoutLeadingAt(username)).ConfigureAwait(false)
?? (await GetUsers().ConfigureAwait(false)).FirstOrDefault(u => u.Name == WithoutLeadingAt(username));
private static string WithoutLeadingAt(string name) => name.TrimStart('@');
/// <summary>
/// Get full list of users.
/// </summary>
public Task<IReadOnlyList<User>> GetUsers() => _allUsers.GetOrCreateValue(FetchUsers);
private async Task<IReadOnlyList<User>> FetchUsers()
{
var users = new List<User>();
string cursor = null;
do
{
var response = await _api.Users.List(cursor).ConfigureAwait(false);
users.AddRange(response.Members);
foreach (var user in response.Members)
_users[user.Id] = Task.FromResult(user);
cursor = response.ResponseMetadata.NextCursor;
} while (!string.IsNullOrEmpty(cursor));
return users;
}
/// <summary>
/// Send a message to Slack as the bot.
/// </summary>
public async Task Send(BotMessage message, CancellationToken? cancellationToken = null)
{
var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(
message.CancellationToken ?? CancellationToken.None,
cancellationToken ?? CancellationToken.None);
message.CancellationToken = linkedTokenSource.Token;
var sent = _sentMessages.FirstOrDefaultAsync(m => m.Message == message)
.SelectMany(m => m.Post)
.ToTask(linkedTokenSource.Token);
_outgoingMessages.OnNext(message);
await sent.ConfigureAwait(false);
}
private async Task<PostMessageResponse> PostMessage(BotMessage message)
{
if (message.Ephemeral && message.ReplyTo?.User?.Id == null)
throw new ArgumentException("Can't send ephemeral message: missing reply-to user ID", nameof(message));
var slackMessage = new Message
{
Channel = message.Conversation != null
? await message.Conversation.ConversationId(this).ConfigureAwait(false)
: message.ReplyTo?.Conversation?.Id,
Text = message.Text,
Attachments = message.Attachments,
Blocks = message.Blocks,
ThreadTs = await ReplyingInDifferentHub(message).ConfigureAwait(false)
? null
: message.ReplyTo?.ThreadTs
?? (message.CreateThread ? message.ReplyTo?.Ts : null),
ReplyBroadcast = message.ReplyBroadcast,
Parse = message.Parse,
LinkNames = message.LinkNames,
UnfurlLinks = message.UnfurlLinks,
UnfurlMedia = message.UnfurlMedia,
AsUser = true
};
return message.Ephemeral
? await _api.Chat.PostEphemeral(message.ReplyTo.User.Id, slackMessage, message.CancellationToken).ConfigureAwait(false)
: await _api.Chat.PostMessage(slackMessage, message.CancellationToken).ConfigureAwait(false);
}
private async Task<bool> ReplyingInDifferentHub(BotMessage message) =>
message.Conversation != null
&& await message.Conversation.ConversationId(this).ConfigureAwait(false) != message.ReplyTo?.Conversation.Id;
/// <summary>
/// Show typing indicator in Slack while performing some action.
/// </summary>
public async Task WhileTyping(string channelId, Func<Task> action)
{
using (Observable.Interval(TimeSpan.FromSeconds(4), _scheduler).Subscribe(_ => _rtm.SendTyping(channelId)))
await action().ConfigureAwait(false);
}
/// <summary>
/// Clear bot's cache of hubs, users etc.
/// </summary>
public void ClearCache()
{
_conversationsFetched.Clear();
_conversations.Clear();
_users.Clear();
_allUsers.Clear();
_hubs.Clear();
_channels.Clear();
_groups.Clear();
_mpims.Clear();
_ims.Clear();
}
public void OnCompleted() => _outgoingMessages.OnCompleted();
public void OnError(Exception error) => _outgoingMessages.OnError(error);
public void OnNext(BotMessage value) => _outgoingMessages.OnNext(value);
public void Dispose()
{
_rtm.Dispose();
_incomingMessages.Dispose();
_outgoingMessages.Dispose();
_incomingSubscription?.Dispose();
_outgoingSubscription?.Dispose();
}
#region Hubs
private readonly ConcurrentDictionary<string, Task<Hub>> _hubs = new();
private readonly ConcurrentValue<Task<IReadOnlyList<Channel>>> _channels = new();
private readonly ConcurrentValue<Task<IReadOnlyList<Channel>>> _groups = new();
private readonly ConcurrentValue<Task<IReadOnlyList<Channel>>> _mpims = new();
private readonly ConcurrentValue<Task<IReadOnlyList<Im>>> _ims = new();
/// <summary>
/// Get information on a public or private channel, IM, or multi-person IM.
/// </summary>
[Obsolete("Use GetConversationById instead")]
public async Task<Hub> GetHubById(string hubId) =>
string.IsNullOrEmpty(hubId)
? null
: await _hubs.GetOrAdd(hubId, FetchHub).ConfigureAwait(false);
private async Task<Hub> FetchHub(string hubId) =>
(await GetConversationById(hubId).ConfigureAwait(false))?.ToHub();
/// <summary>
/// Find hub with matching name.
/// </summary>
/// <param name="channel">Channel, group or IM name, with leading # or @ symbol as appropriate.</param>
[Obsolete("Use GetConversationByName instead")]
public async Task<Hub> GetHubByName(string channel) =>
channel.FirstOrDefault() == '#' ? await GetChannelByName(channel).ConfigureAwait(false)
: channel.FirstOrDefault() == '@' ? await GetImByName(channel).ConfigureAwait(false)
: await GetGroupByName(channel).ConfigureAwait(false);
/// <summary>
/// Find channel by name, with or without leading #.
/// </summary>
[Obsolete("Use GetConversationByName instead")]
public async Task<Hub> GetChannelByName(string name) =>
await FindCachedHub<Channel>(h => h.IsChannel && h.Name == WithoutLeadingHash(name)).ConfigureAwait(false)
?? (await GetChannels().ConfigureAwait(false))
.FirstOrDefault(c => c.Name == WithoutLeadingHash(name));
private static string WithoutLeadingHash(string name) => name.TrimStart('#');
/// <summary>
/// Find private group by name.
/// </summary>
[Obsolete("Use GetConversationByName instead")]
public async Task<Hub> GetGroupByName(string name) =>
await FindCachedHub<Channel>(h => h.IsGroup && h.Name == name).ConfigureAwait(false)
?? (await GetGroups().ConfigureAwait(false))
.FirstOrDefault(g => g.Name == name);
/// <summary>
/// Get an open Im by user name, with or without leading @.
/// </summary>
[Obsolete("Use GetConversationByName instead")]
public async Task<Im> GetImByName(string username) =>
await GetImByUserId(
(await GetUserByName(username).ConfigureAwait(false))?.Id).ConfigureAwait(false);
/// <summary>
/// Get and open Im by user ID.
/// </summary>
[Obsolete("Use GetConversationByUserId instead")]
public async Task<Im> GetImByUserId(string userId) =>
userId == null ? null
: await FindCachedHub<Im>(h => h.User == userId).ConfigureAwait(false)
?? await OpenAndCacheIm(userId).ConfigureAwait(false);
private Task<T> FindCachedHub<T>(Func<T, bool> predicate) where T : Hub => _hubs.Values.FirstOrDefaultAsync(predicate);
private async Task<Im> OpenAndCacheIm(string userId)
{
var im = await OpenIm(userId).ConfigureAwait(false);
if (im != null)
_hubs[im.Id] = Task.FromResult((Hub)im);
return im;
}
private async Task<Im> OpenIm(string userId) =>
(await OpenImConversation(userId).ConfigureAwait(false))?.ToIm();
/// <summary>
/// Get full list of public channels.
/// </summary>
[Obsolete("Use GetConversations instead")]
public Task<IReadOnlyList<Channel>> GetChannels() => _channels.GetOrCreateValue(FetchChannels);
private async Task<IReadOnlyList<Channel>> FetchChannels() => CacheHubs(
(await GetConversations().ConfigureAwait(false))
.Where(c => c.IsChannel)
.Select(ConversationConversion.ToChannel)
.ToList());
/// <summary>
/// Get list of private groups that the bot is in.
/// </summary>
[Obsolete("Use GetConversations instead")]
public Task<IReadOnlyList<Channel>> GetGroups() => _groups.GetOrCreateValue(FetchGroups);
private async Task<IReadOnlyList<Channel>> FetchGroups() => CacheHubs(
(await GetConversations().ConfigureAwait(false))
.Where(c => c.IsGroup)
.Select(ConversationConversion.ToChannel)
.ToList());
/// <summary>
/// Get list of multi-person IMs that the bot is in.
/// </summary>
/// <returns></returns>
[Obsolete("Use GetConversations instead")]
public Task<IReadOnlyList<Channel>> GetMpIms() => _mpims.GetOrCreateValue(FetchMpims);
private async Task<IReadOnlyList<Channel>> FetchMpims() => CacheHubs(
(await GetConversations().ConfigureAwait(false))
.Where(c => c.IsMpim)
.Select(ConversationConversion.ToChannel)
.ToList());
private IReadOnlyList<Channel> CacheHubs(IReadOnlyList<Channel> channels)
{
foreach (var channel in channels)
_hubs[channel.Id] = Task.FromResult((Hub)channel);
return channels;
}
/// <summary>
/// Get list of IMs that have been opened with the bot.
/// </summary>
[Obsolete("Use GetConversations instead")]
public Task<IReadOnlyList<Im>> GetIms() => _ims.GetOrCreateValue(FetchIms);
private async Task<IReadOnlyList<Im>> FetchIms() =>
(await GetConversations().ConfigureAwait(false))
.Where(c => c.IsIm)
.Select(ConversationConversion.ToIm)
.ToList();
#endregion
}
class PostedMessage
{
public BotMessage Message { get; set; }
public Task<PostMessageResponse> Post { get; set; }
}
}