private IEnumerable<ResponseMessage> DeleteHandlerForChannel(IncomingMessage message, string matchedHandle) { string idString = message.TargetedText.Substring(matchedHandle.Length).Trim(); int? id = ConvertToInt(idString); if (id.HasValue) { SchedulePlugin.ScheduleEntry[] schedules = _schedulePlugin.ListSchedulesForChannel(message.Channel); if (id < 0 || id > (schedules.Length - 1)) { yield return message.ReplyToChannel($"Woops, unable to delete schedule with id of `{id.Value}`"); } else { _schedulePlugin.DeleteSchedule(schedules[id.Value]); yield return message.ReplyToChannel($"Removed schedule: {schedules[id.Value]}"); } } else { yield return message.ReplyToChannel($"Invalid id entered. Try using `schedule list`. ({idString})"); } }
private IEnumerable<ResponseMessage> ListPingHandler(IncomingMessage message, string matchedHandle) { string[] users = _pingPlugin.ListPingedUsers(); yield return message.ReplyDirectlyToUser("I am currently pinging:"); yield return message.ReplyDirectlyToUser(">>>" + string.Join("\n", users)); }
private IEnumerable<ResponseMessage> CalculateHandler(IncomingMessage message, string matchedHandle) { string response = string.Empty; if (matchedHandle != null) { string expression = message.FullText.Substring(matchedHandle.Length).Trim(); Parser parser = new Parser(); try { IExpression parsedExpression = parser.Parse(expression); object result = parsedExpression.Calculate(); response = $"{parsedExpression} = {result}"; } catch (Exception e) { bool showErrors = !string.IsNullOrEmpty(matchedHandle); if (showErrors) { _statsPlugin.IncrementState("Calc:Failed"); response = $"Who taught you maths? {e.Message}"; } } } if (!string.IsNullOrEmpty(response)) { _statsPlugin.IncrementState("Calc:Calced"); yield return message.ReplyToChannel($"@{message.Username}: {response}"); } }
private IEnumerable<ResponseMessage> PinHandler(IncomingMessage message, string matchedHandle) { if (!_adminPlugin.AdminModeEnabled()) { yield return message.ReplyToChannel("Admin mode isn't enabled."); yield break; } string pinString = message.TargetedText.Substring(matchedHandle.Length).Trim(); int pin; if (int.TryParse(pinString, out pin)) { if (_adminPlugin.AuthoriseUser(message.UserId, pin)) { yield return message.ReplyToChannel($"{message.Username} - you now have admin rights."); _log.Info($"{message.Username} now has admin rights."); } else { yield return message.ReplyToChannel("Incorrect admin pin entered."); } } else { yield return message.ReplyToChannel($"Unable to parse pin '{pinString}'"); } }
public virtual IEnumerable<ResponseMessage> Invoke(IncomingMessage message) { foreach (var handlerMapping in HandlerMappings) { foreach (string map in handlerMapping.ValidHandles) { string text = message.FullText; if (handlerMapping.MessageShouldTargetBot) { text = message.TargetedText; } if (text.StartsWith(map, StringComparison.InvariantCultureIgnoreCase)) { //TODO: How to do this //_log.Log($"Matched '{map}' on '{this.GetType().Name}'"); foreach (var responseMessage in handlerMapping.EvaluatorFunc(message, map)) { yield return responseMessage; } if (!handlerMapping.ShouldContinueProcessing) { yield break; } } } } foreach (ResponseMessage responseMessage in Next(message)) { yield return responseMessage; } }
private IEnumerable<ResponseMessage> HourlyHandler(IncomingMessage message, string matchedHandle) { int minutesPastTheHour = DateTime.Now.Minute; string schedule = $"0 {minutesPastTheHour} */1 * * ?"; string command = message.TargetedText.Substring(matchedHandle.Length).Trim(); yield return CreateSchedule(message, command, schedule); }
private IEnumerable<ResponseMessage> WelcomeHandler(IncomingMessage message, string matchedHandle) { _statsPlugin.IncrementState("Hello"); yield return message.ReplyToChannel($"Hey @{message.Username}, how you doing?"); Thread.Sleep(TimeSpan.FromSeconds(5)); yield return message.ReplyDirectlyToUser("I know where you live..."); }
private IEnumerable<ResponseMessage> YieldTest(IncomingMessage incomingMessage, string matchedHandle) { for (int i = 0; i < 10; i++) { Console.WriteLine("Sending message"); yield return new ResponseMessage { Channel = incomingMessage.Channel, Text = "Waiting " + i }; Thread.Sleep(TimeSpan.FromSeconds(2)); } }
private IEnumerable<ResponseMessage> StopPingingHandler(IncomingMessage message, string matchedHandle) { if (_pingPlugin.StopPingingUser(message.UserId)) { yield return message.ReplyToChannel($"Ok, I will stop pinging @{message.Username}"); } else { yield return message.ReplyToChannel($"BUT I AM NOT PINGING @{message.Username}"); } }
public override IEnumerable<ResponseMessage> Invoke(IncomingMessage message) { _statsPlugin.IncrementState("Messages:Received"); _log.Info($"Message from {message.Username}: {message.FullText}"); foreach (ResponseMessage responseMessage in Next(message)) { _statsPlugin.IncrementState("Messages:Sent"); yield return responseMessage; } }
private IEnumerable<ResponseMessage> StatsHandler(IncomingMessage message, string matchedHandle) { string textMessage = string.Join(Environment.NewLine, _statsPlugin.GetStats().OrderBy(x => x)); if (!string.IsNullOrEmpty(textMessage)) { yield return message.ReplyToChannel(">>>" + textMessage); } else { yield return message.ReplyToChannel("No stats have been recorded yet."); } }
private IEnumerable<ResponseMessage> FlickrHandler(IncomingMessage message, string matchedHandle) { string searchTerm = message.TargetedText.Substring(matchedHandle.Length).Trim(); if (string.IsNullOrEmpty(searchTerm)) { yield return message.ReplyToChannel($"Please give me something to search, e.g. {matchedHandle} trains"); } else { yield return message.IndicateTypingOnChannel(); string apiKey = _configReader.GetConfigEntry<string>("flickr:apiKey"); if (string.IsNullOrEmpty(apiKey)) { _statsPlugin.IncrementState("Flickr:Failed"); yield return message.ReplyToChannel("Woops, looks like a Flickr API Key has not been entered. Please ask the admin to fix this"); } else { var flickr = new Flickr(apiKey); var options = new PhotoSearchOptions { Tags = searchTerm, PerPage = 50, Page = 1}; PhotoCollection photos = flickr.PhotosSearch(options); if (photos.Any()) { _statsPlugin.IncrementState("Flickr:Sent"); int i = new Random().Next(0, photos.Count); Photo photo = photos[i]; var attachment = new Attachment { AuthorName = photo.OwnerName, Fallback = photo.Description, ImageUrl = photo.LargeUrl, ThumbUrl = photo.ThumbnailUrl }; yield return message.ReplyToChannel($"Here is your picture about '{searchTerm}'", attachment); } else { _statsPlugin.IncrementState("Flickr:Failed"); yield return message.ReplyToChannel($"Sorry @{message.Username}, I couldn't find anything about {searchTerm}"); } } } }
private IEnumerable<ResponseMessage> HelpHandler(IncomingMessage message, string matchedHandle) { var builder = new StringBuilder(); builder.Append(">>>"); IEnumerable<CommandDescription> supportedCommands = GetSupportedCommands().OrderBy(x => x.Command); foreach (CommandDescription commandDescription in supportedCommands) { string description = commandDescription.Description.Replace("@{bot}", $"@{_noobotCore.GetBotUserName()}"); builder.AppendFormat("{0}\t- {1}\n", commandDescription.Command, description); } yield return message.ReplyDirectlyToUser(builder.ToString()); }
private IEnumerable<ResponseMessage> ListHandlerForChannel(IncomingMessage message, string matchedHandle) { SchedulePlugin.ScheduleEntry[] schedules = _schedulePlugin.ListSchedulesForChannel(message.Channel); if (schedules.Any()) { yield return message.ReplyToChannel("Schedules for channel:"); string[] scheduleStrings = schedules.Select((x, i) => x.ToString(i)).ToArray(); yield return message.ReplyToChannel(">>>" + string.Join("\n", scheduleStrings)); } else { yield return message.ReplyToChannel("No schedules set for this channel."); } }
private IEnumerable<ResponseMessage> CronHandler(IncomingMessage message, string matchedHandle) { string cronJob = message.TargetedText.Substring(matchedHandle.Length).Trim(); Match regexMatch = Regex.Match(cronJob); if (!regexMatch.Success) { yield return message.ReplyToChannel($"Error while parsing cron job. Your command should match something like `@{message.BotName} schedule cronjob '0 15 10 * * ?' @{message.BotName} tell me a joke``"); yield break; } string schedule = regexMatch.Groups[1].Value.Trim(); string command = regexMatch.Groups[2].Value.Trim(); yield return CreateSchedule(message, command, schedule); }
private IEnumerable<ResponseMessage> JokeHandler(IncomingMessage message, string matchedHandle) { yield return message.IndicateTypingOnChannel(); IRestResponse jokeResponse = new Random().Next(0, 100) < 80 ? GetTambalJoke() : GetMommaJoke(); if (jokeResponse.StatusCode == HttpStatusCode.OK) { _statsPlugin.IncrementState("Jokes:Told"); var joke = JsonConvert.DeserializeObject<JokeContainer>(jokeResponse.Content); yield return message.ReplyToChannel(joke.Joke); } else { _statsPlugin.IncrementState("Jokes:Failed"); yield return message.ReplyToChannel($"Dam, I can't think of one. [{jokeResponse.StatusCode}]"); } }
private IEnumerable<ResponseMessage> ChannelsHandler(IncomingMessage message, string matchedHandle) { if (!_adminPlugin.AuthenticateUser(message.UserId)) { yield return message.ReplyToChannel($"Sorry {message.Username}, only admins can use this function."); yield break; } Dictionary<string, string> channels = _noobotCore.ListChannels(); yield return message.ReplyToChannel("All Connected Channels:"); yield return message.ReplyToChannel(">>>" + string.Join("\n", channels.Select(x => $"{x.Key}: {x.Value}"))); }
private IEnumerable<ResponseMessage> DeleteSchedulesHandler(IncomingMessage message, string matchedHandle) { if (!_adminPlugin.AuthenticateUser(message.UserId)) { yield return message.ReplyToChannel($"Sorry {message.Username}, only admins can use this function."); yield break; } var schedules = _schedulePlugin.ListAllSchedules(); _schedulePlugin.DeleteSchedules(schedules.Select(x => x.Guid).ToArray()); yield return message.ReplyToChannel("All schedules deleted"); }
private IEnumerable<ResponseMessage> SchedulesListHandler(IncomingMessage message, string matchedHandle) { if (!_adminPlugin.AuthenticateUser(message.UserId)) { yield return message.ReplyToChannel($"Sorry {message.Username}, only admins can use this function."); yield break; } var schedules = _schedulePlugin.ListAllSchedules(); string[] scheduleStrings = schedules.Select(x => $"Guid: '{x.Guid}' Channel: '{x.Channel}'.").ToArray(); yield return message.ReplyToChannel("All Schedules:"); yield return message.ReplyToChannel(">>>" + string.Join("\n", scheduleStrings)); }
private ResponseMessage CreateSchedule(IncomingMessage message, string command, string cronSchedule) { var schedule = new ScheduleEntry { Guid = Guid.NewGuid(), Channel = message.Channel, ChannelType = message.ChannelType, Command = command, CronSchedule = cronSchedule, UserId = message.UserId, UserName = message.Username, Created = DateTime.Now }; if (!CronExpression.IsValidExpression(cronSchedule)) { return message.ReplyToChannel($"Unknown cron schedule `'{cronSchedule}'`"); } if (string.IsNullOrEmpty(schedule.Command)) { return message.ReplyToChannel("Please enter a command to be scheduled."); } _schedulePlugin.AddSchedule(schedule); return message.ReplyToChannel($"Schedule created for command '{schedule.Command}'."); }
private IEnumerable<ResponseMessage> NightlyHandler(IncomingMessage message, string matchedHandle) { yield return CreateSchedule(message, matchedHandle, TimeSpan.FromDays(1), true); }
private IEnumerable<ResponseMessage> AutoResponseHandler(IncomingMessage message, string matchedHandle) { yield return message.ReplyDirectlyToUser(message.FullText); }
private ResponseMessage CreateSchedule(IncomingMessage message, string matchedHandle, TimeSpan timeSpan, bool runOnlyAtNight) { var schedule = new SchedulePlugin.ScheduleEntry { Channel = message.Channel, ChannelType = message.ChannelType, Command = message.TargetedText.Substring(matchedHandle.Length).Trim(), RunEvery = timeSpan, UserId = message.UserId, UserName = message.Username, LastRun = DateTime.Now, RunOnlyAtNight = runOnlyAtNight }; if (string.IsNullOrEmpty(schedule.Command)) { return message.ReplyToChannel("Please enter a command to be scheduled."); } else { _schedulePlugin.AddSchedule(schedule); return message.ReplyToChannel($"Schedule created for command '{schedule.Command}'."); } }
private IEnumerable<ResponseMessage> AboutHandler(IncomingMessage message, string matchedHandle) { yield return message.ReplyDirectlyToUser("Noobot - Created by Simon Colmer " + DateTime.Now.Year); yield return message.ReplyDirectlyToUser("I am an extensible SlackBot built in C# using loads of awesome open source projects."); yield return message.ReplyDirectlyToUser("Please find more at http://github.com/noobot/noobot"); }
private IEnumerable<ResponseMessage> PingHandler(IncomingMessage message, string matchedHandle) { yield return message.ReplyToChannel($"Ok, I will start pinging @{message.Username}"); _pingPlugin.StartPingingUser(message.UserId); }
public async Task MessageReceived(SlackMessage message) { Stopwatch stopwatch = Stopwatch.StartNew(); _log.Info($"[Message found from '{message.User.Name}']"); IMiddleware pipeline = _container.GetMiddlewarePipeline(); var incomingMessage = new IncomingMessage { RawText = message.Text, FullText = message.Text, UserId = message.User.Id, Username = GetUsername(message), Channel = message.ChatHub.Id, ChannelType = message.ChatHub.Type == SlackChatHubType.DM ? ResponseType.DirectMessage : ResponseType.Channel, UserChannel = await GetUserChannel(message), BotName = _connection.Self.Name, BotId = _connection.Self.Id, BotIsMentioned = message.MentionsBot }; incomingMessage.TargetedText = incomingMessage.GetTargetedText(); try { foreach (ResponseMessage responseMessage in pipeline.Invoke(incomingMessage)) { await SendMessage(responseMessage); } } catch (Exception ex) { _log.Error($"ERROR WHILE PROCESSING MESSAGE: {ex}"); } stopwatch.Stop(); _log.Info($"[Message ended - Took {stopwatch.ElapsedMilliseconds} milliseconds]"); _averageResponse.Log(stopwatch.ElapsedMilliseconds); }
public IEnumerable<ResponseMessage> Invoke(IncomingMessage message) { _log.Info("Unhandled"); return new ResponseMessage[0]; }
private IEnumerable<ResponseMessage> HourlyHandler(IncomingMessage message, string matchedHandle) { yield return CreateSchedule(message, matchedHandle, TimeSpan.FromHours(1), false); }
private IEnumerable<ResponseMessage> AdminHelpHandler(IncomingMessage message, string matchedHandle) { if (!_adminPlugin.AuthenticateUser(message.UserId)) { yield return message.ReplyToChannel($"Sorry {message.Username}, only admins can use this function."); yield break; } foreach (var handlerMapping in HandlerMappings) { string mappings = string.Join(" | ", handlerMapping.ValidHandles.Select(x => $"{x}")); yield return message.ReplyDirectlyToUser($"`{mappings}` - {handlerMapping.Description}"); } }
protected IEnumerable<ResponseMessage> Next(IncomingMessage message) { return _next.Invoke(message); }