Example #1
0
            public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
            {
                GroupCollection newCollection =
                    new Regex(@"^coron\S+ (.+)$", RegexOptions.Compiled | RegexOptions.IgnoreCase).Match("corona total").Groups;

                return(new GetCoronaRegionStats().RunCommand(messageEvent, newCollection, useCache));
            }
Example #2
0
            public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
            {
                WeatherApiConfigModel weatherApiConfig =
                    ConfigHelpers.LoadConfig <WeatherApiConfigModel>(ConfigHelpers.ConfigPaths.WeatherApiConfig);

                if (!weatherApiConfig.UserDefaultLocale.ContainsKey(messageEvent.Nick))
                {
                    return($"User has no default locale set, use '{messageEvent.MessageWithPrefix[0]}{arguments[0].Value} set <locale>' command to set a locale.".SplitInParts(430).ToList());
                }

                CurrentWeatherModel.CurrentWeather currentWeather;

                bool shortQuery = arguments[0].Value == "ws";

                try
                {
                    currentWeather =
                        Weather.GetCurrentWeatherAsync(weatherApiConfig.UserDefaultLocale[messageEvent.Nick],
                                                       weatherApiConfig.ApiKey).Result;
                }
                catch (Exception e)
                {
                    if (e.InnerException is QueryNotFoundException)
                    {
                        return("Could not find given location.".SplitInParts(430).ToList());
                    }
                    throw;
                }

                return(FormatResponse.FormatWeatherResponse(currentWeather.Current, currentWeather.Location, shortWeather: shortQuery)
                       .SplitInParts(430)
                       //.Concat(FormatResponse.FormatForecastResponse(forecastWeather.Forecast, forecastWeather.Location, shortWeather: shortQuery))
                       .ToList());
            }
Example #3
0
            public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
            {
                var enabledChannels = ConfigHelpers.LoadConfig <ChannelUriConfigModel>(ConfigHelpers.ConfigPaths.ChannelUriConfig).YouTubeEnabledChannels;

                if (!enabledChannels.Contains(messageEvent.Channel))
                {
                    return(null);
                }
                string videoId = arguments[1].Value;
                YouTubeApiConfigModel config =
                    ConfigHelpers.LoadConfig <YouTubeApiConfigModel>(ConfigHelpers.ConfigPaths.YouTubeApiConfig);

                YouTubeApiModels.ContentDetailsRoot video =
                    JsonConvert.DeserializeObject <YouTubeApiModels.ContentDetailsRoot>(
                        Http.GetJson(new Uri(
                                         $"https://www.googleapis.com/youtube/v3/videos?part=contentDetails%2C+snippet%2C+statistics&id={videoId}&key={config.ApiKey}")));
                if (video.PageInfo.TotalResults == 0)
                {
                    return(new List <string> {
                        "Video not found"
                    });
                }

                var item = video.Items[0];

                return(new List <string> {
                    $"{item.Snippet.Title} | {item.Snippet.ChannelTitle} - https://www.youtube.com/watch?v={item.Id}"
                });
            }
Example #4
0
        public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
        {
            Uri matchedUri    = new Uri(arguments[0].Value);
            var mentionConfig = UrlHistory.GetConfig();
            var mention       =
                UrlHistory.GetUrlMention(mentionConfig, messageEvent.Channel, matchedUri.AbsoluteUri);

            if (mention == null)
            {
                UrlHistory.AddUrlMention(messageEvent.Nick, messageEvent.Channel, matchedUri.AbsoluteUri);
                return(null);
            }

            if (!UrlHistory.IsChannelEnabled(messageEvent.Channel))
            {
                return(null);
            }

            if (String.Equals(mention.User, messageEvent.Nick, UrlHistory.ComparisonCulture))
            {
                return(null);
            }

            return(UrlHistory.FormatResponse(mention, messageEvent.Nick,
                                             UrlHistory.GetResponse(mentionConfig, messageEvent.Channel),
                                             preventHighlight: UrlHistory.ShouldPreventNickHighlight(mention.User)).SplitInParts(430).ToList());
        }
