Ejemplo 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);
            }
        }
Ejemplo n.º 2
0
        private static async Task Bot_UserUpdated(
            SocketUser arg1,
            SocketUser arg2
            )
        {
            if (arg1.IsBot || arg1.IsWebhook)
            {
                return;
            }

            try
            {
                using SkuldDbContext database = new SkuldDbContextFactory()
                                                .CreateDbContext();

                Skuld.Models.User suser = await database
                                          .InsertOrGetUserAsync(arg2)
                                          .ConfigureAwait(false);

                if (!suser.IsUpToDate(arg2))
                {
                    suser.AvatarUrl =
                        arg2.GetAvatarUrl() ?? arg2.GetDefaultAvatarUrl();

                    suser.Username = arg2.Username;

                    await database.SaveChangesAsync().ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                Log.Error("UsrJoin", ex.Message, null, ex);
            }
        }
Ejemplo n.º 3
0
        public async Task GetFlags([Remainder] IUser user = null)
        {
            if (user == null)
            {
                user = Context.User;
            }

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

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

            List <BotAccessLevel> flags = new List <BotAccessLevel>();

            if (dbUser.Flags.IsBitSet(DiscordUtilities.BotCreator))
            {
                flags.Add(BotAccessLevel.BotOwner);
            }
            if (dbUser.Flags.IsBitSet(DiscordUtilities.BotAdmin))
            {
                flags.Add(BotAccessLevel.BotAdmin);
            }
            if (!dbUser.IsDonator)
            {
                flags.Add(BotAccessLevel.BotDonator);
            }
            if (dbUser.Flags.IsBitSet(DiscordUtilities.BotTester))
            {
                flags.Add(BotAccessLevel.BotTester);
            }

            flags.Add(BotAccessLevel.Normal);

            await $"{user.Mention} has the flags `{string.Join(", ", flags)}`".QueueMessageAsync(Context).ConfigureAwait(false);
        }
Ejemplo n.º 4
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);
            }
        }
Ejemplo n.º 5
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);
            }
        }
Ejemplo n.º 6
0
        public override async Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            using var Database = new SkuldDbContextFactory().CreateDbContext();

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

            if ((!DisabledForTesters && usr.Flags.IsBitSet(DiscordUtilities.BotTester)) || usr.Flags.IsBitSet(DiscordUtilities.BotCreator) || (!DisabledForAdmins && usr.Flags.IsBitSet(DiscordUtilities.BotAdmin)))
            {
                return(PreconditionResult.FromSuccess());
            }

            return(PreconditionResult.FromError($"Disabled Command\nReason: \"{Reason}\""));
        }
Ejemplo n.º 7
0
        public async Task Prestige()
        {
            using var Database = new SkuldDbContextFactory().CreateDbContext();

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

            var nextPrestige = usr.PrestigeLevel + 1;

            var xp = Database.UserXp.ToList().Where(x => x.UserId == usr.Id);

            ulong globalLevel = 0;

            xp.ToList().ForEach(x =>
            {
                globalLevel += x.Level;
            });

            if (globalLevel > PrestigeRequirement * nextPrestige)
            {
                await
                EmbedExtensions.FromInfo("Prestige Corner", "Please respond with y/n to confirm you want to prestige\n\n**__PLEASE NOTE__**\nThis will remove **ALL** experience gotten in every server with experience enabled", Context)
                .QueueMessageAsync(Context)
                .ConfigureAwait(false);

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

                try
                {
                    if (next.Content.ToBool())
                    {
                        Database.UserXp.RemoveRange(Database.UserXp.ToList().Where(x => x.UserId == Context.User.Id));
                        await Database.SaveChangesAsync().ConfigureAwait(false);

                        usr.PrestigeLevel = usr.PrestigeLevel.Add(1);

                        await Database.SaveChangesAsync().ConfigureAwait(false);
                    }
                }
                catch
                {
                    DogStatsd.Increment("commands.errors", 1, 1, new[] { "err:parse-fail" });
                }
            }
            else
            {
                await
                EmbedExtensions.FromInfo("Prestige Corner", $"You lack the amount of levels required to prestige. For your prestige level ({usr.PrestigeLevel}), it is: {PrestigeRequirement * nextPrestige}", Context)
                .QueueMessageAsync(Context)
                .ConfigureAwait(false);
            }
        }
