public static Weightable <T> GetRandomWeightedValue <T>(this IList <Weightable <T> > items) { if (items == null || items.Count == 0) { return(null); } var randomWeight = SkuldRandom.Next(items.Sum(x => x.Weight)); Weightable <T> item = null; foreach (var entry in items) { item = entry; randomWeight -= entry.Weight; if (randomWeight <= 0) { break; } } return(item); }
public static Color RandomEmbedColor() { var bytes = new byte[3]; SkuldRandom.Fill(bytes); return(new Color(bytes[0], bytes[1], bytes[2])); }
public async Task <XKCDComic> GetRandomComicAsync() { if (!XKCDLastPage.HasValue) { XKCDLastPage = await GetLastPageAsync().ConfigureAwait(false); } if (rateLimiter.IsRatelimited()) { return(null); } return(await GetComicAsync(SkuldRandom.Next(0, XKCDLastPage.Value)).ConfigureAwait(false)); }
public async Task <GiphyGif> GetGifAsync(string query) { if (rateLimiter.IsRatelimited()) { return(null); } query = query.Replace(" ", "%20"); var rawresp = await HttpWebClient.ReturnStringAsync(new Uri($"https://api.giphy.com/v1/gifs/search?q={query}&api_key=dc6zaTOxFJmzC")).ConfigureAwait(false); var jsonresp = JObject.Parse(rawresp); var photo = (JArray)jsonresp["data"]; dynamic item = photo[SkuldRandom.Next(0, photo.Count)]; return(new GiphyGif { ID = item["id"].ToString() }); }
async static Task UpdateStatusAsync( DiscordSocketClient client ) { Tuple <string, ActivityType> pickedStatus = Statuses.RandomValue(); string replacedString = pickedStatus.Item1 .Replace("{{PREFIX}}", SkuldApp.Configuration.Prefix) .Replace("{{SHARDID}}", (client.ShardId + 1).ToFormattedString()) .Replace("{{SHARDCOUNT}}", SkuldApp.DiscordClient.Shards.Count.ToFormattedString()) .Replace("{{TOTALSERVERCOUNT}}", SkuldApp.DiscordClient.Guilds.Count.ToFormattedString()); await client .SetGameAsync( replacedString, type : pickedStatus.Item2 ).ConfigureAwait(false); await Task.Delay(SkuldRandom.Next(300, 600) * 1000).ConfigureAwait(false); await UpdateStatusAsync(client).ConfigureAwait(false); }
public async Task Slots(ulong bet) { if (bet <= 0) { await EmbedExtensions.FromError("Slots", $"Can't bet 0", Context).QueueMessageAsync(Context).ConfigureAwait(false); return; } using var Database = new SkuldDbContextFactory().CreateDbContext(); var user = await Database.InsertOrGetUserAsync(Context.User).ConfigureAwait(false); string MoneyPrefix = SkuldApp.MessageServiceConfig.MoneyIcon; if (!Context.IsPrivate) { var guild = await Database.InsertOrGetGuildAsync(Context.Guild).ConfigureAwait(false); MoneyPrefix = guild.MoneyIcon; } { if (!IsValidBet(bet)) { await EmbedExtensions.FromError("Slots", $"You have not specified a valid bet, minimum is {MoneyPrefix}{MinimumBet.ToFormattedString()}", Context).QueueMessageAsync(Context).ConfigureAwait(false); return; } if (user.Money < bet) { await EmbedExtensions.FromError("Slots", $"You don't have enough money available to make that bet, you have {MoneyPrefix}{user.Money.ToFormattedString()} available", Context).QueueMessageAsync(Context).ConfigureAwait(false); return; } TransactionService.DoTransaction(new TransactionStruct { Amount = bet, Sender = user }).Then(async _ => { await Database.SaveChangesAsync().ConfigureAwait(false); }); } var rows = GetSlotsRows(); var middleRow = rows[1]; var stringRow = GetStringRows(rows); var message = await EmbedExtensions.FromInfo("Slots", "Please Wait, Calculating Wheels", Context).QueueMessageAsync(Context).ConfigureAwait(false); await Task.Delay(500).ConfigureAwait(false); double percentageMod = 0.0d; percentageMod = GetPercentageModifier(percentageMod, middleRow, SlotIcon.Cherry, .5d, 1d); percentageMod = GetPercentageModifier(percentageMod, middleRow, SlotIcon.Lemon, .8d, 1.5d); percentageMod = GetPercentageModifier(percentageMod, middleRow, SlotIcon.Melon, 1d, 2d); percentageMod = GetPercentageModifier(percentageMod, middleRow, SlotIcon.Bell, 1d, 4d); percentageMod = GetPercentageModifier(percentageMod, middleRow, SlotIcon.Crown, 1.2d, 6d); percentageMod = GetPercentageModifier(percentageMod, middleRow, SlotIcon.Diamond, 1.5d, 10d); percentageMod = GetPercentageModifier(percentageMod, middleRow, SlotIcon.Star, 2d, 12d); await Task.Delay(SkuldRandom.Next(50, 300)).ConfigureAwait(false); if (percentageMod == 0.0d) { await message.ModifyAsync(x => { x.Embed = EmbedExtensions.FromMessage( "Slots", $"{stringRow}\n\n" + $"You lost {bet.ToFormattedString()}! " + $"You now have {MoneyPrefix}`{user.Money}`", Color.Red, Context ).Build(); }).ConfigureAwait(false); } else { var amount = (ulong)Math.Round(bet * percentageMod); TransactionService.DoTransaction(new TransactionStruct { Amount = amount, Receiver = user }) .Then(async _ => { await Database.SaveChangesAsync().ConfigureAwait(false); await message.ModifyAsync(x => x.Embed = EmbedExtensions.FromMessage("Slots", $"{stringRow}\n\nYou won {amount.ToFormattedString()}! You now have {MoneyPrefix}`{user.Money}`", Color.Green, Context).Build()).ConfigureAwait(false); }); } }
public async Task HeadsOrTails(string guess, ulong bet) { using var Database = new SkuldDbContextFactory().CreateDbContext(); var user = await Database.InsertOrGetUserAsync(Context.User).ConfigureAwait(false); string MoneyPrefix = SkuldApp.MessageServiceConfig.MoneyIcon; string Prefix = SkuldApp.MessageServiceConfig.Prefix; if (!Context.IsPrivate) { var guild = await Database.InsertOrGetGuildAsync(Context.Guild).ConfigureAwait(false); MoneyPrefix = guild.MoneyIcon; Prefix = guild.Prefix; } if (!IsValidBet(bet)) { await EmbedExtensions.FromError("Heads Or Tails", $"You have not specified a valid bet, minimum is {MoneyPrefix}{MinimumBet.ToFormattedString()}", Context).QueueMessageAsync(Context).ConfigureAwait(false); return; } if (user.Money < bet) { await EmbedExtensions.FromError("Heads Or Tails", $"You don't have enough money available to make that bet, you have {MoneyPrefix}{user.Money.ToFormattedString()} available", Context).QueueMessageAsync(Context).ConfigureAwait(false); return; } TransactionService.DoTransaction(new TransactionStruct { Amount = bet, Sender = user }); await Database.SaveChangesAsync().ConfigureAwait(false); var result = SkuldRandom.Next(0, coinflip.Count); var loweredGuess = guess.ToLowerInvariant(); switch (loweredGuess) { case "heads": case "head": case "h": case "tails": case "tail": case "t": { bool playerguess = loweredGuess == "heads" || loweredGuess == "head"; var res = (coinflip.Keys.ElementAt(result), coinflip.Values.ElementAt(result)); bool didWin = false; if (result == 0 && playerguess) { didWin = true; } else if (result == 1 && !playerguess) { didWin = true; } string suffix; if (didWin) { TransactionService.DoTransaction(new TransactionStruct { Amount = bet * 2, Receiver = user }); } if (didWin) { suffix = $"You Won! <:blobsquish:350681075296501760> Your money is now {MoneyPrefix}`{user.Money.ToFormattedString()}`"; } else { suffix = $"You Lost! <:blobcrying:662304318531305492> Your money is now {MoneyPrefix}`{user.Money.ToFormattedString()}`"; } await Database.SaveChangesAsync().ConfigureAwait(false); await EmbedExtensions .FromImage(res.Item2, didWin?Color.Green : Color.Red, Context) .WithTitle("Heads Or Tails") .WithDescription($"Result are: {Locale.GetLocale(user.Language).GetString(res.Item1)} {suffix}") .QueueMessageAsync(Context) .ConfigureAwait(false); } break; default: await EmbedExtensions.FromError("Heads Or Tails", $"Incorrect guess value. Try; `{Prefix}flip heads`", Context).QueueMessageAsync(Context).ConfigureAwait(false); return; } }
/// <summary> /// Grab a cryptographically random element from a collection /// </summary> /// <typeparam name="T">Anything</typeparam> /// <param name="source">Source collection</param> /// <returns>Anything within the list</returns> public static T CryptoRandom <T>(this IEnumerable <T> source) => source.ElementAtOrDefault(SkuldRandom.Next(0, source.Count()));
public static async Task <Embed> GetEmbedAsync(this PokemonSpecies pokemon, PokemonDataGroup group) { if (pokemon == null) { return(null); } var poke = await DataFetcher.GetApiObject <Pokemon>(pokemon.ID).ConfigureAwait(false); var embed = new EmbedBuilder { Author = new EmbedAuthorBuilder { Name = $"{char.ToUpperInvariant(pokemon.Name[0])}{pokemon.Name.Substring(1)} - {pokemon.ID}" }, Color = Color.Blue }; var result = SkuldRandom.Next(0, 8193); string sprite = null; //if it equals 8 out of a random integer between 1 and 8192 then give shiny if (result == 8) { sprite = poke.Sprites.FrontShinyMale ?? poke.Sprites.FrontShinyFemale; } else { sprite = poke.Sprites.FrontMale ?? poke.Sprites.FrontFemale; } switch (group) { case PokemonDataGroup.Default: embed.AddInlineField("Height", poke.Height + "dm"); //embed.AddInlineField("Weight", poke.Weight + "hg"); embed.AddInlineField("Base Experience", $"{poke.BaseExperience}xp"); break; case PokemonDataGroup.Abilities: foreach (var ability in poke.Abilities) { embed.AddInlineField(ability.Ability.Name, "Slot: " + ability.Slot); } break; case PokemonDataGroup.Games: string games = null; foreach (var game in poke.GameIndices) { games += game.Version.Name + "\n"; if (game.GameIndex == poke.GameIndices.Last().GameIndex) { games += game.Version.Name; } } embed.AddInlineField("Game", games); break; case PokemonDataGroup.HeldItems: if (poke.HeldItems.Length > 0) { foreach (var hitem in poke.HeldItems) { foreach (var game in hitem.VersionDetails) { embed.AddInlineField("Item", hitem.Item.Name + "\n**Game**\n" + game.Version.Name + "\n**Rarity**\n" + game.Rarity); } } } else { embed.Description = "This pokemon doesn't hold any items in the wild"; } break; case PokemonDataGroup.Moves: var moves = poke.Moves.Take(4).Select(i => i).ToArray(); foreach (var move in moves) { string mve = move.Move.Name; mve += "\n**Learned at:**\n" + "Level " + move.VersionGroupDetails.FirstOrDefault().LearnedAt; mve += "\n**Method:**\n" + move.VersionGroupDetails.FirstOrDefault().LearnMethod.Name; embed.AddInlineField("Move", mve); } embed.Author.Url = "https://bulbapedia.bulbagarden.net/wiki/" + pokemon.Name + "_(Pokémon)"; embed.Footer = new EmbedFooterBuilder { Text = "Click the name to view more moves, I limited it to 4 to prevent a wall of text" }; break; case PokemonDataGroup.Stats: foreach (var stat in poke.Stats) { embed.AddInlineField(stat.Stat.Name, "Base Stat: " + stat.BaseValue); } break; } embed.ThumbnailUrl = sprite; return(embed.Build()); }