Exemplo n.º 1
0
        public async Task Profile([Remainder] IGuildUser user = null)
        {
            using var Database = new SkuldDbContextFactory().CreateDbContext();

            if (user is not null && (user.IsBot || user.IsWebhook))
            {
                await EmbedExtensions.FromError(DiscordUtilities.NoBotsString, Context).QueueMessageAsync(Context).ConfigureAwait(false);

                return;
            }

            if (user is null)
            {
                user = Context.User as IGuildUser;
            }

            await Database.InsertOrGetUserAsync(user).ConfigureAwait(false);

            var profileImage = await ApiClient.GetProfileCardAsync(Context.User.Id, Context.Guild.Id);

            if (profileImage is not null)
            {
                await "".QueueMessageAsync(Context, filestream: profileImage, filename: "image.png").ConfigureAwait(false);
            }
        }
Exemplo n.º 2
0
        public async Task TwitchSearch([Remainder] string twitchStreamer)
        {
            var TwitchClient = SkuldApp.Services.GetRequiredService <ITwitchAPI>();

            var userMatches = await TwitchClient.V5.Users.GetUserByNameAsync(twitchStreamer).ConfigureAwait(false);

            if (userMatches.Matches.Any())
            {
                var user = userMatches.Matches.FirstOrDefault();

                var channel = await TwitchClient.V5.Channels.GetChannelByIDAsync(user.Id).ConfigureAwait(false);

                var streams = await TwitchClient.V5.Streams.GetStreamByUserAsync(user.Id).ConfigureAwait(false);

                await(user.GetEmbed(channel, streams.Stream)).QueueMessageAsync(Context).ConfigureAwait(false);
            }
            else
            {
                await
                EmbedExtensions
                .FromError($"Couldn't find user `{twitchStreamer}`. Check your spelling and try again", Context)
                .QueueMessageAsync(Context)
                .ConfigureAwait(false);
            }
        }
Exemplo n.º 3
0
        public async Task LMGTFY([Remainder] string query)
        {
            using var Database = new SkuldDbContextFactory().CreateDbContext();

            var prefix = (await Database.InsertOrGetGuildAsync(Context.Guild).ConfigureAwait(false)).Prefix ?? Configuration.Prefix;

            string url = "https://lmgtfy.com/";

            var firstPart = query.Split(" ")[0];

            url = (firstPart.ToLowerInvariant()) switch
            {
                "b" or "bing" => url + "?s=b&q=" + query.ReplaceFirst(firstPart, "").Replace(" ", "%20"),
                "y" or "yahoo" => url + "?s=y&q=" + query.ReplaceFirst(firstPart, "").Replace(" ", "%20"),
                "a" or "aol" => url + "?a=b&q=" + query.ReplaceFirst(firstPart, "").Replace(" ", "%20"),
                "k" or "ask" => url + "?k=b&q=" + query.ReplaceFirst(firstPart, "").Replace(" ", "%20"),
                "d" or "duckduckgo" or "ddg" => url + "?s=d&q=" + query.ReplaceFirst(firstPart, "").Replace(" ", "%20"),
                "g" or "google" => url + "?s=g&q=" + query.ReplaceFirst(firstPart, "").Replace(" ", "%20"),
                _ => url + "?q=" + query.Replace(" ", "%20"),
            };

            if (url != "https://lmgtfy.com/")
            {
                await url.QueueMessageAsync(Context).ConfigureAwait(false);
            }
            else
            {
                await EmbedExtensions.FromError($"Ensure your parameters are correct, example: `{prefix}lmgtfy g How to use lmgtfy`", Context).QueueMessageAsync(Context).ConfigureAwait(false);

                StatsdClient.DogStatsd.Increment("commands.errors", 1, 1, new[] { "generic" });
            }
        }
Exemplo n.º 4
0
        public async Task Safebooru(params string[] tags)
        {
            tags
            .ContainsBlacklistedTags()
            .IsSuccessAsync(x => LewdModule.ContainsIllegalTags(x.Data, Context))
            .IsErrorAsync(async x =>
            {
                var posts = await SafebooruClient
                            .GetImagesAsync(tags)
                            .ConfigureAwait(false);

                DogStatsd.Increment("web.get");

                if (posts is null || !posts.Any())
                {
                    await EmbedExtensions
                    .FromError(
                        "Couldn't find an image.",
                        Context
                        )
                    .QueueMessageAsync(Context)
                    .ConfigureAwait(false);
                    return;
                }

                var post = posts.Where(x => !x.Tags.ContainsBlacklistedTags().Successful).Random();

                await post
                .GetMessage(Context)
                .QueueMessageAsync(Context)
                .ConfigureAwait(false);
            });
        }