Ejemplo n.º 8
0
        public async Task GrantExp(ulong amount, [Remainder] IGuildUser user = null)
        {
            if (user == null)
            {
                user = Context.Guild.GetUser(Context.User.Id);
            }

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

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

            await usr.GrantExperienceAsync(amount, Context, ExperienceService.DefaultAction, true).ConfigureAwait(false);

            await EmbedExtensions.FromSuccess($"Gave {user.Mention} {amount.ToFormattedString()}xp", Context).QueueMessageAsync(Context).ConfigureAwait(false);
        }
Ejemplo n.º 9
0
        public async Task SetMoney(IGuildUser user, ulong amount)
        {
            using var Database = new SkuldDbContextFactory().CreateDbContext();

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

            usr.Money = amount;

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

            await EmbedExtensions.FromSuccess(
                $"Set money of {user.Mention} to {usr.Money}",
                Context).QueueMessageAsync(Context)
            .ConfigureAwait(false);
        }
Ejemplo n.º 10
0
        public async Task GiveMoney(IGuildUser user, long amount)
        {
            using var Database = new SkuldDbContextFactory().CreateDbContext();

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

            if (amount < 0)
            {
                TransactionService.DoTransaction(new TransactionStruct
                {
                    Amount   = (ulong)Math.Abs(amount),
                    Receiver = usr
                });
            }
            else
            {
                TransactionService.DoTransaction(new TransactionStruct
                {
                    Amount   = (ulong)amount,
                    Receiver = usr
                });
            }

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

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

            StringBuilder message = new StringBuilder();

            message
            .Append("User ")
            .Append(user.Username)
            .Append(" now has: ")
            .Append(icon)
            .Append(usr.Money.ToFormattedString());

            await message.QueueMessageAsync(Context).ConfigureAwait(false);
        }
Ejemplo n.º 11
0
        public async Task SetStreak(ushort streak, [Remainder] IUser user = null)
        {
            if (user == null)
            {
                user = Context.User;
            }

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

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

            usr.Streak = streak;

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

            await
            EmbedExtensions.FromSuccess(Context).QueueMessageAsync(Context)
            .ConfigureAwait(false);
        }
Ejemplo n.º 12
0
        private static async Task Bot_GuildMemberUpdated(
            SocketGuildUser arg1,
            SocketGuildUser arg2
            )
        {
            if (arg1.IsBot || arg1.IsWebhook)
            {
                return;
            }

            //Resync Data
            {
                using SkuldDbContext database = new SkuldDbContextFactory()
                                                .CreateDbContext();

                User suser = await database
                             .InsertOrGetUserAsync(arg2)
                             .ConfigureAwait(false);

                if (!suser.IsUpToDate(arg2))
                {
                    suser.AvatarUrl =
                        arg2.GetAvatarUrl() ?? arg2.GetDefaultAvatarUrl();

                    suser.Username = arg2.Username;

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

            if (arg1.Roles.Count != arg2.Roles.Count)
            {
                //Add Persistent Role
                await HandlePersistentRoleAdd(arg2).ConfigureAwait(false);

                //Remove Persistent Role
                await HandlePersistentRoleRemove(arg1, arg2).ConfigureAwait(false);
            }
        }
Ejemplo n.º 13
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);
        }
Ejemplo n.º 14
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);
            }
        }
Ejemplo n.º 15
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;
            }
        }
