Example #1
0
        public IEnumerable <ResponseMessage> Booop(IncomingMessage message, IValidHandle matchedHandle)
        {
            string replyMessage = "boopp im testing ";

            Attachment test = new Attachment
            {
                Text     = "test text",
                Title    = "Test Title",
                Color    = "Red",
                ImageUrl =
                    "https://image.shutterstock.com/image-vector/cool-bear-illustration-tshirt-other-450w-766363144.jpg",
                ThumbUrl =
                    "https://image.shutterstock.com/image-vector/cool-bear-illustration-tshirt-other-450w-766363144.jpg",
                Fallback         = "fall back string",
                AuthorName       = "Author string",
                AttachmentFields = new List <AttachmentField>()
                {
                    new AttachmentField()
                    {
                        Title   = "test title one",
                        Value   = "test value one",
                        IsShort = false
                    },
                    new AttachmentField()
                    {
                        Title   = "test title two",
                        Value   = "test value two",
                        IsShort = true
                    }
                }
            };

            yield return(message.ReplyToChannel(replyMessage, test));
        }
Example #2
0
        private IEnumerable <ResponseMessage> JiraHandler(IncomingMessage message, IValidHandle matchedHandle)
        {
            string searchTerm = message.TargetedText.Substring(matchedHandle.HandleHelpText.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 url         = _configReader.GetConfigEntry <string>("jira:url");
                string prefix      = _configReader.GetConfigEntry <string>("jira:prefix");
                string base64Token = _configReader.GetConfigEntry <string>("jira:base64Token");

                if (string.IsNullOrEmpty(url) && string.IsNullOrEmpty(prefix) && string.IsNullOrEmpty(base64Token))
                {
                    _statsPlugin.IncrementState("Jira:Failed");
                    yield return(message.ReplyToChannel("Woops, looks like settings for Jira is not configured properly. Please ask the admin to fix this"));
                }
                else
                {
                    string messageToAnswer = GetDataFromJira(message.RawText, url, prefix, base64Token);
                    yield return(message.ReplyToChannel(messageToAnswer));
                }
            }
        }
Example #3
0
        public IEnumerable <ResponseMessage> ConfirmHandler(IncomingMessage message, IValidHandle matchedHandle)
        {
            string response = string.Empty;

            if (_negativeResponses.Contains(message.FullText))
            {
                try
                {
                    _orderCache.DeleteOrder(message.Username);
                    response = "Ok, I've removed that order for you. Thanks anyway.";
                }
                catch (ArgumentException)
                {
                    response = "You don't have any unconfirmed orders...";
                }
            }
            else if (_positiveResponses.Contains(message.FullText))
            {
                try
                {
                    _orderCache.ConfirmOrder(message.Username);
                    response = "Ok your order is with our baristas now! I'll let you know when it's ready.";
                }
                catch (ArgumentException)
                {
                    response = "Sorry, I couldn't find an order to confirm. What drinks would you like to order?";
                }
            }

            yield return(message.ReplyDirectlyToUser(response));
        }