Exemplo n.º 5
0
        public async Task KonaChan(params string[] tags)
        {
            if (tags.Count() > 6)
            {
                await $"Cannot process more than 6 tags at a time".QueueMessageAsync(Context).ConfigureAwait(false);
                return;
            }
            tags
            .ContainsBlacklistedTags()
            .IsSuccessAsync(x => containsIllegalTags(x.Data, tags, Context))
            .IsErrorAsync(async x =>
            {
                var posts = await KonaChanClient.GetImagesAsync(tags).ConfigureAwait(false);
                StatsdClient.DogStatsd.Increment("web.get");

                if (posts == null || !posts.Any())
                {
                    await EmbedExtensions.FromError("Couldn't find an image.", Context).QueueMessageAsync(Context).ConfigureAwait(false);
                    return;
                }

                var post = posts.Where(x => !x.Tags.ContainsBlacklistedTags().Successful).RandomValue();

                await post.GetMessage(Context).QueueMessageAsync(Context).ConfigureAwait(false);
            }
                          );
        }
Exemplo n.º 6
0
        public async Task Bean(IGuildUser user, [Remainder] string reason = null)
        {
            using var Database = new SkuldDbContextFactory().CreateDbContext();

            var usr = Database.Users.Find(user.Id);

            if (usr.Flags.IsBitSet(DiscordUtilities.Banned))
            {
                usr.Flags    -= DiscordUtilities.Banned;
                usr.BanReason = null;
                await
                EmbedExtensions.FromSuccess(SkuldAppContext.GetCaller(), $"Un-beaned {user.Mention}", Context)
                .QueueMessageAsync(Context).ConfigureAwait(false);
            }
            else
            {
                if (reason == null)
                {
                    await
                    EmbedExtensions.FromError($"{nameof(reason)} needs a value", Context)
                    .QueueMessageAsync(Context).ConfigureAwait(false);

                    return;
                }
                usr.Flags    += DiscordUtilities.Banned;
                usr.BanReason = reason;
                await
                EmbedExtensions.FromSuccess(SkuldAppContext.GetCaller(), $"Beaned {user.Mention} for reason: `{reason}`", Context)
                .QueueMessageAsync(Context).ConfigureAwait(false);
            }

            await Database.SaveChangesAsync().ConfigureAwait(false);
        }
Exemplo n.º 7
0
        public async Task SellKey(Guid key)
        {
            using var Database = new SkuldDbContextFactory().CreateDbContext();

            if (Database.DonatorKeys.ToList().Any(x => x.KeyCode == key))
            {
                var dbKey = Database.DonatorKeys.ToList().FirstOrDefault(x => x.KeyCode == key);
                if (dbKey.Redeemed)
                {
                    await
                    EmbedExtensions
                    .FromError("Donator Module",
                               "Can't sell a redeemed key",
                               Context)
                    .QueueMessageAsync(Context)
                    .ConfigureAwait(false);
                }
                else
                {
                    Database.DonatorKeys.Remove(dbKey);
                    await Database.SaveChangesAsync().ConfigureAwait(false);

                    var usr = await Database.InsertOrGetUserAsync(Context.User).ConfigureAwait(false);

                    TransactionService.DoTransaction(new TransactionStruct
                    {
                        Amount   = 25000,
                        Receiver = usr
                    });

                    await Database.SaveChangesAsync().ConfigureAwait(false);

                    await
                    EmbedExtensions
                    .FromSuccess("Donator Module",
                                 $"You just sold your donator key for {SkuldApp.MessageServiceConfig.MoneyIcon}{25000.ToFormattedString()}",
                                 Context)
                    .QueueMessageAsync(Context)
                    .ConfigureAwait(false);

                    DogStatsd.Increment("donatorkeys.sold");
                }
            }
            else
            {
                await
                EmbedExtensions
                .FromError("Donator Module",
                           "Key doesn't exist",
                           Context)
                .QueueMessageAsync(Context)
                .ConfigureAwait(false);
            }
        }
Exemplo n.º 8
0
        public async Task GetSearch(string platform, [Remainder] string query)
        {
            platform = platform.ToLowerInvariant();
            if (platform == "google" || platform == "g")
            {
                await $"🔍 Searching Google for: {query}".QueueMessageAsync(Context).ConfigureAwait(false);
                var result = await SearchClient.SearchGoogleAsync(query).ConfigureAwait(false);

                if (result == null)
                {
                    await EmbedExtensions.FromError($"I couldn't find anything matching: `{query}`, please try again.", Context).QueueMessageAsync(Context).ConfigureAwait(false);

                    return;
                }

                var item1 = result.FirstOrDefault();
                var item2 = result.ElementAt(1);
                var item3 = result.LastOrDefault();

                string desc = "I found this:\n" +
                              $"**{item1.Title}**\n" +
                              $"<{item1.Link}>\n\n" +
                              "__**Also Relevant**__\n" +
                              $"**{item2.Title}**\n<{item2.Link}>\n\n" +
                              $"**{item3.Title}**\n<{item3.Link}>\n\n" +
                              "If I didn't find what you're looking for, use this link:\n" +
                              $"https://google.com/search?q={query.Replace(" ", "%20")}";

                await
                new EmbedBuilder()
                .WithAuthor(new EmbedAuthorBuilder()
                            .WithName($"Google search for: {query}")
                            .WithIconUrl("https://upload.wikimedia.org/wikipedia/commons/0/09/IOS_Google_icon.png")
                            .WithUrl($"https://google.com/search?q={query.Replace(" ", "%20")}")
                            )
                .AddFooter(Context)
                .WithDescription(desc)
                .QueueMessageAsync(Context).ConfigureAwait(false);
            }
            if (platform == "youtube" || platform == "yt")
            {
                await $"🔍 Searching Youtube for: {query}".QueueMessageAsync(Context).ConfigureAwait(false);
                var result = await SearchClient.SearchYoutubeAsync(query).ConfigureAwait(false);

                await result.QueueMessageAsync(Context).ConfigureAwait(false);
            }
            if (platform == "imgur")
            {
                await "🔍 Searching Imgur for: {query}".QueueMessageAsync(Context).ConfigureAwait(false);
                var result = await SearchClient.SearchImgurAsync(query).ConfigureAwait(false);

                await result.QueueMessageAsync(Context).ConfigureAwait(false);
            }
        }
