Esempio n. 1
0
        public string GetRandomCurrencyImage()
        {
            var rng = new KotocornRandom();
            var cur = _images.ImageUrls.Currency;

            return(cur[rng.Next(0, cur.Length)]);
        }
Esempio n. 2
0
        public Task <Quote> GetRandomQuoteByKeywordAsync(ulong guildId, string keyword)
        {
            var rng = new KotocornRandom();

            return(_set.Where(q => q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rng.Next())
                   .FirstOrDefaultAsync());
        }
Esempio n. 3
0
            public async Task NRoll([Remainder] string range)
            {
                int rolled;

                if (range.Contains("-"))
                {
                    var arr = range.Split('-')
                              .Take(2)
                              .Select(int.Parse)
                              .ToArray();
                    if (arr[0] > arr[1])
                    {
                        await ReplyErrorLocalized("second_larger_than_first").ConfigureAwait(false);

                        return;
                    }
                    rolled = new KotocornRandom().Next(arr[0], arr[1] + 1);
                }
                else
                {
                    rolled = new KotocornRandom().Next(0, int.Parse(range) + 1);
                }

                await ReplyConfirmLocalized("dice_rolled", Format.Bold(rolled.ToString())).ConfigureAwait(false);
            }
Esempio n. 4
0
        private async Task InternalHentai(IMessageChannel channel, string tag, bool noError)
        {
            var rng  = new KotocornRandom();
            var arr  = Enum.GetValues(typeof(DapiSearchType));
            var type = (DapiSearchType)arr.GetValue(new KotocornRandom().Next(2, arr.Length));
            ImageCacherObject img;

            try
            {
                img = await _service.DapiSearch(tag, type, Context.Guild?.Id, true).ConfigureAwait(false);
            }
            catch (TagBlacklistedException)
            {
                await ReplyErrorLocalized("blacklisted_tag").ConfigureAwait(false);

                return;
            }

            if (img == null)
            {
                if (!noError)
                {
                    await ReplyErrorLocalized("not_found").ConfigureAwait(false);
                }
                return;
            }

            await channel.EmbedAsync(new EmbedBuilder().WithOkColor()
                                     .WithImageUrl(img.FileUrl)
                                     .WithDescription($"[{GetText("tag")}: {tag}]({img})"))
            .ConfigureAwait(false);
        }
Esempio n. 5
0
        public SearchImageCacher()
        {
            _http = new HttpClient();
            _http.AddFakeHeaders();

            _log   = LogManager.GetCurrentClassLogger();
            _rng   = new KotocornRandom();
            _cache = new SortedSet <ImageCacherObject>();
        }
Esempio n. 6
0
        public Task <Quote> SearchQuoteKeywordTextAsync(ulong guildId, string keyword, string text)
        {
            var rngk = new KotocornRandom();

            return(_set.Where(q => q.Text.ContainsNoCase(text, StringComparison.OrdinalIgnoreCase) &&
                              q.GuildId == guildId && q.Keyword == keyword)
                   .OrderBy(q => rngk.Next())
                   .FirstOrDefaultAsync());
        }