Example #4
0
        public IEnumerable <ResponseMessage> OrderHandler(IncomingMessage message, IValidHandle matchedHandle)
        {
            Order  order        = null;
            string responseText = string.Empty;

            try
            {
                order = _orderBuilder.BuildOrder(message.FullText, message.Username);

                if (!order.MannersUsed)
                {
                    responseText  = _mannersMessageGenerator.GetMannerResponse();
                    responseText += Environment.NewLine;
                }

                _orderCache.CacheOrder(order);
                responseText += _orderFormatter.FormatOrder(order);
            }
            catch (ArgumentException)
            {
                responseText += "Sorry, I couldn't figure out your table number. Please try again.";
            }
            catch (InvalidOperationException ioEx)
            {
                responseText += ioEx.Message;
            }
            catch (Exception ex)
            {
                responseText += "Sorry, it looks like something has gone wrong. Please could you try again?";
                responseText += Environment.NewLine;
                responseText += ex.Message;
            }

            yield return(message.ReplyDirectlyToUser(responseText));
        }
        private IEnumerable <ResponseMessage> Handler(IncomingMessage message, IValidHandle matchedHandle)
        {
            if (!_authorizationPlugin.HasPermission("tflights", message.UserEmail))
            {
                yield return(message.ReplyToChannel("Nope! Ask for access first.")); yield break;
            }

            yield return(message.IndicateTypingOnChannel());

            var results = _flightFinderClient.Find().GetAwaiter().GetResult();

            var attachments = results
                              .OrderBy(x => x.Departure)
                              .Take(15)
                              .Select(x => new Attachment
            {
                Text  = GetText(x),
                Color = GetColor(x)
            })
                              .ToList();

            attachments.Add(new Attachment
            {
                Fallback = "Book  your flights at https://www.flypgs.com/en",
                Color    = "#000"
            }.AddAttachmentAction("Book flights", "https://www.flypgs.com/en"));


            yield return(message.ReplyToChannel("Cheapest upcoming weekend flights from London to Istanbul - Friday evening to Sunday evening:", attachments));
        }
        private IEnumerable <ResponseMessage> PinHandler(IncomingMessage message, IValidHandle matchedHandle)
        {
            if (!_adminPlugin.AdminModeEnabled())
            {
                yield return(message.ReplyToChannel("Admin mode isn't enabled."));

                yield break;
            }

            string pinString = message.TargetedText.Substring(matchedHandle.HandleHelpText.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}'"));
            }
        }
Example #7
0
        private IEnumerable <ResponseMessage> AboutHandler(IncomingMessage message, IValidHandle 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"));
        }
Example #8
0
        private IEnumerable <ResponseMessage> HourlyHandler(IncomingMessage message, IValidHandle matchedHandle)
        {
            int    minutesPastTheHour = DateTime.Now.Minute;
            string schedule           = $"0 {minutesPastTheHour} */1 * * ?";
            string command            = message.TargetedText.Substring(matchedHandle.HandleHelpText.Length).Trim();

            yield return(CreateSchedule(message, command, schedule));
        }
Example #9
0
        private IEnumerable <ResponseMessage> AboutHandler(IncomingMessage message, IValidHandle matchedHandle)
        {
            yield return(message.ReplyDirectlyToUser("uBot - a sassy uInform bot"));

            yield return(message.ReplyDirectlyToUser("I am a SlackBot built in C# using piles of spaghet"));

            yield return(message.ReplyDirectlyToUser("Contact Matt Wilson (uConnect|IET) for help / troubleshooting"));
        }
Example #10
0
        private IEnumerable <ResponseMessage> KarmaHandler(IncomingMessage message, IValidHandle matchedHandle)
        {
            var matches = _karmaPlugin.GetMessageMatches(message.FullText);

            foreach (Match match in matches)
            {
                var changeRequest = _karmaPlugin.ParseKarmaChange(match.Value);
                yield return(HandleKarmaChange(message, changeRequest));
            }
        }