Exemplo n.º 9
0
        public async Task RedeemKey(Guid key)
        {
            using var Database = new SkuldDbContextFactory().CreateDbContext();

            if (Database.DonatorKeys.ToList().Any(x => x.KeyCode == key))
            {
                var dbKey = Database.DonatorKeys.ToList().FirstOrDefault(x => x.KeyCode == key);
                if (dbKey.Redeemed)
                {
                    await
                    EmbedExtensions
                    .FromError("Donator Module",
                               "Key already redeemed",
                               Context)
                    .QueueMessageAsync(Context)
                    .ConfigureAwait(false);
                }
                else
                {
                    dbKey.Redeemed     = true;
                    dbKey.Redeemer     = Context.User.Id;
                    dbKey.RedeemedWhen = DateTime.UtcNow.ToEpoch();

                    await Database.SaveChangesAsync().ConfigureAwait(false);

                    var usr = await Database.InsertOrGetUserAsync(Context.User).ConfigureAwait(false);

                    usr.Flags += DiscordUtilities.BotDonator;

                    await Database.SaveChangesAsync().ConfigureAwait(false);

                    await
                    EmbedExtensions
                    .FromSuccess("Donator Module",
                                 "You are now a donator",
                                 Context)
                    .QueueMessageAsync(Context)
                    .ConfigureAwait(false);

                    DogStatsd.Increment("donatorkeys.redeemed");
                }
            }
            else
            {
                await
                EmbedExtensions
                .FromError("Donator Module",
                           "Key doesn't exist",
                           Context)
                .QueueMessageAsync(Context)
                .ConfigureAwait(false);
            }
        }
Exemplo n.º 10
0
        public async Task LewdNeko()
        {
            var neko = await NekosLifeClient.GetAsync(NekoImageType.LewdNeko).ConfigureAwait(false);

            StatsdClient.DogStatsd.Increment("web.get");
            if (neko != null)
            {
                await EmbedExtensions.FromImage(neko, Color.Purple, Context).QueueMessageAsync(Context).ConfigureAwait(false);
            }
            else
            {
                await EmbedExtensions.FromError("Hmmm <:Thunk:350673785923567616> I got an empty response. Try again.", Context).QueueMessageAsync(Context).ConfigureAwait(false);
            }
        }
Exemplo n.º 11
0
        public async Task SendPokemonAsync(PokemonSpecies pokemon, string group)
        {
            if (pokemon is null)
            {
                StatsdClient.DogStatsd.Increment("commands.errors", 1, 1, new string[] { "generic" });

                await
                EmbedExtensions.FromError("This pokemon doesn't exist. Please try again.", Context)
                .QueueMessageAsync(Context)
                .ConfigureAwait(false);
            }
            else
            {
                switch (group.ToLowerInvariant())
                {
                case "stat":
                case "stats":
                    await(await pokemon.GetEmbedAsync(PokemonDataGroup.Stats).ConfigureAwait(false)).QueueMessageAsync(Context).ConfigureAwait(false);
                    break;

                case "abilities":
                case "ability":
                    await(await pokemon.GetEmbedAsync(PokemonDataGroup.Abilities).ConfigureAwait(false)).QueueMessageAsync(Context).ConfigureAwait(false);
                    break;

                case "helditems":
                case "hitems":
                case "hitem":
                case "items":
                    await(await pokemon.GetEmbedAsync(PokemonDataGroup.HeldItems).ConfigureAwait(false)).QueueMessageAsync(Context).ConfigureAwait(false);
                    break;

                case "move":
                case "moves":
                    await(await pokemon.GetEmbedAsync(PokemonDataGroup.Moves).ConfigureAwait(false)).QueueMessageAsync(Context).ConfigureAwait(false);
                    break;

                case "games":
                case "game":
                    await(await pokemon.GetEmbedAsync(PokemonDataGroup.Games).ConfigureAwait(false)).QueueMessageAsync(Context).ConfigureAwait(false);
                    break;

                case "default":
                default:
                    await(await pokemon.GetEmbedAsync(PokemonDataGroup.Default).ConfigureAwait(false)).QueueMessageAsync(Context).ConfigureAwait(false);
                    break;
                }
            }
        }
