public WhenHandler( SlackBot bot, Func <Message, Task <Match[]> > matchGenerator, Func <Message, Match[], Task <(bool success, Exception ex)> > messageHandler)
internal static async Task <SlackBot> InitializeAsync(IDriver driver, IMessageBus bus, Action <ISlackBotConfig> config = null) { var defaultConfig = new DefaultSlackBotConfig(); config?.Invoke(defaultConfig); var logger = defaultConfig.LoggerFactory.CreateLogger <SlackBot>(); var state = await driver.ConnectAsync(bus, logger); var bot = new SlackBot(state, driver, bus, defaultConfig, logger); bot.On <IHubJoined>(msg => { bot.state.AddHub(msg.Channel.Id, msg.Channel.Name, msg.HubType); logger.LogInformation($"Joined hub {msg.Channel.Name} (Id: {msg.Channel.Id})"); }); bot.On <IHubLeft>(msg => { logger.LogInformation($"Left hub {bot.state.GetHubById(msg.Channel).Name}"); bot.state.RemoveHub(msg.Channel); }); // Handle .When setups bot.On <Message>(async msg => { // Ignore messages with reply_to that is set. // They appear to be sent after the initial connection that the bot establishes. if (!string.IsNullOrEmpty(msg.ReplyTo)) { return; } (decimal score, Match[] matches, WhenHandler handler)bestMatch = (-1m, null, null); foreach (var handler in bot.whenHandlers) { var matches = new Match[0]; try { matches = await handler.MatchGenerator.Invoke(msg); } catch (Exception exception) { handler.OnException(msg, exception); } if (matches == null) { continue; } decimal score = matches.Sum(m => m.Score); if (score < 0) { continue; } if (bot.config.WhenHandlerMatchMode == WhenHandlerMatchMode.AllMatches || bot.config.WhenHandlerMatchMode == WhenHandlerMatchMode.FirstMatch) { var(success, ex) = await handler.MessageHandler(msg, matches); if (ex != null) { handler.OnException(msg, ex); } if (success && bot.config.WhenHandlerMatchMode == WhenHandlerMatchMode.FirstMatch) { break; } } if (score > bestMatch.score) { bestMatch = (score, matches, handler); } } if (bot.config.WhenHandlerMatchMode == WhenHandlerMatchMode.BestMatch && bestMatch.handler != null) { await bestMatch.handler.MessageHandler(msg, bestMatch.matches); } }); return(bot); }
internal Conversation(SlackBot bot, Modes modes, Message message, Match[] matches) : this(bot, modes, message, matches, new CancellationTokenSource()) { }