Ejemplo n.º 16
0
        public async Task GetAnime([Remainder] string animetitle)
        {
            using var Database = new SkuldDbContextFactory().CreateDbContext();

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

            var loc = Locale.GetLocale(
                usr.Language ?? Locale.DefaultLocale
                );

            var raw = await Anime
                      .GetAnimeAsync(animetitle)
                      .ConfigureAwait(false);

            var data = raw.Data;

            if (data.Count > 1) // do pagination
            {
                var pages = data.PaginateList(25);

                IUserMessage sentmessage = await ReplyAsync(null, false,
                                                            EmbedExtensions
                                                            .FromMessage(
                                                                loc.GetString("SKULD_SEARCH_MKSLCTN") + " 30s",
                                                                pages[0],
                                                                Context
                                                                )
                                                            .WithColor(Color.Purple)
                                                            .Build()
                                                            ).ConfigureAwait(false);

                var response = await NextMessageAsync(
                    true,
                    true,
                    TimeSpan.FromSeconds(30)
                    ).ConfigureAwait(false);

                if (response is null)
                {
                    await sentmessage.DeleteAsync().ConfigureAwait(false);

                    return;
                }

                var selection = Convert.ToInt32(response.Content);

                var anime = data[selection - 1];

                await anime
                .ToEmbed(loc)
                .QueueMessageAsync(Context)
                .ConfigureAwait(false);
            }
            else
            {
                var anime = data[0];

                await anime
                .ToEmbed(loc)
                .QueueMessageAsync(Context)
                .ConfigureAwait(false);
            }
        }
Ejemplo n.º 17
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);
            }
        }
Ejemplo n.º 18
0
        private static async Task HandleMessageAsync(SocketMessage arg)
        {
            DogStatsd.Increment("messages.recieved");

            if (arg.Author.IsBot ||
                arg.Author.IsWebhook ||
                arg.Author.DiscriminatorValue == 0 ||
                arg is not SocketUserMessage message)
            {
                return;
            }

            ShardedCommandContext context = new ShardedCommandContext(
                SkuldApp.DiscordClient,
                message
                );

            Guild sguild = null;

            if (context.Guild != null)
            {
                if (!await CheckPermissionToSendMessageAsync(context.Channel as ITextChannel).ConfigureAwait(false))
                {
                    return;
                }

                if (SkuldApp.DiscordClient.GetShardFor(context.Guild).ConnectionState != ConnectionState.Connected)
                {
                    return;
                }

                _ = Task.Run(() => HandleSideTasksAsync(context));

                var guser = await
                                (context.Guild as IGuild).GetCurrentUserAsync()
                            .ConfigureAwait(false);

                var guildMem = await
                                   (context.Guild as IGuild).GetUserAsync(message.Author.Id)
                               .ConfigureAwait(false);

                if (!guser.GetPermissions(context.Channel as IGuildChannel).SendMessages)
                {
                    return;
                }

                if (!MessageTools.IsEnabledChannel(guildMem, context.Channel as ITextChannel))
                {
                    return;
                }

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

                sguild = await
                         Database.InsertOrGetGuildAsync(context.Guild)
                         .ConfigureAwait(false);

                if (sguild.Name != context.Guild.Name)
                {
                    sguild.Name = context.Guild.Name;

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

                if (sguild.IconUrl != context.Guild.IconUrl)
                {
                    sguild.IconUrl = context.Guild.IconUrl;

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

            if (!MessageTools.HasPrefix(message, SkuldApp.Configuration.Prefix, SkuldApp.Configuration.AltPrefix, sguild?.Prefix))
            {
                return;
            }

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

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

                if (suser != null &&
                    suser.Flags.IsBitSet(DiscordUtilities.Banned) &&
                    (!suser.Flags.IsBitSet(DiscordUtilities.BotCreator) ||
                     !suser.Flags.IsBitSet(DiscordUtilities.BotAdmin))
                    )
                {
                    return;
                }

                var prefix = MessageTools.GetPrefixFromCommand(context.Message.Content, SkuldApp.Configuration.Prefix, SkuldApp.Configuration.AltPrefix, sguild?.Prefix);

                if (prefix != null)
                {
                    await DispatchCommandAsync(context, prefix).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                Log.Critical(Key, ex.Message, context, ex);
            }
        }
Ejemplo n.º 19
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);
        }
Ejemplo n.º 20
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);
            }
Ejemplo n.º 21
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);
        }