Exemplo n.º 12
0
 public async Task LeaveServer(ulong id)
 {
     var guild = Context.Client.GetGuild(id);
     await guild.LeaveAsync().ContinueWith(async x =>
     {
         if (Context.Client.GetGuild(id) == null)
         {
             await EmbedExtensions.FromSuccess(
                 $"Left guild **{guild.Name}**",
                 Context).QueueMessageAsync(Context)
             .ConfigureAwait(false);
         }
         else
         {
             await EmbedExtensions.FromError(
                 $"Hmm, I haven't left **{guild.Name}**",
                 Context).QueueMessageAsync(Context)
             .ConfigureAwait(false);
         }
     }).ConfigureAwait(false);
 }
Exemplo n.º 13
0
        public async Task SteamStore([Remainder] string game)
        {
            var steam = Query.Search(game);

            if (steam.Capacity > 0)
            {
                if (steam.Count > 1)
                {
                    var Pages = steam.PaginateList(25);

                    await $"Type the number of what you want:\n{string.Join("\n", Pages)}".QueueMessageAsync(Context).ConfigureAwait(false);

                    var message = await NextMessageAsync().ConfigureAwait(false);

                    int.TryParse(message.Content, out int selectedapp);
                    if (selectedapp <= 0)
                    {
                        await EmbedExtensions.FromError("Incorrect input", Context).QueueMessageAsync(Context).ConfigureAwait(false);

                        return;
                    }

                    selectedapp--;

                    await(await steam[selectedapp].GetEmbedAsync().ConfigureAwait(false)).QueueMessageAsync(Context).ConfigureAwait(false);
                }
                else
                {
                    await(await steam[0].GetEmbedAsync().ConfigureAwait(false)).QueueMessageAsync(Context).ConfigureAwait(false);
                }
            }
            else
            {
                await EmbedExtensions.FromError("I found nothing from steam", Context).QueueMessageAsync(Context).ConfigureAwait(false);
            }
        }
Exemplo n.º 14
0
        public async Task Money([Remainder] IGuildUser user = null)
        {
            using var Database = new SkuldDbContextFactory().CreateDbContext();

            if (user is not null && (user.IsBot || user.IsWebhook))
            {
                await EmbedExtensions.FromError("SkuldBank - Account Information", DiscordUtilities.NoBotsString, Context).QueueMessageAsync(Context).ConfigureAwait(false);

                return;
            }

            if (user is null)
            {
                user = (IGuildUser)Context.User;
            }

            var gld = await Database.InsertOrGetGuildAsync(Context.Guild).ConfigureAwait(false);

            var dbusr = await Database.InsertOrGetUserAsync(user).ConfigureAwait(false);

            await
            EmbedExtensions.FromMessage("SkuldBank - Account Information", $"{user.Mention} has {gld.MoneyIcon}{dbusr.Money.ToFormattedString()} {gld.MoneyName}", Context)
            .QueueMessageAsync(Context).ConfigureAwait(false);
        }
Exemplo n.º 15
0
        public async Task EvalStuff([Remainder] string code)
        {
            evalGlobals.Context = Context as ShardedCommandContext;

            if (scriptOptions == null)
            {
                scriptOptions = ScriptOptions
                                .Default
                                .WithReferences(typeof(SkuldDbContext).Assembly)
                                .WithReferences(
                    typeof(ShardedCommandContext).Assembly,
                    typeof(ShardedCommandContext).Assembly,
                    typeof(SocketGuildUser).Assembly,
                    typeof(Task).Assembly,
                    typeof(Queryable).Assembly,
                    typeof(SkuldApp).Assembly
                    )
                                .WithImports(typeof(SkuldDbContext).FullName)
                                .WithImports(typeof(ShardedCommandContext).FullName,
                                             typeof(ShardedCommandContext).FullName,
                                             typeof(SocketGuildUser).FullName,
                                             typeof(Task).FullName,
                                             typeof(Queryable).FullName,
                                             typeof(SkuldApp).FullName
                                             );
            }

            try
            {
                if (code.ToLowerInvariant().Contains("token") ||
                    code.ToLowerInvariant().Contains("key") ||
                    code.ToLowerInvariant().Contains("configuration"))
                {
                    await EmbedExtensions.FromError(
                        "Script Evaluation",
                        "Nope.",
                        Context)
                    .QueueMessageAsync(Context).ConfigureAwait(false);

                    return;
                }

                if ((code.StartsWith("```cs", StringComparison.Ordinal) ||
                     code.StartsWith("```", StringComparison.Ordinal)) &&
                    !code.EndsWith("```", StringComparison.Ordinal))
                {
                    await
                    EmbedExtensions.FromError(
                        "Script Evaluation",
                        "Starting Codeblock tags does not " +
                        "finish with closing Codeblock tags",
                        Context
                        ).QueueMessageAsync(Context)
                    .ConfigureAwait(false);

                    return;
                }

                if (code.StartsWith("```cs", StringComparison.Ordinal))
                {
                    code = code.ReplaceFirst("```cs", "");
                    code = code.ReplaceLast("```", "");
                }
                else if (code.StartsWith("```", StringComparison.Ordinal))
                {
                    code = code.Replace("```", "");
                }

                var script = CSharpScript.Create(
                    code,
                    scriptOptions,
                    typeof(Globals));

                script.Compile();

                var execution = await
                                script.RunAsync(globals : evalGlobals)
                                .ConfigureAwait(false);

                var result = execution.ReturnValue;

                string type = "N/A";

                if (result != null)
                {
                    type = result.GetType().ToString();
                }

                StringBuilder evalDesc = new StringBuilder();

                evalDesc
                .Append("__**Execution Result**__")
                .AppendLine()
                .Append("Returned Type: ")
                .AppendLine(type)
                .Append("Value: ")
                .Append(result);

                await EmbedExtensions.FromMessage(
                    "Script Evaluation",
                    evalDesc.ToString(),
                    Context
                    ).QueueMessageAsync(Context).ConfigureAwait(false);
            }
#pragma warning disable CS0168 // Variable is declared but never used
            catch (NullReferenceException ex) { /*Do nothing here*/ }
#pragma warning restore CS0168 // Variable is declared but never used
            catch (Exception ex)
            {
                Log.Error(
                    "EvalCMD",
                    "Error with eval command " + ex.Message,
                    Context,
                    ex);

                await EmbedExtensions.FromError(
                    "Script Evaluation",
                    $"Error with eval command\n\n{ex.Message}",
                    Context
                    ).QueueMessageAsync(Context).ConfigureAwait(false);
            }
        }