Esempio n. 7
0
            private async Task InternalRoll(int num, bool ordered)
            {
                if (num < 1 || num > 30)
                {
                    await ReplyErrorLocalized("dice_invalid_number", 1, 30).ConfigureAwait(false);

                    return;
                }

                var rng = new KotocornRandom();

                var dice   = new List <Image <Rgba32> >(num);
                var values = new List <int>(num);

                for (var i = 0; i < num; i++)
                {
                    var randomNumber = rng.Next(1, 7);
                    var toInsert     = dice.Count;
                    if (ordered)
                    {
                        if (randomNumber == 6 || dice.Count == 0)
                        {
                            toInsert = 0;
                        }
                        else if (randomNumber != 1)
                        {
                            for (var j = 0; j < dice.Count; j++)
                            {
                                if (values[j] < randomNumber)
                                {
                                    toInsert = j;
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        toInsert = dice.Count;
                    }
                    dice.Insert(toInsert, GetDice(randomNumber));
                    values.Insert(toInsert, randomNumber);
                }

                var bitmap = dice.Merge();
                var ms     = new MemoryStream();

                bitmap.SaveAsPng(ms);
                ms.Position = 0;
                await Context.Channel.SendFileAsync(ms, "dice.png",
                                                    Context.User.Mention + " " +
                                                    GetText("dice_rolled_num", Format.Bold(values.Count.ToString())) +
                                                    " " + GetText("total_average",
                                                                  Format.Bold(values.Sum().ToString()),
                                                                  Format.Bold((values.Sum() / (1.0f * values.Count)).ToString("N2")))).ConfigureAwait(false);
            }
Esempio n. 8
0
            public async Task Place(PlaceType placeType, uint width = 0, uint height = 0)
            {
                var url = "";

                switch (placeType)
                {
                case PlaceType.Cage:
                    url = "http://www.placecage.com";
                    break;

                case PlaceType.Steven:
                    url = "http://www.stevensegallery.com";
                    break;

                case PlaceType.Beard:
                    url = "http://placebeard.it";
                    break;

                case PlaceType.Fill:
                    url = "http://www.fillmurray.com";
                    break;

                case PlaceType.Bear:
                    url = "https://www.placebear.com";
                    break;

                case PlaceType.Kitten:
                    url = "http://placekitten.com";
                    break;

                case PlaceType.Bacon:
                    url = "http://baconmockup.com";
                    break;

                case PlaceType.Xoart:
                    url = "http://xoart.link";
                    break;
                }
                var rng = new KotocornRandom();

                if (width <= 0 || width > 1000)
                {
                    width = (uint)rng.Next(250, 850);
                }

                if (height <= 0 || height > 1000)
                {
                    height = (uint)rng.Next(250, 850);
                }

                url += $"/{width}/{height}";

                await Context.Channel.SendMessageAsync(url).ConfigureAwait(false);
            }
Esempio n. 9
0
        public async Task Videocall(params IGuildUser[] users)
        {
            var allUsrs      = users.Append(Context.User);
            var allUsrsArray = allUsrs.ToArray();
            var str          = allUsrsArray.Aggregate("http://appear.in/", (current, usr) => current + Uri.EscapeUriString(usr.Username[0].ToString()));

            str += new KotocornRandom().Next();
            foreach (var usr in allUsrsArray)
            {
                await(await usr.GetOrCreateDMChannelAsync()).SendConfirmAsync(str).ConfigureAwait(false);
            }
        }
Esempio n. 10
0
        private async Task Start()
        {
            CurrentPhase = Phase.Running;
            if (_users.Count <= 1)
            {
                foreach (var user in _users)
                {
                    if (user.Bet > 0)
                    {
                        await _currency.AddAsync(user.UserId, "Race refund", user.Bet).ConfigureAwait(false);
                    }
                }

                var _sf = OnStartingFailed?.Invoke(this);
                CurrentPhase = Phase.Ended;
                return;
            }

            var _  = OnStarted?.Invoke(this);
            var _t = Task.Run(async() =>
            {
                var rng = new KotocornRandom();
                while (!_users.All(x => x.Progress >= 60))
                {
                    foreach (var user in _users)
                    {
                        user.Progress += rng.Next(1, 11);
                        if (user.Progress >= 60)
                        {
                            user.Progress = 60;
                        }
                    }

                    var finished = _users.Where(x => x.Progress >= 60 && !FinishedUsers.Contains(x))
                                   .Shuffle();

                    FinishedUsers.AddRange(finished);

                    var _ignore = OnStateUpdate?.Invoke(this);
                    await Task.Delay(2500).ConfigureAwait(false);
                }

                if (FinishedUsers[0].Bet > 0)
                {
                    await _currency.AddAsync(FinishedUsers[0].UserId, "Won a Race", FinishedUsers[0].Bet * (_users.Count - 1))
                    .ConfigureAwait(false);
                }

                var _ended = OnEnded?.Invoke(this);
            });
        }
Esempio n. 11
0
        public async Task Choose([Remainder] string list = null)
        {
            if (string.IsNullOrWhiteSpace(list))
            {
                return;
            }
            var listArr = list.Split(';');

            if (listArr.Length < 2)
            {
                return;
            }
            var rng = new KotocornRandom();
            await Context.Channel.SendConfirmAsync("🤔", listArr[rng.Next(0, listArr.Length)]).ConfigureAwait(false);
        }
Esempio n. 12
0
        public async Task InRole([Remainder] IRole role)
        {
            var rng       = new KotocornRandom();
            var usrs      = (await Context.Guild.GetUsersAsync()).ToArray();
            var roleUsers = usrs
                            .Where(u => u.RoleIds.Contains(role.Id))
                            .Select(u => u.ToString())
                            .ToArray();

            await Context.SendPaginatedConfirmAsync(0, (cur) =>
            {
                return(new EmbedBuilder().WithOkColor()
                       .WithTitle(Format.Bold(GetText("inrole_list", Format.Bold(role.Name))) + $" - {roleUsers.Length}")
                       .WithDescription(string.Join("\n", roleUsers.Skip(cur * 20).Take(20))));
            }, roleUsers.Length, 20).ConfigureAwait(false);
        }
Esempio n. 13
0
            private async Task InternallDndRoll(string arg, bool ordered)
            {
                Match match;

                if ((match = fudgeRegex.Match(arg)).Length != 0 &&
                    int.TryParse(match.Groups["n1"].ToString(), out int n1) &&
                    n1 > 0 && n1 < 500)
                {
                    var rng = new KotocornRandom();

                    var rolls = new List <char>();

                    for (int i = 0; i < n1; i++)
                    {
                        rolls.Add(_fateRolls[rng.Next(0, _fateRolls.Length)]);
                    }
                    var embed = new EmbedBuilder().WithOkColor().WithDescription(Context.User.Mention + " " + GetText("dice_rolled_num", Format.Bold(n1.ToString())))
                                .AddField(efb => efb.WithName(Format.Bold("Result"))
                                          .WithValue(string.Join(" ", rolls.Select(c => Format.Code($"[{c}]")))));
                    await Context.Channel.EmbedAsync(embed).ConfigureAwait(false);
                }
                else if ((match = dndRegex.Match(arg)).Length != 0)
                {
                    var rng = new KotocornRandom();
                    if (int.TryParse(match.Groups["n1"].ToString(), out n1) &&
                        int.TryParse(match.Groups["n2"].ToString(), out int n2) &&
                        n1 <= 50 && n2 <= 100000 && n1 > 0 && n2 > 0)
                    {
                        int.TryParse(match.Groups["add"].Value, out int add);
                        int.TryParse(match.Groups["sub"].Value, out int sub);

                        var arr = new int[n1];
                        for (int i = 0; i < n1; i++)
                        {
                            arr[i] = rng.Next(1, n2 + 1);
                        }

                        var sum   = arr.Sum();
                        var embed = new EmbedBuilder().WithOkColor().WithDescription(Context.User.Mention + " " + GetText("dice_rolled_num", n1) + $"`1 - {n2}`")
                                    .AddField(efb => efb.WithName(Format.Bold("Rolls"))
                                              .WithValue(string.Join(" ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => Format.Code(x.ToString())))))
                                    .AddField(efb => efb.WithName(Format.Bold("Sum"))
                                              .WithValue(sum + " + " + add + " - " + sub + " = " + (sum + add - sub)));
                        await Context.Channel.EmbedAsync(embed).ConfigureAwait(false);
                    }
                }
            }
Esempio n. 14
0
        //[KotocornCommand, Usage, Description, Aliases]
        //[OwnerOnly]
        //public Task BrTest(int tests = 1000)
        //{
        //    var t = Task.Run(async () =>
        //    {
        //        if (tests <= 0)
        //            return;
        //        //multi vs how many times it occured
        //        var dict = new Dictionary<int, int>();
        //        var generator = new KotocornRandom();
        //        for (int i = 0; i < tests; i++)
        //        {
        //            var rng = generator.Next(0, 101);
        //            var mult = 0;
        //            if (rng < 67)
        //            {
        //                mult = 0;
        //            }
        //            else if (rng < 91)
        //            {
        //                mult = 2;
        //            }
        //            else if (rng < 100)
        //            {
        //                mult = 4;
        //            }
        //            else
        //                mult = 10;

        //            if (dict.ContainsKey(mult))
        //                dict[mult] += 1;
        //            else
        //                dict.Add(mult, 1);
        //        }

        //        var sb = new StringBuilder();
        //        const int bet = 1;
        //        int payout = 0;
        //        foreach (var key in dict.Keys.OrderByDescending(x => x))
        //        {
        //            sb.AppendLine($"x{key} occured {dict[key]} times. {dict[key] * 1.0f / tests * 100}%");
        //            payout += key * dict[key];
        //        }
        //        try
        //        {
        //            await Context.Channel.SendConfirmAsync("BetRoll Test Results", sb.ToString(),
        //                footer: $"Total Bet: {tests * bet} | Payout: {payout * bet} | {payout * 1.0f / tests * 100}%");
        //        }
        //        catch { }

        //    });
        //    return Task.CompletedTask;
        //}

        private async Task InternallBetroll(long amount)
        {
            if (!await CheckBetMandatory(amount))
            {
                return;
            }

            if (!await _cs.RemoveAsync(Context.User, "Betroll Gamble", amount, false, gamble: true).ConfigureAwait(false))
            {
                await ReplyErrorLocalized("not_enough", CurrencyPluralName).ConfigureAwait(false);

                return;
            }

            var rnd = new KotocornRandom().Next(0, 101);
            var str = Format.Bold(Context.User.ToString()) + Format.Code(GetText("roll", rnd));

            if (rnd < 67)
            {
                str += GetText("better_luck");
            }
            else
            {
                if (rnd < 91)
                {
                    str += GetText("br_win", (amount * _bc.BotConfig.Betroll67Multiplier) + CurrencySign, 66);
                    await _cs.AddAsync(Context.User, "Betroll Gamble",
                                       (int)(amount *_bc.BotConfig.Betroll67Multiplier), false, gamble : true).ConfigureAwait(false);
                }
                else if (rnd < 100)
                {
                    str += GetText("br_win", (amount * _bc.BotConfig.Betroll91Multiplier) + CurrencySign, 90);
                    await _cs.AddAsync(Context.User, "Betroll Gamble",
                                       (int)(amount *_bc.BotConfig.Betroll91Multiplier), false, gamble : true).ConfigureAwait(false);
                }
                else
                {
                    str += GetText("br_win", (amount * _bc.BotConfig.Betroll100Multiplier) + CurrencySign, 99) + " 👑";
                    await _cs.AddAsync(Context.User, "Betroll Gamble",
                                       (int)(amount *_bc.BotConfig.Betroll100Multiplier), false, gamble : true).ConfigureAwait(false);
                }
            }
            await Context.Channel.SendConfirmAsync(str).ConfigureAwait(false);
        }
Esempio n. 15
0
            public async Task Roll()
            {
                var rng = new KotocornRandom();
                var gen = rng.Next(1, 101);

                var num1        = gen / 10;
                var num2        = gen % 10;
                var imageStream = await Task.Run(() =>
                {
                    var ms = new MemoryStream();
                    new[] { GetDice(num1), GetDice(num2) }.Merge().SaveAsPng(ms);
                    ms.Position = 0;
                    return(ms);
                }).ConfigureAwait(false);

                await Context.Channel.SendFileAsync(imageStream,
                                                    "dice.png",
                                                    Context.User.Mention + " " + GetText("dice_rolled", Format.Code(gen.ToString()))).ConfigureAwait(false);
            }
Esempio n. 16
0
                public static SlotResult Pull()
                {
                    var numbers = new int[3];

                    for (var i = 0; i < numbers.Length; i++)
                    {
                        numbers[i] = new KotocornRandom().Next(0, MaxValue + 1);
                    }
                    var multi = 0;

                    foreach (var t in _winningCombos)
                    {
                        multi = t(numbers);
                        if (multi != 0)
                        {
                            break;
                        }
                    }

                    return(new SlotResult(numbers, multi));
                }
Esempio n. 17
0
        public HangmanObject GetTerm(string type)
        {
            type = type?.Trim().ToLowerInvariant();
            var rng = new KotocornRandom();

            if (type == "random")
            {
                var keys = Data.Keys.ToArray();

                type = Data.Keys.ToArray()[rng.Next(0, Data.Keys.Count())];
            }
            if (!Data.TryGetValue(type, out var termTypes) || termTypes.Length == 0)
            {
                throw new TermNotFoundException();
            }

            var obj = termTypes[rng.Next(0, termTypes.Length)];

            obj.Word = obj.Word.Trim().ToLowerInvariant();
            return(obj);
        }
Esempio n. 18
0
        public GamesService(CommandHandler cmd, IBotConfigProvider bc, Kotocorn bot,
                            KotocornStrings strings, IDataCache data, CommandHandler cmdHandler,
                            ICurrencyService cs)
        {
            _bc         = bc;
            _cmd        = cmd;
            _strings    = strings;
            _images     = data.LocalImages;
            _cmdHandler = cmdHandler;
            _log        = LogManager.GetCurrentClassLogger();
            _rng        = new KotocornRandom();
            _cs         = cs;

            //8ball
            EightBallResponses = _bc.BotConfig.EightBallResponses.Select(ebr => ebr.Text).ToImmutableArray();

            //girl ratings
            _t = new Timer((_) =>
            {
                GirlRatings.Clear();
            }, null, TimeSpan.FromDays(1), TimeSpan.FromDays(1));

            //plantpick
            _cmd.OnMessageNoTrigger += PotentialFlowerGeneration;
            GenerationChannels       = new ConcurrentHashSet <ulong>(bot
                                                                     .AllGuildConfigs
                                                                     .SelectMany(c => c.GenerateCurrencyChannelIds.Select(obj => obj.ChannelId)));

            try
            {
                TypingArticles = JsonConvert.DeserializeObject <List <TypingArticle> >(File.ReadAllText(TypingArticlesPath));
            }
            catch (Exception ex)
            {
                _log.Warn("Error while loading typing articles {0}", ex.ToString());
                TypingArticles = new List <TypingArticle>();
            }
        }
Esempio n. 19
0
        public User GetWinner()
        {
            var rng = new KotocornRandom();

            if (GameType == Type.Mixed)
            {
                var num = rng.NextLong(0L, Users.Sum(x => x.Amount));
                var sum = 0L;
                foreach (var u in Users)
                {
                    sum += u.Amount;
                    if (sum > num)
                    {
                        return(u);
                    }
                }
                _log.Error("Woah. Report this.\nRoll: {0}\nAmounts: {1}", num, string.Join(",", Users.Select(x => x.Amount)));
            }

            var usrs = _users.ToArray();

            return(usrs[rng.Next(0, usrs.Length)]);
        }
Esempio n. 20
0
        public ReplacementBuilder WithRngRegex()
        {
            var rng = new KotocornRandom();

            _regex.TryAdd(rngRegex, (match) =>
            {
                int.TryParse(match.Groups["from"].ToString(), out var from);
                int.TryParse(match.Groups["to"].ToString(), out var to);

                if (from == 0 && to == 0)
                {
                    return(rng.Next(0, 11).ToString());
                }

                if (from >= to)
                {
                    return(string.Empty);
                }

                return(rng.Next(from, to + 1).ToString());
            });
            return(this);
        }
Esempio n. 21
0
        public async Task WhosPlaying([Remainder] string game)
        {
            game = game?.Trim().ToUpperInvariant();
            if (string.IsNullOrWhiteSpace(game))
            {
                return;
            }

            var socketGuild = Context.Guild as SocketGuild;

            if (socketGuild == null)
            {
                _log.Warn("Can't cast guild to socket guild.");
                return;
            }
            var rng = new KotocornRandom();
            var arr = await Task.Run(() => socketGuild.Users
                                     .Where(u => u.Activity?.Name?.ToUpperInvariant() == game)
                                     .Select(u => u.Username)
                                     .OrderBy(x => rng.Next())
                                     .Take(60)
                                     .ToArray()).ConfigureAwait(false);

            int i = 0;

            if (arr.Length == 0)
            {
                await ReplyErrorLocalized("nobody_playing_game").ConfigureAwait(false);
            }
            else
            {
                await Context.Channel.SendConfirmAsync("```css\n" + string.Join("\n", arr.GroupBy(item => (i++) / 2)
                                                                                .Select(ig => string.Concat(ig.Select(el => $"• {el,-27}")))) + "\n```")
                .ConfigureAwait(false);
            }
        }
Esempio n. 22
0
            public async Task WaifuInfo([Remainder] IGuildUser target = null)
            {
                if (target == null)
                {
                    target = (IGuildUser)Context.User;
                }
                WaifuInfo         w;
                IList <WaifuInfo> claims;
                int divorces;

                using (var uow = _db.UnitOfWork)
                {
                    w        = uow.Waifus.ByWaifuUserId(target.Id);
                    claims   = uow.Waifus.ByClaimerUserId(target.Id);
                    divorces = uow._context.WaifuUpdates.Count(x => x.Old != null &&
                                                               x.Old.UserId == target.Id &&
                                                               x.UpdateType == WaifuUpdateType.Claimed &&
                                                               x.New == null);
                    if (w == null)
                    {
                        uow.Waifus.Add(w = new WaifuInfo()
                        {
                            Affinity = null,
                            Claimer  = null,
                            Price    = 1,
                            Waifu    = uow.DiscordUsers.GetOrCreate(target),
                        });
                    }

                    w.Waifu.Username      = target.Username;
                    w.Waifu.Discriminator = target.Discriminator;
                    await uow.CompleteAsync().ConfigureAwait(false);
                }

                var claimInfo = GetClaimTitle(target.Id);
                var affInfo   = GetAffinityTitle(target.Id);

                var rng = new KotocornRandom();

                var nobody   = GetText("nobody");
                var i        = 0;
                var itemsStr = !w.Items.Any()
                    ? "-"
                    : string.Join("\n", w.Items
                                  .OrderBy(x => x.Price)
                                  .GroupBy(x => x.ItemEmoji)
                                  .Select(x => $"{x.Key} x{x.Count(),-3}")
                                  .GroupBy(x => i++ / 2)
                                  .Select(x => string.Join(" ", x)));


                var embed = new EmbedBuilder()
                            .WithOkColor()
                            .WithTitle("Waifu " + w.Waifu + " - \"the " + claimInfo.Title + "\"")
                            .AddField(efb => efb.WithName(GetText("price")).WithValue(w.Price.ToString()).WithIsInline(true))
                            .AddField(efb => efb.WithName(GetText("claimed_by")).WithValue(w.Claimer?.ToString() ?? nobody).WithIsInline(true))
                            .AddField(efb => efb.WithName(GetText("likes")).WithValue(w.Affinity?.ToString() ?? nobody).WithIsInline(true))
                            .AddField(efb => efb.WithName(GetText("changes_of_heart")).WithValue($"{affInfo.Count} - \"the {affInfo.Title}\"").WithIsInline(true))
                            .AddField(efb => efb.WithName(GetText("divorces")).WithValue(divorces.ToString()).WithIsInline(true))
                            .AddField(efb => efb.WithName(GetText("gifts")).WithValue(itemsStr).WithIsInline(false))
                            .AddField(efb => efb.WithName($"Waifus ({claims.Count})").WithValue(claims.Count == 0 ? nobody : string.Join("\n", claims.OrderBy(x => rng.Next()).Take(30).Select(x => x.Waifu))).WithIsInline(false));

                await Context.Channel.EmbedAsync(embed).ConfigureAwait(false);
            }
Esempio n. 23
0
        public BotCredentials()
        {
            _log = LogManager.GetCurrentClassLogger();

            try { File.WriteAllText("./credentials_example.json", JsonConvert.SerializeObject(new CredentialsModel(), Formatting.Indented)); } catch { }
            if (!File.Exists(_credsFileName))
            {
                _log.Warn($"credentials.json is missing. Attempting to load creds from environment variables prefixed with 'Kotocorn_'. Example is in {Path.GetFullPath("./credentials_example.json")}");
            }
            try
            {
                var configBuilder = new ConfigurationBuilder();
                configBuilder.AddJsonFile(_credsFileName, true)
                .AddEnvironmentVariables("Kotocorn_");

                var data = configBuilder.Build();

                Token = data[nameof(Token)];
                if (string.IsNullOrWhiteSpace(Token))
                {
                    _log.Error("Token is missing from credentials.json or Environment varibles. Add it and restart the program.");
                    Console.ReadKey();
                    Environment.Exit(3);
                }
                OwnerIds           = data.GetSection("OwnerIds").GetChildren().Select(c => ulong.Parse(c.Value)).ToImmutableArray();
                LoLApiKey          = data[nameof(LoLApiKey)];
                GoogleApiKey       = data[nameof(GoogleApiKey)];
                MashapeKey         = data[nameof(MashapeKey)];
                OsuApiKey          = data[nameof(OsuApiKey)];
                PatreonAccessToken = data[nameof(PatreonAccessToken)];
                PatreonCampaignId  = data[nameof(PatreonCampaignId)] ?? "334038";
                ShardRunCommand    = data[nameof(ShardRunCommand)];
                ShardRunArguments  = data[nameof(ShardRunArguments)];
                CleverbotApiKey    = data[nameof(CleverbotApiKey)];
                MiningProxyUrl     = data[nameof(MiningProxyUrl)];
                MiningProxyCreds   = data[nameof(MiningProxyCreds)];

                VotesToken   = data[nameof(VotesToken)];
                VotesUrl     = data[nameof(VotesUrl)];
                BotListToken = data[nameof(BotListToken)];

                var restartSection = data.GetSection(nameof(RestartCommand));
                var cmd            = restartSection["cmd"];
                var args           = restartSection["args"];
                if (!string.IsNullOrWhiteSpace(cmd))
                {
                    RestartCommand = new RestartConfig(cmd, args);
                }

                if (Environment.OSVersion.Platform == PlatformID.Unix)
                {
                    if (string.IsNullOrWhiteSpace(ShardRunCommand))
                    {
                        ShardRunCommand = "dotnet";
                    }
                    if (string.IsNullOrWhiteSpace(ShardRunArguments))
                    {
                        ShardRunArguments = "run -c Release -- {0} {1}";
                    }
                }
                else //windows
                {
                    if (string.IsNullOrWhiteSpace(ShardRunCommand))
                    {
                        ShardRunCommand = "Kotocorn.exe";
                    }
                    if (string.IsNullOrWhiteSpace(ShardRunArguments))
                    {
                        ShardRunArguments = "{0} {1}";
                    }
                }

                var portStr = data[nameof(ShardRunPort)];
                if (string.IsNullOrWhiteSpace(portStr))
                {
                    ShardRunPort = new KotocornRandom().Next(5000, 6000);
                }
                else
                {
                    ShardRunPort = int.Parse(portStr);
                }

                int.TryParse(data[nameof(TotalShards)], out var ts);
                TotalShards = ts < 1 ? 1 : ts;

                ulong.TryParse(data[nameof(ClientId)], out ulong clId);
                ClientId = clId;

                CarbonKey = data[nameof(CarbonKey)];
                var dbSection = data.GetSection("db");
                Db = new DBConfig(string.IsNullOrWhiteSpace(dbSection["Type"])
                                ? "sqlite"
                                : dbSection["Type"],
                                  string.IsNullOrWhiteSpace(dbSection["ConnectionString"])
                                ? "Data Source=data/Kotocorn.db"
                                : dbSection["ConnectionString"]);

                TwitchClientId = data[nameof(TwitchClientId)];
                if (string.IsNullOrWhiteSpace(TwitchClientId))
                {
                    TwitchClientId = "67w6z9i09xv2uoojdm9l0wsyph4hxo6";
                }
            }
            catch (Exception ex)
            {
                _log.Fatal(ex.Message);
                _log.Fatal(ex);
                throw;
            }
        }
Esempio n. 24
0
 public Acrophobia(Options options)
 {
     Opts = options;
     _rng = new KotocornRandom();
     InitializeStartingLetters();
 }
Esempio n. 25
0
        private GirlRating GetGirl(ulong uid)
        {
            var rng = new KotocornRandom();

            var roll = rng.Next(1, 1001);

            if ((uid == 185968432783687681 ||
                 uid == 265642040950390784) && roll >= 900)
            {
                roll = 1000;
            }


            double hot;
            double crazy;
            string advice;

            if (roll < 500)
            {
                hot    = NextDouble(0, 5);
                crazy  = NextDouble(4, 10);
                advice =
                    "This is your NO-GO ZONE. We do not hang around, and date, and marry women who are at least, in our mind, a 5. " +
                    "So, this is your no-go zone. You don't go here. You just rule this out. Life is better this way, that's the way it is.";
            }
            else if (roll < 750)
            {
                hot    = NextDouble(5, 8);
                crazy  = NextDouble(4, .6 * hot + 4);
                advice = "Above a 5, and to about an 8, and below the crazy line - this is your FUN ZONE. You can " +
                         "hang around here, and meet these girls and spend time with them. Keep in mind, while you're " +
                         "in the fun zone, you want to move OUT of the fun zone to a more permanent location. " +
                         "These girls are most of the time not crazy.";
            }
            else if (roll < 900)
            {
                hot    = NextDouble(5, 10);
                crazy  = NextDouble(.61 * hot + 4, 10);
                advice = "Above the crazy line - it's the DANGER ZONE. This is redheads, strippers, anyone named Tiffany, " +
                         "hairdressers... This is where your car gets keyed, you get bunny in the pot, your tires get slashed, " +
                         "and you wind up in jail.";
            }
            else if (roll < 951)
            {
                hot    = NextDouble(8, 10);
                crazy  = NextDouble(7, .6 * hot + 4);
                advice = "Below the crazy line, above an 8 hot, but still about 7 crazy. This is your DATE ZONE. " +
                         "You can stay in the date zone indefinitely. These are the girls you introduce to your friends and your family. " +
                         "They're good looking, and they're reasonably not crazy most of the time. You can stay here indefinitely.";
            }
            else if (roll < 990)
            {
                hot    = NextDouble(8, 10);
                crazy  = NextDouble(5, 7);
                advice = "Above an 8 hot, and between about 7 and a 5 crazy - this is WIFE ZONE. If you meet this girl, you should consider long-term " +
                         "relationship. Rare.";
            }
            else if (roll < 999)
            {
                hot    = NextDouble(8, 10);
                crazy  = NextDouble(2, 3.99d);
                advice = "You've met a girl she's above 8 hot, and not crazy at all (below 4)... totally cool?" +
                         " You should be careful. That's a dude. You're talking to a tranny!";
            }
            else
            {
                hot    = NextDouble(8, 10);
                crazy  = NextDouble(4, 5);
                advice = "Below 5 crazy, and above 8 hot, this is the UNICORN ZONE, these things don't exist." +
                         "If you find a unicorn, please capture it safely, keep it alive, we'd like to study it, " +
                         "and maybe look at how to replicate that.";
            }

            return(new GirlRating(_images, crazy, hot, roll, advice));
        }
Esempio n. 26
0
        private Task PotentialFlowerGeneration(IUserMessage imsg)
        {
            var msg = imsg as SocketUserMessage;

            if (msg == null || msg.Author.IsBot)
            {
                return(Task.CompletedTask);
            }

            var channel = imsg.Channel as ITextChannel;

            if (channel == null)
            {
                return(Task.CompletedTask);
            }

            if (!GenerationChannels.Contains(channel.Id))
            {
                return(Task.CompletedTask);
            }

            var _ = Task.Run(async() =>
            {
                try
                {
                    var lastGeneration = LastGenerations.GetOrAdd(channel.Id, DateTime.MinValue);
                    var rng            = new KotocornRandom();

                    if (DateTime.UtcNow - TimeSpan.FromSeconds(_bc.BotConfig.CurrencyGenerationCooldown) < lastGeneration) //recently generated in this channel, don't generate again
                    {
                        return;
                    }

                    var num = rng.Next(1, 101) + _bc.BotConfig.CurrencyGenerationChance * 100;
                    if (num > 100 && LastGenerations.TryUpdate(channel.Id, DateTime.UtcNow, lastGeneration))
                    {
                        var dropAmount    = _bc.BotConfig.CurrencyDropAmount;
                        var dropAmountMax = _bc.BotConfig.CurrencyDropAmountMax;

                        if (dropAmountMax != null && dropAmountMax > dropAmount)
                        {
                            dropAmount = new KotocornRandom().Next(dropAmount, dropAmountMax.Value + 1);
                        }

                        if (dropAmount > 0)
                        {
                            var msgs   = new IUserMessage[dropAmount];
                            var prefix = _cmdHandler.GetPrefix(channel.Guild.Id);
                            var toSend = dropAmount == 1
                                ? GetText(channel, "curgen_sn", _bc.BotConfig.CurrencySign)
                                         + " " + GetText(channel, "pick_sn", prefix)
                                : GetText(channel, "curgen_pl", dropAmount, _bc.BotConfig.CurrencySign)
                                         + " " + GetText(channel, "pick_pl", prefix);
                            var file = GetRandomCurrencyImage();

                            var sent = await channel.EmbedAsync(new EmbedBuilder()
                                                                .WithOkColor()
                                                                .WithDescription(toSend)
                                                                .WithImageUrl(file));

                            msgs[0] = sent;

                            PlantedFlowers.AddOrUpdate(channel.Id, msgs.ToList(), (id, old) => { old.AddRange(msgs); return(old); });
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogManager.GetCurrentClassLogger().Warn(ex);
                }
            });

            return(Task.CompletedTask);
        }