Example #11
0
        IEnumerable <ResponseMessage> WhatHappened(IncomingMessage msg, IValidHandle handle)
        {
            var user = ctx.Users.Single(x => x.UserId == msg.UserId);
            var utxt = new String(msg.RawText.Substring(whc.Length).TakeWhile(c => c != '?').ToArray());
            int?wk   = null;

            switch (utxt)
            {
            case "last week": wk = -1; break;

            case "this week": wk = 0; break;

            default:
                if (int.TryParse(utxt, out int wki))
                {
                    wk = wki;
                }
                break;
            }
            if (!wk.HasValue)
            {
                yield return(msg.ReplyDirectlyToUser($"Sorry, that {whc}didn't make sense to me!"));
            }
            else
            {
                var wkv = ctx.WhatHappened(wk.Value, user);
                if (wkv.data.Count() == 0)
                {
                    yield return(msg.ReplyDirectlyToUser("Nothing!"));
                }
                else
                {
                    StringBuilder Response = new StringBuilder();
                    Response.AppendLine($"▓▒░▓ *Week of {wkv.start.ToShortDateString()}* ▓░▒▓");
                    var wd = wkv.data.GroupBy(x => (int)x.When.DayOfWeek).ToDictionary(x => x.Key, x => x as IEnumerable <LogModel>);
                    foreach (var x in new[] { 1, 2, 3, 4, 5, 6, 0 })
                    {
                        Response.Append($"*{(DayOfWeek)x}*");
                        if (wd.ContainsKey(x))
                        {
                            Response.AppendLine();
                            foreach (var it in wd[x])
                            {
                                Response.AppendLine($"{it.When.ToShortTimeString()}: {it.Data}");
                            }
                        }
                        else
                        {
                            Response.AppendLine(" _nothing_");
                        }
                    }
                    yield return(msg.ReplyDirectlyToUser(Response.ToString()));
                }
            }
        }
Example #12
0
        private IEnumerable <ResponseMessage> BeerHandler(IncomingMessage message, IValidHandle matchedHandle)
        {
            if (!message.BotIsMentioned)
            {
                yield break;
            }

            var response = GetBeerResponse(message);

            yield return(message.ReplyToChannel(response));
        }
Example #13
0
        private IEnumerable <ResponseMessage> Handler(IncomingMessage message, IValidHandle matchedHandle)
        {
            var command = ExtractCommand(message.TargetedText);

            switch (command)
            {
            case "graph": yield return(Graph(message)); break;

            case "book": yield return(Book(message)); break;
            }
        }
Example #14
0
        IEnumerable <ResponseMessage> Log(IncomingMessage msg, IValidHandle handle)
        {
            var user = ctx.Users.Single(x => x.UserId == msg.UserId);

            ctx.Add(new LogModel {
                User = user, When = DateTime.Now, Data = msg.RawText
            });
            ctx.SaveChanges();
            ModelContext.OnChanged();
            yield return(msg.ReplyDirectlyToUser(gotit[rd.Next(0, gotit.Length - 1)]));
        }
        private IEnumerable <ResponseMessage> JokeHandler(IncomingMessage message, IValidHandle matchedHandle)
        {
            yield return(message.IndicateTypingOnChannel());

            var jokeResponse = new Random().Next(0, 100) < 80 ? GetChuckNorrisJoke() : GetMommaJoke();

            _statsPlugin.IncrementState("Jokes:Told");
            var jokeString = $"{{ {jokeResponse.SelectToken("$..joke").Parent} }}";
            var joke       = JsonConvert.DeserializeObject <JokeContainer>(jokeString);

            yield return(message.ReplyToChannel(joke.Joke));
        }
        private IEnumerable <ResponseMessage> FlickrHandler(IncomingMessage message, IValidHandle matchedHandle)
        {
            string searchTerm = message.TargetedText.Substring(matchedHandle.HandleHelpText.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}"));
                    }
                }
            }
        }
Example #17
0
        private IEnumerable <ResponseMessage> StatsHandler(IncomingMessage message, IValidHandle 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."));
            }
        }
Example #18
0
        private IEnumerable <ResponseMessage> HelpHandler(IncomingMessage message, IValidHandle 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.ReplyToChannel(builder.ToString()));
        }
Example #19
0
        private IEnumerable <ResponseMessage> CronHandler(IncomingMessage message, IValidHandle matchedHandle)
        {
            string cronJob    = message.TargetedText.Substring(matchedHandle.HandleHelpText.Length).Trim();
            Match  regexMatch = CronFormat.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));
        }