Exemplo n.º 16
0
        public async Task PlacePixel(int x, int y, [Remainder] Color colour)
        {
            if (x <= 0 || y <= 0)
            {
                await EmbedExtensions.FromError("I can't process coordinates below 0", Context).QueueMessageAsync(Context);

                return;
            }
            if (x > SkuldAppContext.PLACEIMAGESIZE || y > SkuldAppContext.PLACEIMAGESIZE)
            {
                await EmbedExtensions.FromError("I can't process coordinates above " + SkuldAppContext.PLACEIMAGESIZE, Context).QueueMessageAsync(Context);

                return;
            }

            ulong pixelCost = GetPixelCost(x, y);

            using var Database = new SkuldDbContextFactory().CreateDbContext();

            string prefix = (await Database.InsertOrGetConfigAsync(SkuldAppContext.ConfigurationId)).Prefix;

            if (!Context.IsPrivate)
            {
                prefix = (await Database.InsertOrGetGuildAsync(Context.Guild)).Prefix;
            }

            var dbUser = await Database.InsertOrGetUserAsync(Context.User).ConfigureAwait(false);

            TransactionService.DoTransaction(new TransactionStruct
            {
                Sender = dbUser,
                Amount = pixelCost
            })
            .IsSuccessAsync(async _ =>
            {
                using var db = new SkuldDbContextFactory().CreateDbContext();

                var pixel = db.PlacePixelData.FirstOrDefault(p => p.XPos == x && p.YPos == y);

                pixel.R = colour.R;
                pixel.G = colour.G;
                pixel.B = colour.B;

                await db.SaveChangesAsync().ConfigureAwait(false);

                db.PlacePixelHistory.Add(new PixelHistory
                {
                    PixelId          = pixel.Id,
                    ChangedTimestamp = DateTime.UtcNow.ToEpoch(),
                    CostToChange     = pixelCost,
                    ModifierId       = Context.User.Id
                });

                await db.SaveChangesAsync().ConfigureAwait(false);

                await $"Set it, use `{prefix}theplace view` to view it".QueueMessageAsync(Context).ConfigureAwait(false);
            })
            .IsErrorAsync(async _ =>
            {
                await "You don't have enough currency".QueueMessageAsync(Context).ConfigureAwait(false);
            });

            await Database.SaveChangesAsync().ConfigureAwait(false);
        }
Exemplo n.º 17
0
        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);
                });
            }
        }
Exemplo n.º 18
0
        public async Task RPS(string shoot, ulong bet)
        {
            if (bet <= 0)
            {
                await EmbedExtensions.FromError("Rock Paper Scissors", $"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);

            var skuldThrow = rpsWeights.GetRandomWeightedValue().Value;

            var playerThrow = RockPaperScissorsHelper.FromString(shoot);

            if (playerThrow != RPSThrow.Invalid)
            {
                var result = (WinResult)((playerThrow - skuldThrow + 2) % 3);

                var throwName = Locale.GetLocale(user.Language).GetString(rps.FirstOrDefault(x => x.Key == skuldThrow).Value);

                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("Rock Paper Scissors", $"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("Rock Paper Scissors", $"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);
                }

                switch (result)
                {
                case WinResult.BotWin:
                {
                    await EmbedExtensions.FromError("Rock Paper Scissors", $"I draw {throwName} and... You lost, you now have {MoneyPrefix}`{user.Money}`", Context).QueueMessageAsync(Context).ConfigureAwait(false);
                }
                break;

                case WinResult.PlayerWin:
                {
                    TransactionService.DoTransaction(new TransactionStruct
                        {
                            Amount   = bet * 2,
                            Receiver = user
                        });

                    await Database.SaveChangesAsync().ConfigureAwait(false);

                    await EmbedExtensions.FromSuccess("Rock Paper Scissors", $"I draw {throwName} and... You won, you now have {MoneyPrefix}`{user.Money}`", Context).QueueMessageAsync(Context).ConfigureAwait(false);
                }
                break;

                case WinResult.Draw:
                {
                    TransactionService.DoTransaction(new TransactionStruct
                        {
                            Amount   = bet,
                            Receiver = user
                        });

                    await Database.SaveChangesAsync().ConfigureAwait(false);

                    await EmbedExtensions.FromInfo("Rock Paper Scissors", $"I draw {throwName} and... It's a draw, your money has not been affected", Context).QueueMessageAsync(Context).ConfigureAwait(false);
                }
                break;
                }
            }
            else
            {
                await
                EmbedExtensions.FromError("Rock Paper Scissors", $"`{shoot}` is not a valid option", Context)
                .QueueMessageAsync(Context)
                .ConfigureAwait(false);
            }
        }
Exemplo n.º 19
0
        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;
            }
        }