Example #5
0
 public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
 {
     Thread.Sleep(5000);
     return(new List <string> {
         "💤 Slept for 5 seconds"
     });
 }
Example #6
0
        public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
        {
            List <int> randomRange;

            try
            {
                randomRange = JsonConvert.DeserializeObject <List <int> >(File.ReadAllText(Path.Join("Config", "geez.json")));
            }
            catch (FileNotFoundException)
            {
                randomRange = new List <int> {
                    50, 450
                };
            }
            if (randomRange.Count <= 1)
            {
                randomRange = new List <int> {
                    50, 450
                };
            }

            int geezSize = new Random(Guid.NewGuid().GetHashCode()).Next(randomRange[0], randomRange[1]);

            if (messageEvent.Message.StartsWith("GEEZ"))
            {
                geezSize = geezSize * 2;
            }
            return(("G" + new string('E', geezSize) + "Z").SplitInParts(430).ToList());
        }
            public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
            {
                GroupCollection newCollection =
                    new Regex(@"^stock (\S+)$", RegexOptions.Compiled | RegexOptions.IgnoreCase).Match("stock tsla").Groups;

                return(new GetLatestDailyQuoteBySymbol().RunCommand(messageEvent, newCollection, useCache));
            }
Example #8
0
        public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
        {
            int count = new Regex(Regex.Escape("👌")).Matches(messageEvent.Message).Count;

            return(new List <string> {
                String.Concat(Enumerable.Repeat("👌", count))
            });
        }
        public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
        {
            GdaxTickerApiModel ticker =
                JsonConvert.DeserializeObject <GdaxTickerApiModel>(
                    Http.Get(new Uri("https://api.gdax.com/products/BCH-USD/stats"), compression: true, fuzzUserAgent: true));

            return($"GDAX BCH: Last: ${ticker.Last:n2} - High: ${ticker.High:n2} - Low: ${ticker.Low:n2} - Volume: {ticker.Volume:n2} BTC".SplitInParts(430).ToList());
        }