Example #20
0
        public IEnumerable <ResponseMessage> SetDevice(IncomingMessage message, IValidHandle matchedHandle)
        {
            string reply;
            Regex  regex          = new Regex(this._setDeviceRegEx);
            Match  setDeviceMatch = regex.Match(message.RawText);

            if (setDeviceMatch.Success)
            {
                string deviceId = setDeviceMatch.Groups["DeviceId"].Value;
                this._spotifyPlugin.SetPlaybackDevice(deviceId);
                reply = "Device was set";
            }
            else
            {
                reply = $"did not match the regex : {message.RawText}";
            }

            yield return(message.ReplyToChannel(reply, (Attachment)null));
        }
Example #21
0
        public IEnumerable <ResponseMessage> HelpHandler(IncomingMessage message, IValidHandle matchedHandle)
        {
            var responseText = string.Empty;

            responseText += "Hello! I'm the Zuto BrewBot. I can help you bypass the queue and use Slack to get your drinks order to our Baristas. I'll then let you know when it's ready for you to collect.";
            responseText += Environment.NewLine;
            responseText += Environment.NewLine;
            responseText += "To put an order in, just tell me what you'd like and which table number you're sat at (and manners always help!). If you don't include your table number, I won't understand your order, so make sure you include it.";
            responseText += Environment.NewLine;
            responseText += Environment.NewLine;
            responseText += "I'll then ask you to confirm that your order is correct. Simply type \"yes\" or \"confirm\" if your order is right, or \"no\" if it's wrong.";
            responseText += Environment.NewLine;
            responseText += Environment.NewLine;
            responseText += "Once your order is with our Baristas, keep an eye on the #general channel for a message to let you know it's ready.";
            responseText += Environment.NewLine;
            responseText += Environment.NewLine;
            responseText += "Good luck with your hack... May the odds be ever in your favour.";

            yield return(message.ReplyDirectlyToUser(responseText));
        }
        private IEnumerable <ResponseMessage> Handle(IncomingMessage message, IValidHandle matchedHandle)
        {
            var expression = message.TargetedText.Replace("calc ", string.Empty);

            var responses = new List <string>();

            try
            {
                var func = new SimpleCalculator().ParseExpression(expression).Compile();

                var result = func();

                responses.Add(result.ToString(CultureInfo.InvariantCulture));
            }
            catch (ParseException e)
            {
                responses.Add(e.Message);
            }

            foreach (var response in responses)
            {
                yield return(message.ReplyToChannel(response));
            }
        }
        private IEnumerable <ResponseMessage> PearlOfWisdomHandler(IncomingMessage message, IValidHandle matchedHandle)
        {
            var response = GetResponse(message);

            yield return(message.ReplyToChannel(response));
        }
Example #24
0
        private IEnumerable <ResponseMessage> PurgeCacheTag(IncomingMessage incomingMessage, IValidHandle matchedHandle)
        {
            yield return(incomingMessage.IndicateTypingOnChannel());

            if (!CommandWellFormatted(incomingMessage.TargetedText, requiredCommandLength: 5))
            {
                yield return(incomingMessage.ReplyToChannel($"Command was not formatted correctly. Help: {GetPurgeCacheTagHelpText()}"));

                yield break;
            }

            var cacheTag = GetPositionalElementFromTargetText(incomingMessage.TargetedText, position: 3);
            var zoneName = GetCleanZoneName(GetPositionalElementFromTargetText(incomingMessage.TargetedText, position: 4));

            var result = this.cloudflarePlugin.PurgeZoneCacheTag(zoneName, cacheTag);

            yield return(incomingMessage.ReplyToChannel(result.Message));
        }