Ejemplo n.º 22
0
        private static async Task HandleMessageAsync(SocketMessage arg)
        {
            DogStatsd.Increment("messages.recieved");

            if (arg.Author.IsBot ||
                arg.Author.IsWebhook ||
                arg.Author.DiscriminatorValue == 0 ||
                arg is not SocketUserMessage message)
            {
                return;
            }

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

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

            if (suser is not null &&
                suser.Flags.IsBitSet(DiscordUtilities.Banned) &&
                (!suser.Flags.IsBitSet(DiscordUtilities.BotCreator) ||
                 !suser.Flags.IsBitSet(DiscordUtilities.BotAdmin))
                )
            {
                return;
            }

            ShardedCommandContext context = new(SkuldApp.DiscordClient, message);

            Guild sguild = null;

            if (context.Guild is not null)
            {
                if (SkuldApp.DiscordClient.GetShardFor(context.Guild).ConnectionState != ConnectionState.Connected)
                {
                    return;
                }

                if (!await CheckPermissionToSendMessageAsync(context.Channel as ITextChannel).ConfigureAwait(false))
                {
                    return;
                }

                var guser = await
                                (context.Guild as IGuild).GetCurrentUserAsync()
                            .ConfigureAwait(false);

                if (!guser.GetPermissions(context.Channel as IGuildChannel).SendMessages)
                {
                    return;
                }

                var guildMem = await
                                   (context.Guild as IGuild).GetUserAsync(message.Author.Id)
                               .ConfigureAwait(false);

                if (!MessageTools.IsEnabledChannel(guildMem, context.Channel as ITextChannel))
                {
                    return;
                }

                sguild = await
                         Database.InsertOrGetGuildAsync(context.Guild)
                         .ConfigureAwait(false);

                if (sguild.Name != context.Guild.Name)
                {
                    sguild.Name = context.Guild.Name;

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

                if (sguild.IconUrl != context.Guild.IconUrl)
                {
                    sguild.IconUrl = context.Guild.IconUrl;

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

            if (!MessageTools.HasPrefix(message, SkuldApp.Configuration.Prefix, SkuldApp.Configuration.AltPrefix, sguild?.Prefix))
            {
                return;
            }

            await Task.WhenAll(ProcessCommandAsync(context, sguild), ProcessExperienceAsync(context, sguild), ProcessCustomCommand(context, sguild));
        }
Ejemplo n.º 23
0
        private static async Task Bot_UserJoined(
            SocketGuildUser arg
            )
        {
            DogStatsd.Increment("guild.users.joined");

            //Insert into Database
            try
            {
                using SkuldDbContext database = new SkuldDbContextFactory()
                                                .CreateDbContext();

                await database.InsertOrGetUserAsync(arg as IUser)
                .ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Log.Error("UsrJoin", ex.Message, null, ex);
            }

            //Persistent Roles
            try
            {
                using SkuldDbContext database = new SkuldDbContextFactory()
                                                .CreateDbContext();

                if (database.PersistentRoles.ToList()
                    .Any(x => x.UserId == arg.Id && x.GuildId == arg.Guild.Id))
                {
                    foreach (var persistentRole in database.PersistentRoles
                             .ToList().Where(x =>
                                             x.UserId == arg.Id && x.GuildId == arg.Guild.Id)
                             )
                    {
                        try
                        {
                            await arg.AddRoleAsync(
                                arg.Guild.GetRole(persistentRole.RoleId)
                                ).ConfigureAwait(false);
                        }
                        catch (Exception ex)
                        {
                            Log.Error("UsrJoin", ex.Message, null, ex);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("UsrJoin", ex.Message, null, ex);
            }

            //Join Message
            try
            {
                using SkuldDbContext database = new SkuldDbContextFactory()
                                                .CreateDbContext();

                var gld = await database.InsertOrGetGuildAsync(arg.Guild)
                          .ConfigureAwait(false);

                if (gld != null)
                {
                    if (gld.JoinRole != 0)
                    {
                        var joinrole = arg.Guild.GetRole(gld.JoinRole);
                        await arg
                        .AddRoleAsync(joinrole)
                        .ConfigureAwait(false);
                    }

                    if (gld.JoinChannel != 0 &&
                        !string.IsNullOrEmpty(gld.JoinMessage)
                        )
                    {
                        var channel = arg.Guild
                                      .GetTextChannel(gld.JoinChannel);

                        var message = gld.JoinMessage
                                      .ReplaceGuildEventMessage(
                            arg,
                            arg.Guild
                            );

                        await channel
                        .SendMessageAsync(message)
                        .ConfigureAwait(false);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("UsrJoin", ex.Message, null, ex);
            }

            //Experience Roles
            try
            {
                using SkuldDbContext database =
                          new SkuldDbContextFactory()
                          .CreateDbContext();

                var feats = database.Features
                            .Find(arg.Guild.Id);

                if (feats.Experience)
                {
                    var rewards = database.LevelRewards
                                  .ToList().Where(x => x.GuildId == arg.Guild.Id);

                    var usrLvl = database.UserXp
                                 .FirstOrDefault(x =>
                                                 x.GuildId == arg.Guild.Id && x.UserId == arg.Id
                                                 );

                    var lvl = DatabaseUtilities.GetLevelFromTotalXP(
                        usrLvl.TotalXP,
                        DiscordUtilities.LevelModifier
                        );

                    var rolesToGive = rewards
                                      .Where(x => x.LevelRequired <= lvl)
                                      .Select(z => z.RoleId);

                    if (feats.StackingRoles)
                    {
                        var roles = (arg.Guild as IGuild).Roles
                                    .Where(z => rolesToGive.Contains(z.Id));

                        if (roles.Any())
                        {
                            try
                            {
                                await arg.AddRolesAsync(roles)
                                .ConfigureAwait(false);
                            }
                            catch (Exception ex)
                            {
                                Log.Error("UsrJoin", ex.Message, null, ex);
                            }
                        }
                    }
                    else
                    {
                        var r = rewards
                                .Where(x => x.LevelRequired <= lvl)
                                .OrderByDescending(x => x.LevelRequired)
                                .FirstOrDefault();

                        if (r != null)
                        {
                            var role = arg.Guild.Roles.FirstOrDefault(z =>
                                                                      rolesToGive.Contains(r.Id)
                                                                      );

                            if (role != null)
                            {
                                try
                                {
                                    await arg.AddRoleAsync(role)
                                    .ConfigureAwait(false);
                                }
                                catch (Exception ex)
                                {
                                    Log.Error("UsrJoin", ex.Message, null, ex);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("UsrJoin", ex.Message, null, ex);
            }

            Log.Verbose(Key, $"{arg} joined {arg.Guild}", null);
        }
Ejemplo n.º 24
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);
                });
            }
        }
Ejemplo n.º 25
0
        public async Task SetFlag(BotAccessLevel level, bool give = true, [Remainder] IUser user = null)
        {
            if (user == null)
            {
                user = Context.User;
            }

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

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

            bool DidAny = false;

            switch (level)
            {
            case BotAccessLevel.BotOwner:
                if (give & !dbUser.Flags.IsBitSet(DiscordUtilities.BotCreator))
                {
                    dbUser.Flags += DiscordUtilities.BotCreator;
                    DidAny        = true;
                }
                else if (!give && dbUser.Flags.IsBitSet(DiscordUtilities.BotCreator))
                {
                    dbUser.Flags -= DiscordUtilities.BotCreator;
                    DidAny        = true;
                }
                break;

            case BotAccessLevel.BotAdmin:
                if (give && !dbUser.Flags.IsBitSet(DiscordUtilities.BotAdmin))
                {
                    dbUser.Flags += DiscordUtilities.BotAdmin;
                    DidAny        = true;
                }
                else if (!give && dbUser.Flags.IsBitSet(DiscordUtilities.BotAdmin))
                {
                    dbUser.Flags -= DiscordUtilities.BotAdmin;
                    DidAny        = true;
                }
                break;

            case BotAccessLevel.BotTester:
                if (give && !dbUser.Flags.IsBitSet(DiscordUtilities.BotTester))
                {
                    dbUser.Flags += DiscordUtilities.BotTester;
                    DidAny        = true;
                }
                else if (!give && dbUser.Flags.IsBitSet(DiscordUtilities.BotTester))
                {
                    dbUser.Flags -= DiscordUtilities.BotTester;
                    DidAny        = true;
                }
                break;

            case BotAccessLevel.BotDonator:
                if (give && !dbUser.IsDonator)
                {
                    dbUser.Flags += DiscordUtilities.BotDonator;
                    DidAny        = true;
                }
                else if (!give && dbUser.IsDonator)
                {
                    dbUser.Flags -= DiscordUtilities.BotDonator;
                    DidAny        = true;
                }
                break;
            }

            if (DidAny)
            {
                await Database.SaveChangesAsync().ConfigureAwait(false);
            }

            if (DidAny)
            {
                await $"{(give ? "Added" : "Removed")} flag `{level}` to {user.Mention}".QueueMessageAsync(Context).ConfigureAwait(false);
            }
            else
            {
                await $"{user.Mention} {(give ? "already has" : "doesn't have")} the flag `{level}`".QueueMessageAsync(Context).ConfigureAwait(false);
            }
        }
Ejemplo n.º 26
0
        public async Task Pet([Remainder] string target = null)
        {
            var images = await Imghoard.GetImagesAsync(SkuldAppContext.GetCaller().LowercaseFirstLetter()).ConfigureAwait(false);

            var image = images.Images.RandomValue().Url;

            var action =
                new EmbedBuilder()
                .WithImageUrl(image)
                .WithTitle(SkuldAppContext.GetCaller().CapitaliseFirstLetter())
                .WithRandomColor()
                .AddAuthor(Context.Client)
                .AddFooter(Context);

            if (target != null)
            {
                if (Context.Message.MentionedUsers.Any())
                {
                    List <ulong> prune = new List <ulong>();

                    {
                        using SkuldDbContext Database = new SkuldDbContextFactory().CreateDbContext(null);

                        foreach (var mentionedUser in Context.Message.MentionedUsers)
                        {
                            var res = Database.BlockedActions.FirstOrDefault(x => x.Blockee == Context.User.Id && x.Blocker == mentionedUser.Id);

                            if (res != null)
                            {
                                prune.Add(mentionedUser.Id);
                            }
                        }
                    }

                    {
                        using SkuldDbContext Database = new SkuldDbContextFactory().CreateDbContext(null);
                        var initiator = await Database.InsertOrGetUserAsync(Context.User).ConfigureAwait(false);

                        StringBuilder message = new StringBuilder($"{Context.User.Mention} pets ");

                        var msg = target;

                        foreach (var usr in Context.Message.MentionedUsers)
                        {
                            if (usr.IsBot || usr.IsWebhook || usr.Discriminator == "0000" || usr.DiscriminatorValue == 0 || prune.Contains(usr.Id))
                            {
                                continue;
                            }

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

                            if (!(uzr.RecurringBlock && uzr.Patted.IsRecurring(3)))
                            {
                                uzr.Patted     += 1;
                                initiator.Pats += 1;

                                message.Append(usr.Mention + " ");
                            }
                            else
                            {
                                msg.PruneMention(usr.Id);
                            }
                        }

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

                        if (message.ToString() != $"{Context.User.Mention} pets ")
                        {
                            action.WithDescription(message.ToString());
                        }
                        else
                        {
                            action.WithDescription($"{Context.Client.CurrentUser.Mention} pets {Context.User.Mention}");
                        }
                    }
                }
                else
                {
                    action.WithDescription($"{Context.User.Mention} pets {target}");
                }
            }
            else
            {
                action.WithDescription($"{Context.Client.CurrentUser.Mention} pets {Context.User.Mention}");
            }

            await action.QueueMessageAsync(Context).ConfigureAwait(false);
        }
Ejemplo n.º 27
0
        private static async Task Bot_ReactionAdded(
            Cacheable <IUserMessage, ulong> arg1,
            ISocketMessageChannel arg2,
            SocketReaction arg3)
        {
            DogStatsd.Increment("messages.reactions.added");
            IUser usr;

            var msg = await arg1.GetOrDownloadAsync().ConfigureAwait(false);

            if (msg == null)
            {
                return;
            }

            if (!arg3.User.IsSpecified)
            {
                return;
            }
            else
            {
                usr = arg3.User.Value;
            }

            if (usr.IsBot || usr.IsWebhook)
            {
                return;
            }

            if (arg2 is IGuildChannel)
            {
                await PinningService.ExecuteAdditionAsync(SkuldApp.DiscordClient, SkuldApp.Configuration, msg, arg2)
                .ConfigureAwait(false);

                await StarboardService.ExecuteAdditionAsync(msg, arg2, arg3)
                .ConfigureAwait(false);
            }

            if (arg2.Id == SkuldApp.Configuration.IssueChannel)
            {
                using var Database = new SkuldDbContextFactory()
                                     .CreateDbContext();

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

                if (user.Flags.IsBitSet(DiscordUtilities.BotCreator))
                {
                    try
                    {
                        if (arg1.HasValue)
                        {
                            var message = Database.Issues
                                          .FirstOrDefault(x =>
                                                          x.IssueChannelMessageId == arg1.Id
                                                          );
                            if (message != null)
                            {
                                var emote = arg3.Emote as Emote;

                                if (emote.Id == DiscordUtilities.Tick_Emote.Id)
                                {
                                    if (!message.HasSent)
                                    {
                                        try
                                        {
                                            var newissue =
                                                new NewIssue(message.Title)
                                            {
                                                Body = message.Body
                                            };

                                            newissue.
                                            Assignees.Add("exsersewo");
                                            newissue.
                                            Labels.Add("From Command");

                                            var issue = await SkuldApp
                                                        .Services
                                                        .GetRequiredService
                                                        <GitHubClient>()
                                                        .Issue
                                                        .Create(
                                                SkuldApp
                                                .Configuration
                                                .GithubRepository,
                                                newissue
                                                ).ConfigureAwait(false);

                                            try
                                            {
                                                await SkuldApp.DiscordClient
                                                .GetUser(
                                                    message.SubmitterId
                                                    )
                                                .SendMessageAsync(
                                                    "",
                                                    false,
                                                    new EmbedBuilder()
                                                    .WithTitle(
                                                        "Good News!"
                                                        )
                                                    .AddAuthor(
                                                        SkuldApp
                                                        .DiscordClient
                                                        )
                                                    .WithDescription(
                                                        "Your issue:\n" +
                                                        $"\"[{newissue.Title}]" +
                                                        $"({issue.HtmlUrl})\"" +
                                                        "\n\nhas been accepted"
                                                        )
                                                    .WithRandomColor()
                                                    .Build()
                                                    ).ConfigureAwait(false);
                                            }
                                            catch { }

                                            await msg.ModifyAsync(x =>
                                            {
                                                x.Embed = msg.Embeds
                                                          .ElementAt(0)
                                                          .ToEmbedBuilder()
                                                          .AddField(
                                                    "Sent",
                                                    DiscordUtilities
                                                    .Tick_Emote
                                                    .ToString()
                                                    )
                                                          .Build();
                                            }).ConfigureAwait(false);

                                            message.HasSent = true;

                                            await Database.SaveChangesAsync()
                                            .ConfigureAwait(false);
                                        }
                                        catch (Exception ex)
                                        {
                                            Log.Error(
                                                "Git-" +
                                                SkuldAppContext.GetCaller(),
                                                ex.Message,
                                                null,
                                                ex
                                                );
                                        }
                                    }
                                }
                                else if (
                                    emote.Id == DiscordUtilities.Cross_Emote.Id
                                    )
                                {
                                    Database.Issues.Remove(message);

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

                                    await msg.DeleteAsync()
                                    .ConfigureAwait(false);

                                    try
                                    {
                                        await SkuldApp
                                        .DiscordClient
                                        .GetUser(message.SubmitterId)
                                        .SendMessageAsync(
                                            "",
                                            false,
                                            new EmbedBuilder()
                                            .WithTitle("Bad News")
                                            .AddAuthor(
                                                SkuldApp.DiscordClient
                                                )
                                            .WithDescription(
                                                "Your issue:\n" +
                                                $"\"{message.Title}\"" +
                                                "\n\nhas been declined. " +
                                                "If you would like to know why, " +
                                                $"send: {usr.FullName()} a message"
                                                )
                                            .WithRandomColor()
                                            .Build()
                                            ).ConfigureAwait(false);
                                    }
                                    catch { }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Critical(Key,
                                     ex.Message,
                                     null,
                                     ex
                                     );
                    }
                }
            }
        }