Example #10
0
            public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
            {
                int count = new Random(Guid.NewGuid().GetHashCode()).Next(10, 40);

                return(new List <string>
                {
                    string.Concat(Enumerable.Repeat("Cannapede ", count))
                });
            }
            public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
            {
                var tickerData = Services.CryptoTickers.GetFinexPubTicker();

                return(new List <string> {
                    $"Finex - Last: ${tickerData.LastPrice:N} - High: ${tickerData.High:N} - " +
                    $"Low: ${tickerData.Low:N} - Volume: {tickerData.Volume:N} - " +
                    $"Last Updated: {DateTime.UtcNow.Humanize(true, tickerData.Timestamp)}"
                });
            }
            public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
            {
                string term = arguments[1].Value.ToLower().TrimEnd();
                int    index;

                string maybeIndex = term.Split(' ').Last();

                if (!int.TryParse(maybeIndex, out index))
                {
                    index = 1;
                }
                else
                {
                    int count         = term.Split(' ').Length;
                    var fuckingkillme = term.Split(' ').ToList();
                    fuckingkillme.RemoveAt(count - 1);
                    term = string.Join(" ", fuckingkillme.ToArray());
                }

                if (index == 0)
                {
                    return(new List <string> {
                        "Nice try asshole"
                    });
                }

                var definitions =
                    JsonConvert.DeserializeObject <UrbanDictionaryApiModel.UrbanDictionaryApiItemListModel>(
                        Http.GetJson(
                            new Uri($"http://api.urbandictionary.com/v0/define?term={WebUtility.HtmlEncode(term)}"),
                            true));

                if (definitions.List.Count == 0)
                {
                    return(new List <string> {
                        "No results from Urban Dictionary"
                    });
                }

                if (definitions.List.Count < index)
                {
                    return(new List <string> {
                        $"Urban Dictionary only returned {definitions.List.Count} results"
                    });
                }

                var item = definitions.List[index - 1];

                return
                    ($"<{item.Author}> Up: {item.ThumbsUp}, Down: {item.ThumbsDown}, \"{item.Definition.ReplaceNewlines(" ")}\", ex: \"{item.Example.ReplaceNewlines()}\", {item.WrittenOn.Humanize(true, DateTime.UtcNow)}, {item.Permalink}"
                     .Truncate(1290).SplitInParts().ToList());
            }
            public List <string> RunCommand(ChannelMessageEventDataModel messageEvent,
                                            GroupCollection arguments = null, bool useCache = true)
            {
                if (arguments == null || arguments.Count == 1)
                {
                    throw new ArgumentException("Not enough arguments");
                }
                string tickerName = arguments[1].Value;

                List <CoinMarketSymbolCacheModel> symbolCache = Cache.Get <List <CoinMarketSymbolCacheModel> >("CoinMarketSymbolCache");

                if (symbolCache == null)
                {
                    // 0 means all in CoinMarketCap-land
                    List <TickerModel> symbolList = CoinMarketCapApi.Api.TickerApi.GetAllTickers(limit: 0).Result;

                    symbolCache = symbolList.Select(symbol =>
                                                    new CoinMarketSymbolCacheModel {
                        Name = symbol.TickerId, Symbol = symbol.Symbol
                    }).ToList();

                    Cache.Set("CoinMarketSymbolCache", symbolCache, DateTimeOffset.Now.AddDays(1));
                }

                foreach (CoinMarketSymbolCacheModel symbol in symbolCache)
                {
                    if (!String.Equals(tickerName, symbol.Symbol, StringComparison.CurrentCultureIgnoreCase))
                    {
                        continue;
                    }
                    tickerName = symbol.Name;
                    break;
                }

                TickerModel ticker;

                try
                {
                    ticker = CoinMarketCapApi.Api.TickerApi.GetTicker(tickerName).Result[0];
                }
                catch (Exception e)
                {
                    if (e.InnerException is CoinMarketCapApi.Exceptions.TickerNotFoundException)
                    {
                        return("Ticker not found".SplitInParts(430).ToList());
                    }
                    throw;
                }

                return(CoinMarketCapHelpers.FormatTicker(ticker));
            }
            public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
            {
                if (arguments == null || arguments.Count == 1)
                {
                    throw new ArgumentException("Not enough arguments");
                }

                string symbolName = arguments[1].Value;

                IexApiModels.IexQuoteApiModel ticker;

                try
                {
                    ticker = IexApi.GetIexQuote(symbolName);
                }
                catch (Http.HttpException e)
                {
                    if (e.Message.Contains("NotFound"))
                    {
                        return(new List <string> {
                            "Symbol does not exist"
                        });
                    }

                    throw;
                }

                if (ticker.Symbol == null)
                {
                    return(new List <string> {
                        "JSON is all f****d up."
                    });
                }

                DateTimeOffset now = new DateTimeOffset(TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow,
                                                                                        TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")), TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time").BaseUtcOffset);
                DateTimeOffset openTime  = new DateTimeOffset(now.Year, now.Month, now.Day, 9, 30, 0, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time").BaseUtcOffset); // Even though it says standard time it is actually DST aware
                DateTimeOffset closeTime = new DateTimeOffset(now.Year, now.Month, now.Day, 16, 0, 0, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time").BaseUtcOffset);

                if ((now >= openTime && now <= closeTime) && !(now.DayOfWeek == DayOfWeek.Saturday || now.DayOfWeek == DayOfWeek.Sunday))
                {
                    return(new List <string> {
                        FormatTicker(ticker)
                    });
                }
                return(new List <string> {
                    FormatAfterHoursTicker(ticker)
                });
            }
Example #15
0
        public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
        {
            string airportCode = arguments[1].Value;
            Dictionary <string, AirportModel> airports = Cache.Get <Dictionary <string, AirportModel> >("Airports");

            if (airports == null)
            {
                airports = Configs.ConfigHelpers.LoadConfig <Dictionary <string, AirportModel> >(Configs.ConfigHelpers
                                                                                                 .ConfigPaths.AirportConfig);
            }
            Cache.Set("Airports", airports, DateTimeOffset.Now.AddDays(1));
            AirportModel airport;

            try
            {
                airport = airports.Single(a =>
                                          string.Equals(a.Value.IATA, airportCode, StringComparison.CurrentCultureIgnoreCase) ||
                                          string.Equals(a.Value.ICAO, airportCode, StringComparison.CurrentCultureIgnoreCase)).Value;
            }
            catch
            {
                return(new List <string> {
                    "Airport probably doesn't exist"
                });
            }

            if (airport == null)
            {
                return(new List <string> {
                    "Airport probably doesn't exist"
                });
            }
            Uri          metarDataUri = new Uri($"https://www.aviationweather.gov/metar/data?ids={airport.ICAO}&format=raw&hours=0&taf=off&layout=off");
            string       pageHtml     = Http.Get(metarDataUri, fuzzUserAgent: true, compression: true);
            HtmlDocument document     = new HtmlDocument();

            document.LoadHtml(pageHtml);
            var metarElement = document.DocumentNode.SelectSingleNode("//code");

            if (metarElement == null)
            {
                return(new List <string> {
                    "Could not find METAR data for airport"
                });
            }
            return(new List <string> {
                airport.Name + ": " + metarElement.InnerText
            });
        }
Example #16
0
            public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
            {
                if (arguments == null || arguments.Count == 1)
                {
                    throw new ArgumentException("Not enough arguments");
                }

                WeatherApiConfigModel weatherApiConfig =
                    ConfigHelpers.LoadConfig <WeatherApiConfigModel>(ConfigHelpers.ConfigPaths.WeatherApiConfig);

                weatherApiConfig.UserDefaultLocale[messageEvent.Nick] = arguments[1].Value;
                ConfigHelpers.SaveConfig(weatherApiConfig, ConfigHelpers.ConfigPaths.WeatherApiConfig);
                return($"Successfully updated default user locale for {messageEvent.Nick} to {arguments[1].Value}".SplitInParts(430)
                       .ToList());
            }
Example #17
0
            public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
            {
                var enabledChannels = ConfigHelpers.LoadConfig <ChannelUriConfigModel>(ConfigHelpers.ConfigPaths.ChannelUriConfig).TwitterEnabledChannels;

                if (!enabledChannels.Contains(messageEvent.Channel))
                {
                    return(null);
                }

                string twitterHandle = arguments[1].Value;
                long   tweetId       = long.Parse(arguments[2].Value);
                var    client        = Twitter.GetTwitterClient();

                var tweet = client.Tweets.GetTweetAsync(tweetId).Result;

                return(FormatTweet(tweet, false).SplitInParts(430).ToList());
            }
Example #18
0
            public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
            {
                if (!arguments[1].Value.Contains(","))
                {
                    return(null);
                }
                string[] regions = arguments[1].Value.ToLower().Split(',');
                var      result  = new List <string>();

                foreach (var region in regions)
                {
                    GroupCollection newCollection =
                        new Regex(@"^coron\S+ (.+)$", RegexOptions.Compiled | RegexOptions.IgnoreCase).Match($"corona {region.TrimStart(' ').TrimEnd(' ')}").Groups;
                    result.Add(new GetCoronaRegionStats().RunCommand(messageEvent, newCollection, useCache)[0]);
                }

                return(result);
            }
Example #19
0
            public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
            {
                var enabledChannels = ConfigHelpers.LoadConfig <ChannelUriConfigModel>(ConfigHelpers.ConfigPaths.ChannelUriConfig).TwitterEnabledChannels;

                if (!enabledChannels.Contains(messageEvent.Channel))
                {
                    return(null);
                }

                Uri shortUri = new Uri(arguments[0].Value);
                Uri fullUri;

                using (HttpClient client = new HttpClient(new HttpClientHandler {
                    AllowAutoRedirect = false
                }))
                {
                    HttpRequestMessage headRequest = new HttpRequestMessage(HttpMethod.Head, shortUri);
                    headRequest.Headers.UserAgent.ParseAdd(
                        "curl/7.51.0");
                    headRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
                    headRequest.Headers.Host = "t.co";

                    HttpResponseMessage headResponse = client.SendAsync(headRequest).Result;

                    fullUri = headResponse.Headers.Location;
                }

                if (!fullUri.Host.Contains("twitter.com"))
                {
                    return($"URL: {fullUri.AbsoluteUri}".SplitInParts(430).ToList());
                }

                GroupCollection groups = new Regex(@"https?:\/\/twitter\.com\/(?:\#!\/)?(\w+)\/(?:status|statuses)\/(\d+)")
                                         .Match(fullUri.AbsoluteUri).Groups;

                long tweetId = long.Parse(groups[2].Value);

                var twitterClient = Twitter.GetTwitterClient();

                var tweet = twitterClient.Tweets.GetTweetAsync(tweetId).Result;

                return(FormatTweet(tweet).SplitInParts(430).ToList());
            }
Example #20
0
            public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
            {
                if (arguments == null || arguments.Count == 1)
                {
                    throw new ArgumentException("Not enough arguments");
                }

                bool shortQuery = arguments[0].Value.Substring(0, 2) == "ws";

                string query = arguments[1].Value;

                if (query.ToLower() == "goonyland")
                {
                    query = "Goteborg, Sweden";
                }

                WeatherApiConfigModel weatherApiConfig =
                    ConfigHelpers.LoadConfig <WeatherApiConfigModel>(ConfigHelpers.ConfigPaths.WeatherApiConfig);

                CurrentWeatherModel.CurrentWeather currentWeather;

                try
                {
                    currentWeather =
                        Weather.GetCurrentWeatherAsync(query, weatherApiConfig.ApiKey)
                        .Result;
                }
                catch (Exception e)
                {
                    if (e.InnerException is QueryNotFoundException)
                    {
                        return("Could not find given location.".SplitInParts(430).ToList());
                    }
                    throw;
                }



                return(FormatResponse.FormatWeatherResponse(currentWeather.Current, currentWeather.Location, shortWeather: shortQuery)
                       .SplitInParts(430)
                       //.Concat(FormatResponse.FormatForecastResponse(forecastWeather.Forecast, forecastWeather.Location, shortWeather: shortQuery))
                       .ToList());
            }
            public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
            {
                const string tickerName = "bitcoin-cash";
                TickerModel  ticker;

                try
                {
                    ticker = CoinMarketCapApi.Api.TickerApi.GetTicker(tickerName).Result[0];
                }
                catch (Exception e)
                {
                    if (e.InnerException is CoinMarketCapApi.Exceptions.TickerNotFoundException)
                    {
                        return("Ticker not found".SplitInParts(430).ToList());
                    }
                    throw;
                }

                return(CoinMarketCapHelpers.FormatTicker(ticker));
            }
Example #22
0
            public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
            {
                var screenName = arguments[1].Value;
                int index      = 1;

                if (arguments.Count == 3)
                {
                    index = int.Parse(arguments[2].Value);
                }

                if (index < 1)
                {
                    return("Try a number larger than 0".SplitInParts(430).ToList());
                }
                if (index > 200)
                {
                    return("Twitter limitations do not allow me to retrieve more than 200 tweets in a user timeline, sorry."
                           .SplitInParts(430).ToList());
                }

                if (screenName[0] == '@')
                {
                    screenName = screenName.TrimStart('@');
                }

                var tweets = Twitter.GetTwitterClient().Timelines.GetUserTimelineAsync(screenName).Result; // Default is 40 tweets

                if (tweets == null)
                {
                    return("Twitter user does not exist".SplitInParts(430).ToList());
                }

                if (!tweets.Any())
                {
                    return("No tweets from this user.".SplitInParts(430).ToList());
                }

                var tweet = tweets.ToList()[index - 1];

                return(FormatTweet(tweet).SplitInParts(430).ToList());
            }
            public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
            {
                List <CoinMarketSymbolCacheModel> symbolCache = Cache.Get <List <CoinMarketSymbolCacheModel> >("CoinMarketSymbolCache");

                if (symbolCache == null)
                {
                    // 0 means all in CoinMarketCap-land
                    List <TickerModel> symbolList = CoinMarketCapApi.Api.TickerApi.GetAllTickers(limit: 0).Result;

                    symbolCache = symbolList.Select(symbol =>
                                                    new CoinMarketSymbolCacheModel {
                        Name = symbol.TickerId, Symbol = symbol.Symbol
                    }).ToList();

                    Cache.Set("CoinMarketSymbolCache", symbolCache, DateTimeOffset.Now.AddDays(1));
                }

                string tickerName = symbolCache[new Random().Next(0, symbolCache.Count - 1)].Name;

                TickerModel ticker;

                try
                {
                    ticker = CoinMarketCapApi.Api.TickerApi.GetTicker(tickerName).Result[0];
                }
                catch (Exception e)
                {
                    if (e.InnerException is CoinMarketCapApi.Exceptions.TickerNotFoundException)
                    {
                        return("Ticker not found".SplitInParts(430).ToList());
                    }
                    throw;
                }

                return(CoinMarketCapHelpers.FormatTicker(ticker));
            }
            public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
            {
                List <CoinMarketSymbolCacheModel> symbolCache = Cache.Get <List <CoinMarketSymbolCacheModel> >("CoinMarketSymbolCache");

                if (symbolCache == null)
                {
                    // 0 means all in CoinMarketCap-land
                    List <TickerModel> symbolList = CoinMarketCapApi.Api.TickerApi.GetAllTickers(limit: 0).Result;

                    symbolCache = symbolList.Select(symbol =>
                                                    new CoinMarketSymbolCacheModel {
                        Name = symbol.TickerId, Symbol = symbol.Symbol
                    }).ToList();

                    Cache.Set("CoinMarketSymbolCache", symbolCache, DateTimeOffset.Now.AddDays(1));
                }

                var results = "";

                if (arguments == null || arguments.Count == 1)
                {
                    throw new ArgumentException("Not enough arguments");
                }

                Regex searchRegex;

                try
                {
                    searchRegex = new Regex(arguments[1].Value, RegexOptions.IgnoreCase);
                }
                catch (ArgumentException)
                {
                    return(new List <string> {
                        "Regex was invalid"
                    });
                }

                int matches = 0;

                foreach (var symbol in symbolCache)
                {
                    if (matches > 50)
                    {
                        results += "reached limit, search better moron";
                        break;
                    }
                    ;
                    if (searchRegex.Match(symbol.Name).Success || searchRegex.Match(symbol.Symbol).Success)
                    {
                        matches++;
                        results += $"{symbol.Name} ({symbol.Symbol}); ";
                    }
                }

                if (results == "")
                {
                    return("Lol no results".SplitInParts(430).ToList());
                }

                return(results.SplitInParts(430).ToList());
            }
Example #25
0
 public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
 {
     return(new List <string> {
         $"This is the low priority command, this should be third. Ticks: {DateTime.UtcNow.Ticks}"
     });
 }
Example #26
0
        public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
        {
            Random random = new Random(Guid.NewGuid().GetHashCode());

            int rolls = int.Parse(arguments[1].Value);

            if (rolls > 100)
            {
                return(new List <string> {
                    "Too many rolls!"
                });
            }
            int  dieSize       = int.Parse(arguments[2].Value);
            bool modifier      = false;
            bool subtract      = false;
            bool add           = false;
            int  modifierValue = 0;

            if (arguments.Count > 3)
            {
                modifier = true;
                if (arguments[3].Value == "+")
                {
                    add = true;
                }
                if (arguments[3].Value == "-")
                {
                    subtract = true;
                }
                if (!add && !subtract)
                {
                    return(new List <string> {
                        "Please provide a valid operator of either + or -"
                    });
                }
                modifierValue = int.Parse(arguments[4].Value);
            }

            if (dieSize <= 0)
            {
                return new List <string> {
                           "Die size needs to be greater than 0"
                }
            }
            ;

            if (rolls <= 0)
            {
                return new List <string> {
                           "There needs to be more than 0 rolls"
                }
            }
            ;

            List <int> rollResults = new List <int>(rolls);

            int i = 0;

            while (i < rolls)
            {
                var currentResult = random.Next(1, dieSize + 1);

                if (modifier)
                {
                    if (add)
                    {
                        currentResult += modifierValue;
                    }
                    if (subtract)
                    {
                        currentResult -= modifierValue;
                    }
                }

                rollResults.Add(currentResult);

                i++;
            }

            string result = $"{messageEvent.Nick}'s roll results:";

            result = rollResults.Aggregate(result, (current, roll) => current + $" {roll},");

            result += $" Rolled {rolls}d{dieSize}";
            if (!modifier)
            {
                return(result.SplitInParts().ToList());
            }

            if (add)
            {
                result += $" with a +{modifierValue} modifier";
            }
            if (subtract)
            {
                result += $" with a -{modifierValue} modifier";
            }

            return(result.SplitInParts().ToList());
        }
    }
}
Example #27
0
        public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null,
                                        bool useCache = true)
        {
            var           config          = ConfigHelpers.LoadConfig <ChannelUriConfigModel>(ConfigHelpers.ConfigPaths.ChannelUriConfig);
            List <string> enabledChannels = config.EnabledChannels;

            if (!enabledChannels.Contains(messageEvent.Channel))
            {
                return(null);
            }

            Uri matchedUri = new Uri(arguments[0].Value);

            string responseHtml;

            using (HttpClient client = new HttpClient(new HttpClientHandler {
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
            }))
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
                client.DefaultRequestHeaders.UserAgent.ParseAdd(config.UserAgent);
                client.MaxResponseContentBufferSize = 100000000;
                client.DefaultRequestHeaders.Add("X-PX-AUTHORIZATION", "3:e76c2ea8a77ff1c04948d6d2df6775c4c4cdf92d1fac1686385531addd70b72f:uIOIhredLiWowZ3z8uzCCa9P1FMWQlnfxsWR3YLwS0x6iMJzL1WfWXjjYiIra+vfW1A/gbgL1Lh8Lsy8u1yJTQ==:1000:OaDoummliEwwdJgN3ZDkqVGf2KfVBR31tQxllxT2zKyvgo8H/A6RD6EZQS5yzPjN3aAo5dZn7IhcKGHsWFgI7JrFEJ6zy6GwDpMqgbnIV5aBECIZy17VtZZzDe92YlIY9KMfxfZXHDFdTqk1xDf+rY96FTIzFUuvAy0w3dZcqbc=");

                HttpResponseMessage response = client.GetAsync(matchedUri).Result;

                var contentLength = response.Content.Headers.ContentLength ?? 0;
                var contentType   = response.Content.Headers.ContentType == null ? "text/html" : response.Content.Headers.ContentType.MediaType;

                if (contentType != "text/html" ||
                    contentLength > (100 * 1024 * 1024))
                {
                    GC.Collect(); // GC for some reason doesn't flush until next request
                    if (response.Content.Headers.ContentLength == null)
                    {
                        return(new List <string> {
                            $"[URL] {response.Content.Headers.ContentType?.MediaType};{response.Content.Headers.ContentType?.CharSet} No content length"
                        });
                    }
                    return(new List <string> {
                        $"[URL] {response.Content.Headers.ContentType?.MediaType};{response.Content.Headers.ContentType?.CharSet} {contentLength / 1024} KB"
                    });
                }

                if (response.IsSuccessStatusCode)
                {
                    responseHtml = response.Content.ReadAsStringAsync().Result;
                }
                else
                {
                    throw new Exception($"Bad HTTP status code, {response.StatusCode}");
                }
            }

            HtmlDocument document = new HtmlDocument();

            document.LoadHtml(responseHtml);

            if (matchedUri.Host.Contains("imgur"))
            {
                string imgurTitle = document.DocumentNode.ParseHtmlAttribute("//meta[@property=\"og:title\"]",
                                                                             "content", "og:title missing");
                if (document.DocumentNode.ParseHtmlAttribute("//meta[@property=\"og:type\"]", "content", "og:type missing").ToLower()
                    .Contains("video.other"))
                {
                    return(new List <string>
                    {
                        $"{imgurTitle} - {document.DocumentNode.ParseHtmlAttribute("//meta[@name=\"twitter:player:stream\"]", "content", "twitter:player:stream missing")}"
                    });
                }

                if (document.DocumentNode
                    .ParseHtmlAttribute("//meta[@property=\"og:type\"]", "content", "og:type missing").ToLower()
                    .Contains("article"))
                {
                    return(new List <string>
                    {
                        $"{imgurTitle} - {document.DocumentNode.ParseHtmlAttribute("//meta[@name=\"twitter:image\"]", "content", "twitter:image missing")}"
                    });
                }
            }

            var title = document.DocumentNode.ParseHtmlElement("//title");

            if (title == null)
            {
                return(null);
            }

            string description      = null;
            bool   fetchDescription = true;

            foreach (var domain in
                     config.DomainsToIgnoreDescriptions.Where(domain => matchedUri.Host.Contains(domain)))
            {
                fetchDescription = false;
            }

            if (fetchDescription)
            {
                description =
                    document.DocumentNode.ParseHtmlAttribute("//meta[@name=\"description\"]", "content",
                                                             "no description");

                var ogDescription = document.DocumentNode.ParseHtmlAttribute("//meta[@property=\"og:description\"]",
                                                                             "content", "no description");

                if (description == "no description" || ogDescription.Length > description.Length)
                {
                    description = ogDescription;
                }
            }

            DateTime?createTime = null;
            DateTime?modifyTime = null;

            if (config.AppendMetaDates)
            {
                createTime =
                    document.DocumentNode.ParseHtmlAttributeDateTime("//meta[@property=\"article:published_time\"]", "content") ??
                    document.DocumentNode.ParseHtmlAttributeDateTime("//meta[@name=\"article:published_time\"]", "content") ??
                    document.DocumentNode.ParseHtmlAttributeDateTime("//meta[@name=\"article.published\"]", "content") ??
                    document.DocumentNode.ParseHtmlAttributeDateTime("//meta[@itemprop=\"dateCreated\"]", "content") ??
                    document.DocumentNode.ParseHtmlAttributeDateTime("//meta[@itemprop=\"datePublished\"]", "content") ??
                    document.DocumentNode.ParseHtmlAttributeDateTime("//meta[@name=\"article.created\"]", "content");

                modifyTime =
                    document.DocumentNode.ParseHtmlAttributeDateTime("//meta[@property=\"article:modified_time\"]", "content") ??
                    document.DocumentNode.ParseHtmlAttributeDateTime("//meta[@name=\"article:modified_time\"]", "content") ??
                    document.DocumentNode.ParseHtmlAttributeDateTime("//meta[@itemprop=\"dateModified\"]", "content") ??
                    document.DocumentNode.ParseHtmlAttributeDateTime("//meta[@name=\"article.updated\"]", "content");
            }

            bool appendModifyTime = true;

            if (createTime != null)
            {
                title += $" (published {createTime.Humanize(false, DateTime.Now)}";
                if (modifyTime != null)
                {
                    if (modifyTime.Humanize(false, DateTime.Now) == createTime.Humanize(false, DateTime.Now))
                    {
                        title           += ")";
                        appendModifyTime = false;
                    }
                    else
                    {
                        title += ", ";
                    }
                }
                else
                {
                    title += ")";
                }
            }

            if (modifyTime != null && appendModifyTime)
            {
                title += $"modified {modifyTime.Humanize(false, DateTime.Now)})";
            }

            if (description == "no description")
            {
                description = null;
            }

            List <string> result = new List <string>
            {
                title
                .TrimStart(' ')
            };

            if (description != null && description != result[0])
            {
                result.Add(description.TrimStart(' ').Truncate(400));
            }

            return(result);
        }
Example #28
0
 public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
 {
     return(new List <string> {
         $"It's {DateTime.UtcNow.Year}!"
     });
 }
Example #29
0
 public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
 {
     return(new List <string> {
         $"It is {DateTime.UtcNow.ToLongDateString()} {DateTime.UtcNow.ToLongTimeString()} UTC according to the server clock."
     });
 }
Example #30
0
 public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
 {
     return(("R" + String.Concat(Enumerable.Repeat("Æ", new Random().Next(50, 450)))).SplitInParts(430).ToList());
 }