Example #25
0
        private IEnumerable <ResponseMessage> RecommendBeerHandler(IncomingMessage message, IValidHandle matchedHandle)
        {
            var response = GetRecommendBeerResponse(message);

            yield return(message.ReplyToChannel(response));
        }
        private async IAsyncEnumerable <ResponseMessage> DayHandler(IncomingMessage message, IValidHandle matchedHandle)
        {
            var minutesPastTheHour = DateTime.Now.Minute - 1;
            var hourOfDay          = DateTime.Now.Hour;
            var schedule           = $"0 {minutesPastTheHour} {hourOfDay} * * ?";
            var command            = message.TargetedText.Substring(matchedHandle.HandleHelpText.Length).Trim();

            yield return(await CreateSchedule(message, command, schedule));
        }
        private async IAsyncEnumerable <ResponseMessage> DeleteHandlerForChannel(IncomingMessage message, IValidHandle matchedHandle)
        {
            var idString = message.TargetedText.Substring(matchedHandle.HandleHelpText.Length).Trim();

            if (Guid.TryParse(idString, out var guid))
            {
                var schedules        = _schedulePlugin.ListSchedulesForChannel(message.Channel);
                var scheduleToDelete = schedules.FirstOrDefault(x => x.Guid == guid);

                if (scheduleToDelete == null)
                {
                    yield return(await Task.FromResult(message.ReplyToChannel($"Unable to find schedule with GUID: `'{guid}'`")));
                }
                else
                {
                    _schedulePlugin.DeleteSchedule(guid);
                    yield return(message.ReplyToChannel($"Removed schedule: `{scheduleToDelete}`"));
                }
            }
            else
            {
                yield return(message.ReplyToChannel($"Invalid id entered. Try using `schedule list`. (`{idString}`)"));
            }
        }
        private async IAsyncEnumerable <ResponseMessage> ListHandlerForChannel(IncomingMessage message, IValidHandle matchedHandle)
        {
            var schedules = _schedulePlugin.ListSchedulesForChannel(message.Channel);

            if (schedules.Any())
            {
                yield return(await Task.FromResult(message.ReplyToChannel("Schedules for channel:")));

                string[] scheduleStrings = schedules.Select(x => x.ToString()).ToArray();
                yield return(message.ReplyToChannel(">>>" + string.Join("\n", scheduleStrings)));
            }
            else
            {
                yield return(message.ReplyToChannel("No schedules set for this channel."));
            }
        }
Example #29
0
        private IEnumerable <ResponseMessage> LikedRecipeHandler(IncomingMessage message, IValidHandle matchedHandle)
        {
            App        app        = new App();
            Recipe     recipe     = new Recipe();
            DataAccess dataAccess = new DataAccess("Server=(localdb)\\mssqllocaldb; Database=Reczept");
            User       user       = new User
            {
                MemberId = message.UserId
            };
            var tempArray = message.TargetedText.Split(' ');

            if (tempArray.Length > 1)
            {
                if (tempArray[1] == "inte")
                {
                    dataAccess.AddIfLikedOrNot(user, false);
                    yield return(message.ReplyToChannel("Tack! Ditt val är sparat!"));
                }
                else
                {
                    yield return(message.ReplyToChannel("Jag förstod inte ditt svar. Skriv 'gillar' eller 'gillar inte' för att registrera din preferens!"));
                }
            }
            else
            {
                dataAccess.AddIfLikedOrNot(user, true);
                yield return(message.ReplyToChannel("Tack! Ditt val är sparat!"));
            }
        }
Example #30
0
        private async IAsyncEnumerable <ResponseMessage> ReasonHandler(IncomingMessage message, IValidHandle matchedHandle)
        {
            var karmaEntryName  = _karmaPlugin.ParseNameFromReasonRequest(message.FullText);
            var numberRequested = _karmaPlugin.ParseNumberFromEndOfRequest(message.FullText);

            int reasonsCount = 0;

            foreach (var entry in _karmaRepositoryPlugin.GetReasons(karmaEntryName, numberRequested))
            {
                yield return(message.ReplyToChannel(_karmaPlugin.GenerateReasonMessage(entry)));

                reasonsCount++;
            }

            if (reasonsCount == 0)
            {
                yield return(message.ReplyToChannel($"No reasons found for {karmaEntryName}"));
            }
        }