Exemplo n.º 20
0
        internal static async Task CommandService_CommandExecuted(
            Optional <CommandInfo> arg1,
            ICommandContext arg2,
            IResult arg3
            )
        {
            CommandInfo cmd  = null;
            string      name = "";

            if (arg1.IsSpecified)
            {
                cmd = arg1.Value;

                name = cmd.Module.GetModulePath();

                if (cmd.Name != null)
                {
                    name += "." + cmd.Name;
                }

                name = name
                       .ToLowerInvariant()
                       .Replace(" ", "-")
                       .Replace("/", ".");
            }

            if (arg3.IsSuccess)
            {
                using var Database = new SkuldDbContextFactory().CreateDbContext();

                if (arg1.IsSpecified)
                {
                    var cont = arg2 as ShardedCommandContext;

                    DogStatsd.Increment("commands.total.threads", 1, 1, new[] { $"module:{cmd.Module.Name.ToLowerInvariant()}", $"cmd:{name}" });

                    DogStatsd.Histogram("commands.latency", watch.ElapsedMilliseconds, 0.5, new[] { $"module:{cmd.Module.Name.ToLowerInvariant()}", $"cmd:{name}" });

                    var usr = await Database.InsertOrGetUserAsync(cont.User).ConfigureAwait(false);

                    await InsertCommandAsync(cmd, usr).ConfigureAwait(false);

                    DogStatsd.Increment("commands.processed", 1, 1, new[] { $"module:{cmd.Module.Name.ToLowerInvariant()}", $"cmd:{name}" });
                }
            }
            else
            {
                bool displayerror = true;
                if (arg3.ErrorReason.Contains("few parameters"))
                {
                    var prefix = MessageTools.GetPrefixFromCommand(arg2.Message.Content, SkuldApp.Configuration.Prefix, SkuldApp.Configuration.AltPrefix);

                    string cmdName = "";

                    if (arg2.Guild != null)
                    {
                        using var Database = new SkuldDbContextFactory().CreateDbContext();

                        prefix = MessageTools.GetPrefixFromCommand(arg2.Message.Content,
                                                                   SkuldApp.Configuration.Prefix,
                                                                   SkuldApp.Configuration.AltPrefix,
                                                                   (await Database.InsertOrGetGuildAsync(arg2.Guild).ConfigureAwait(false)).Prefix
                                                                   );
                    }

                    if (cmd != null && cmd.Module.Group != null)
                    {
                        string pfx = "";

                        ModuleInfo mod = cmd.Module;
                        while (mod.Group != null)
                        {
                            pfx += $"{mod.Group} ";

                            if (mod.IsSubmodule)
                            {
                                mod = cmd.Module.Parent;
                            }
                        }

                        cmdName = $"{pfx}{cmd.Name}";

                        var cmdembed = await SkuldApp.CommandService.GetCommandHelpAsync(arg2, cmdName, prefix).ConfigureAwait(false);

                        await
                        arg2.Channel.SendMessageAsync(
                            "You seem to be missing a parameter or 2, here's the help",
                            embed : cmdembed.Build()
                            )
                        .ConfigureAwait(false);

                        displayerror = false;
                    }
                }

                if (arg3.ErrorReason.Contains("Timeout"))
                {
                    var hourglass = new Emoji("⏳");
                    if (!arg2.Message.Reactions.Any(x => x.Key == hourglass && x.Value.IsMe))
                    {
                        await arg2.Message.AddReactionAsync(hourglass).ConfigureAwait(false);
                    }
                    displayerror = false;
                }

                if (arg3.Error != CommandError.UnknownCommand && displayerror)
                {
                    Log.Error(Key,
                              "Error with command, Error is: " + arg3,
                              arg2 as ShardedCommandContext);

                    await EmbedExtensions.FromError(arg3.ErrorReason, arg2)
                    .QueueMessageAsync(arg2)
                    .ConfigureAwait(false);
                }

                switch (arg3.Error)
                {
                case CommandError.UnmetPrecondition:
                    DogStatsd.Increment("commands.errors",
                                        1,
                                        1,
                                        new[] {
                        "err:unm-precon",
                        $"mod:{cmd.Module.Name}",
                        $"cmd:{name}"
                    }
                                        );
                    break;

                case CommandError.Unsuccessful:
                    DogStatsd.Increment("commands.errors",
                                        1,
                                        1,
                                        new[] {
                        "err:generic",
                        $"mod:{cmd.Module.Name}",
                        $"cmd:{name}"
                    }
                                        );
                    break;

                case CommandError.MultipleMatches:
                    DogStatsd.Increment("commands.errors",
                                        1,
                                        1,
                                        new[] {
                        "err:multiple",
                        $"mod:{cmd.Module.Name}",
                        $"cmd:{name}"
                    }
                                        );
                    break;

                case CommandError.BadArgCount:
                    DogStatsd.Increment("commands.errors",
                                        1,
                                        1,
                                        new[] {
                        "err:incorr-args",
                        $"mod:{cmd.Module.Name}",
                        $"cmd:{name}"
                    }
                                        );
                    break;

                case CommandError.ParseFailed:
                    DogStatsd.Increment("commands.errors",
                                        1,
                                        1,
                                        new[] {
                        "err:parse-fail",
                        $"mod:{cmd.Module.Name}",
                        $"cmd:{name}"
                    }
                                        );
                    break;

                case CommandError.Exception:
                    DogStatsd.Increment("commands.errors",
                                        1,
                                        1,
                                        new[] {
                        "err:exception",
                        $"mod:{cmd.Module.Name}",
                        $"cmd:{name}"
                    }
                                        );
                    break;

                case CommandError.UnknownCommand:
                    DogStatsd.Increment("commands.errors",
                                        1,
                                        1,
                                        new[] {
                        "err:unk-cmd"
                    }
                                        );
                    break;
                }
            }
            watch = new Stopwatch();

            try
            {
                var message = arg2.Message as SocketUserMessage;

                using var Database = new SkuldDbContextFactory().CreateDbContext();

                User suser = await Database.InsertOrGetUserAsync(message.Author).ConfigureAwait(false);

                {
                    var keys = Database.DonatorKeys.AsAsyncEnumerable().Where(x => x.Redeemer == suser.Id);

                    if (await keys.AnyAsync().ConfigureAwait(false))
                    {
                        bool hasChanged = false;
                        var  current    = DateTime.Now;
                        await keys.ForEachAsync(x =>
                        {
                            if (current > x.RedeemedWhen.FromEpoch().AddDays(365))
                            {
                                Database.DonatorKeys.Remove(x);
                                hasChanged = true;
                            }
                        }).ConfigureAwait(false);

                        if (hasChanged)
                        {
                            if (!await Database.DonatorKeys.AsAsyncEnumerable().Where(x => x.Redeemer == suser.Id).AnyAsync().ConfigureAwait(false))
                            {
                                suser.Flags -= DiscordUtilities.BotDonator;
                            }
                            await Database.SaveChangesAsync().ConfigureAwait(false);
                        }
                    }
                }

                if (!suser.IsUpToDate(message.Author as SocketUser))
                {
                    suser.AvatarUrl = message.Author.GetAvatarUrl() ?? message.Author.GetDefaultAvatarUrl();
                    suser.Username  = message.Author.Username;
                    await Database.SaveChangesAsync().ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                Log.Error(Key, ex.Message, arg2, ex);
            }
        }
Exemplo n.º 21
0
        public async Task Daily(IGuildUser user = null)
        {
            if (user is not null && (user.IsBot || user.IsWebhook))
            {
                await EmbedExtensions.FromError(DiscordUtilities.NoBotsString, Context).QueueMessageAsync(Context).ConfigureAwait(false);

                return;
            }

            using var Database = new SkuldDbContextFactory().CreateDbContext();

            var self = await Database.InsertOrGetUserAsync(Context.User).ConfigureAwait(false);

            var gld = await Database.InsertOrGetGuildAsync(Context.Guild).ConfigureAwait(false);

            User target = null;

            if (user is not null)
            {
                target = await Database.InsertOrGetUserAsync(user).ConfigureAwait(false);
            }

            var previousAmount = user is null ? self.Money : target.Money;

            if (self.IsStreakReset(Configuration))
            {
                self.Streak = 0;
            }

            ulong MoneyAmount = self.GetDailyAmount(Configuration);

            if ((user is null ? self : target).ProcessDaily(MoneyAmount, self))
            {
                string desc = $"You just got your daily of {gld.MoneyIcon}{MoneyAmount}";

                if (target is not null)
                {
                    desc = $"You just gave your daily of {gld.MoneyIcon}{MoneyAmount.ToFormattedString()} to {user.Mention}";
                }

                var newAmount = user is null ? self.Money : target.Money;

                var embed =
                    EmbedExtensions
                    .FromMessage("SkuldBank - Daily",
                                 desc,
                                 Context
                                 )
                    .AddInlineField(
                        "Previous Amount",
                        $"{gld.MoneyIcon}{previousAmount.ToFormattedString()}"
                        )
                    .AddInlineField(
                        "New Amount",
                        $"{gld.MoneyIcon}{newAmount.ToFormattedString()}"
                        );

                if (self.Streak > 0)
                {
                    embed.AddField(
                        "Streak",
                        $"You're on a streak of {self.Streak} days!!"
                        );
                }

                self.Streak = self.Streak.Add(1);

                if (self.MaxStreak < self.Streak)
                {
                    self.MaxStreak = self.Streak;
                }

                await embed.QueueMessageAsync(Context).ConfigureAwait(false);
            }
Exemplo n.º 22
0
        public async Task PlaceImage(int x, int y, [Remainder] string image)
        {
            if (x <= 0 || y <= 0)
            {
                await EmbedExtensions.FromError("I can't process coordinates below 0", Context).QueueMessageAsync(Context);

                return;
            }
            if (x > SkuldAppContext.PLACEIMAGESIZE || y > SkuldAppContext.PLACEIMAGESIZE)
            {
                await EmbedExtensions.FromError("I can't process coordinates above " + SkuldAppContext.PLACEIMAGESIZE, Context).QueueMessageAsync(Context);

                return;
            }

            if (!image.IsWebsite() && !image.IsImageExtension())
            {
                await EmbedExtensions.FromError("You haven't provided an image link", Context).QueueMessageAsync(Context);

                return;
            }

            Bitmap bitmapImage;

            try
            {
                bitmapImage = new(await HttpWebClient.GetStreamAsync(new Uri(image)));
            }
            catch (Exception ex)
            {
                await EmbedExtensions.FromError("Couldn't process image", Context).QueueMessageAsync(Context);

                Log.Error("ThePlace", ex.Message, Context, ex);
                return;
            }

            if (bitmapImage is null)
            {
                await EmbedExtensions.FromError("Couldn't process image", Context).QueueMessageAsync(Context);

                Log.Error("ThePlace", "Couldn't load image", Context);
                return;
            }

            double aspectRatio = (double)bitmapImage.Width / bitmapImage.Height;

            if (bitmapImage.Width > SkuldAppContext.PLACEIMAGESIZE - x)
            {
                double otherAspect = (double)bitmapImage.Height / bitmapImage.Width;

                int newHeight = (int)Math.Min(Math.Round(SkuldAppContext.PLACEIMAGESIZE - y * otherAspect), SkuldAppContext.PLACEIMAGESIZE - y);
                bitmapImage = bitmapImage.ResizeBitmap(SkuldAppContext.PLACEIMAGESIZE - x, newHeight);
            }

            if (bitmapImage.Height > SkuldAppContext.PLACEIMAGESIZE - y)
            {
                int newWidth = (int)Math.Min(Math.Round(SkuldAppContext.PLACEIMAGESIZE - x * aspectRatio), SkuldAppContext.PLACEIMAGESIZE - x);
                bitmapImage = bitmapImage.ResizeBitmap(newWidth, SkuldAppContext.PLACEIMAGESIZE - y);
            }

            ulong pixelCost = 0;

            for (int bx = 0; bx < bitmapImage.Width; bx++)
            {
                for (int by = 0; by < bitmapImage.Height; by++)
                {
                    pixelCost += GetPixelCost(x + bx, y + by);
                }
            }

            using var Database = new SkuldDbContextFactory().CreateDbContext();

            string prefix = (await Database.InsertOrGetConfigAsync(SkuldAppContext.ConfigurationId)).Prefix;

            if (!Context.IsPrivate)
            {
                prefix = (await Database.InsertOrGetGuildAsync(Context.Guild)).Prefix;
            }

            var dbUser = await Database.InsertOrGetUserAsync(Context.User).ConfigureAwait(false);

            TransactionService.DoTransaction(new TransactionStruct
            {
                Sender = dbUser,
                Amount = pixelCost
            })
            .IsSuccessAsync(async _ =>
            {
                using var PixelDb   = new SkuldDbContextFactory().CreateDbContext();
                using var historyDb = new SkuldDbContextFactory().CreateDbContext();

                for (int bx = 0; bx < bitmapImage.Width; bx++)
                {
                    for (int by = 0; by < bitmapImage.Height; by++)
                    {
                        var pixel = PixelDb.PlacePixelData.FirstOrDefault(p => p.XPos == x + bx && p.YPos == y + by);

                        var colour = bitmapImage.GetPixel(bx, by);

                        pixel.R = colour.R;
                        pixel.G = colour.G;
                        pixel.B = colour.B;

                        historyDb.PlacePixelHistory.Add(new PixelHistory
                        {
                            PixelId          = pixel.Id,
                            ChangedTimestamp = DateTime.UtcNow.ToEpoch(),
                            CostToChange     = pixelCost,
                            ModifierId       = Context.User.Id
                        });
                    }
                }

                await PixelDb.SaveChangesAsync().ConfigureAwait(false);
                await historyDb.SaveChangesAsync().ConfigureAwait(false);

                await $"Set it, use `{prefix}theplace view` to view it".QueueMessageAsync(Context).ConfigureAwait(false);
            })
            .IsErrorAsync(async _ =>
            {
                await "You don't have enough currency".QueueMessageAsync(Context).ConfigureAwait(false);
            });

            await Database.SaveChangesAsync().ConfigureAwait(false);
        }