Exemple #1
0
        public static async Task HandleSideTasksAsync(ICommandContext context)
        {
            using var Database = new SkuldDbContextFactory().CreateDbContext();

            Guild sguild = null;

            if (context.Guild != null)
            {
                sguild = await
                         Database.InsertOrGetGuildAsync(context.Guild)
                         .ConfigureAwait(false);
            }

            if (sguild != null)
            {
                if (!Database.Features.Any(x => x.Id == sguild.Id))
                {
                    Database.Features.Add(new GuildFeatures
                    {
                        Id = sguild.Id
                    });
                    await Database.SaveChangesAsync().ConfigureAwait(false);
                }

                GuildFeatures features = Database.Features.Find(sguild.Id);
                if (features.Experience)
                {
                    _ = Task.Run(() => ExperienceService.HandleExperienceAsync(context));
                }

                if (!Database.Modules.Any(x => x.Id == sguild.Id))
                {
                    Database.Modules.Add(new GuildModules
                    {
                        Id = sguild.Id
                    });
                    await Database.SaveChangesAsync().ConfigureAwait(false);
                }

                GuildModules modules;
                if (!Database.Modules.Any(x => x.Id == sguild.Id))
                {
                    Database.Modules.Add(new GuildModules
                    {
                        Id = sguild.Id
                    });
                    await Database.SaveChangesAsync().ConfigureAwait(false);
                }

                modules = Database.Modules.Find(sguild.Id);

                if (modules.Custom)
                {
                    _ = Task.Run(() => CustomCommandService.HandleCustomCommandAsync(context, SkuldApp.Configuration));
                }
            }
        }
Exemple #2
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);
            }
        }
Exemple #3
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);
            }
        }
Exemple #4
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);
            }
        }
Exemple #5
0
        public static async Task ProcessExperienceAsync(ICommandContext context, Guild sguild)
        {
            if (sguild is null)
            {
                return;
            }

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

            if (!Database.Features.Any(x => x.Id == sguild.Id))
            {
                Database.Features.Add(new GuildFeatures
                {
                    Id = sguild.Id
                });
                await Database.SaveChangesAsync().ConfigureAwait(false);
            }

            GuildFeatures features = Database.Features.Find(sguild.Id);

            if (features.Experience)
            {
                await ExperienceService.HandleExperienceAsync(context);
            }
        }
Exemple #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);
        }
Exemple #7
0
        public async Task CreateKeys(ulong amount)
        {
            using var db = new SkuldDbContextFactory().CreateDbContext();

            StringBuilder message = new StringBuilder($"Keycodes:");

            message.AppendLine();

            for (ulong x = 0; x < amount; x++)
            {
                var key = new DonatorKey
                {
                    KeyCode = Guid.NewGuid()
                };
                db.DonatorKeys.Add(key);

                message.AppendLine($"Keycode: {key.KeyCode}");
            }

            DogStatsd.Increment("donatorkeys.generated", (int)amount);

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

            await message.QueueMessageAsync(
                Context,
                type : Services.Messaging.Models.MessageType.DMS
                ).ConfigureAwait(false);
        }
Exemple #8
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);
            }
        }
Exemple #9
0
        public static async Task ProcessCustomCommand(ICommandContext context, Guild sguild)
        {
            if (sguild is null)
            {
                return;
            }

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

            if (sguild is not null)
            {
                GuildModules modules;
                if (!Database.Modules.Any(x => x.Id == sguild.Id))
                {
                    Database.Modules.Add(new GuildModules
                    {
                        Id = sguild.Id
                    });
                    await Database.SaveChangesAsync().ConfigureAwait(false);
                }

                modules = Database.Modules.Find(sguild.Id);

                if (modules.Custom)
                {
                    await CustomCommandService.HandleCustomCommandAsync(context, SkuldApp.Configuration);
                }
            }
        }
Exemple #10
0
        private static async Task Bot_GuildUpdated(
            SocketGuild arg1,
            SocketGuild arg2
            )
        {
            try
            {
                using SkuldDbContext Database = new SkuldDbContextFactory()
                                                .CreateDbContext();

                var sguild = await
                             Database.InsertOrGetGuildAsync(arg2)
                             .ConfigureAwait(false);

                if (sguild.Name == null ||
                    !sguild.Name.Equals(arg2.Name))
                {
                    sguild.Name = arg2.Name;
                }

                if (sguild.IconUrl == null ||
                    !sguild.IconUrl.Equals(arg2.IconUrl))
                {
                    sguild.IconUrl = arg2.IconUrl;
                }

                await Database.SaveChangesAsync().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Log.Error("UsrJoin", ex.Message, null, ex);
            }
        }
Exemple #11
0
        public async Task DropGuild(ulong guildId)
        {
            using var database = new SkuldDbContextFactory().CreateDbContext();

            await database.DropGuildAsync(guildId).ConfigureAwait(false);

            await database.SaveChangesAsync().ConfigureAwait(false);
        }
Exemple #12
0
        private static async Task Shard_MessagesBulkDeleted(
            IReadOnlyCollection <Cacheable <IMessage, ulong> > arg1,
            ISocketMessageChannel arg2
            )
        {
            using var Database = new SkuldDbContextFactory().CreateDbContext();

            if (arg2 is IGuildChannel guildChannel)
            {
                var gld = await Database
                          .InsertOrGetGuildAsync(guildChannel.Guild)
                          .ConfigureAwait(false);

                var feats = Database.Features
                            .Find(guildChannel.GuildId);

                if (feats.Starboard && gld.StarDeleteIfSourceDelete)
                {
                    foreach (var msg in arg1)
                    {
                        var message = await msg.GetOrDownloadAsync()
                                      .ConfigureAwait(false);

                        if (Database.StarboardVotes
                            .Any(x => x.MessageId == message.Id))
                        {
                            var vote = Database.StarboardVotes
                                       .FirstOrDefault(x =>
                                                       x.MessageId == message.Id
                                                       );

                            Database.StarboardVotes
                            .RemoveRange(Database.StarboardVotes.ToList()
                                         .Where(x => x.MessageId == message.Id));

                            var chan = await guildChannel.Guild
                                       .GetTextChannelAsync(gld.StarboardChannel)
                                       .ConfigureAwait(false);

                            var starMessage = await chan
                                              .GetMessageAsync(vote.StarboardMessageId)
                                              .ConfigureAwait(false);

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

                            await Database.SaveChangesAsync()
                            .ConfigureAwait(false);
                        }
                    }
                }
            }
        }
Exemple #13
0
        private static async Task InsertCommandAsync(CommandInfo command, User user)
        {
            var name = command.Name ?? command.Module.Name;

            if (string.IsNullOrEmpty(name))
            {
                if (command.Module.IsSubmodule)
                {
                    ModuleInfo parentModule = command.Module.Parent;
                    while (string.IsNullOrEmpty(name))
                    {
                        name = parentModule.Name;

                        if (string.IsNullOrEmpty(name) && parentModule.IsSubmodule)
                        {
                            parentModule = parentModule.Parent;
                        }
                        else if (string.IsNullOrEmpty(name) && !parentModule.IsSubmodule)
                        {
                            break;
                        }
                    }
                }
            }

            if (string.IsNullOrEmpty(name))
            {
                return;
            }

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

            var experience = Database.UserCommandUsage.FirstOrDefault(x => x.UserId == user.Id && x.Command.ToLower() == name.ToLower());

            if (experience != null)
            {
                experience.Usage += 1;
            }
            else
            {
                Database.UserCommandUsage.Add(new UserCommandUsage
                {
                    Command = name,
                    UserId  = user.Id,
                    Usage   = 1
                });
            }

            await Database.SaveChangesAsync().ConfigureAwait(false);
        }
Exemple #14
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);
        }
Exemple #15
0
        private static async Task HandlePersistentRoleRemove(
            SocketGuildUser arg1,
            SocketGuildUser arg2)
        {
            using SkuldDbContext database = new SkuldDbContextFactory()
                                            .CreateDbContext();

            IEnumerable <SocketRole> roleDifference;

            if (arg1.Roles.Count > arg2.Roles.Count)
            {
                roleDifference = arg1.Roles.Except(arg2.Roles);
            }
            else
            {
                roleDifference = arg2.Roles.Except(arg1.Roles);
            }

            var guildPersistentRoles = database.PersistentRoles
                                       .AsQueryable()
                                       .Where(x => x.GuildId == arg2.Guild.Id)
                                       .DistinctBy(x => x.RoleId)
                                       .ToList();

            var roles = new List <ulong>();

            guildPersistentRoles.ForEach(z =>
            {
                if (roleDifference.Any(x => x.Id == z.RoleId))
                {
                    roles.Add(z.RoleId);
                }
            });

            if (roles.Any())
            {
                database.PersistentRoles.RemoveRange(
                    database.PersistentRoles.ToList()
                    .Where(x =>
                           roles.Contains(x.RoleId) &&
                           x.UserId == arg2.Id &&
                           x.GuildId == arg2.Guild.Id
                           )
                    );

                await database.SaveChangesAsync().ConfigureAwait(false);
            }
        }
Exemple #16
0
        private static async Task HandlePersistentRoleAdd(
            SocketGuildUser arg
            )
        {
            using SkuldDbContext database = new SkuldDbContextFactory()
                                            .CreateDbContext();

            var guildPersistentRoles = database.PersistentRoles
                                       .AsQueryable()
                                       .Where(x => x.GuildId == arg.Guild.Id)
                                       .DistinctBy(x => x.RoleId)
                                       .ToList();

            if (guildPersistentRoles.Any())
            {
                guildPersistentRoles.ForEach(z =>
                {
                    arg.Roles.ToList().ForEach(x =>
                    {
                        if (z.RoleId == x.Id)
                        {
                            if (!database.PersistentRoles
                                .Any(y => y.RoleId == z.RoleId &&
                                     y.UserId == arg.Id &&
                                     y.GuildId == arg.Guild.Id)
                                )
                            {
                                database.PersistentRoles.Add(
                                    new PersistentRole
                                {
                                    GuildId = arg.Guild.Id,
                                    RoleId  = z.RoleId,
                                    UserId  = arg.Id
                                }
                                    );
                            }
                        }
                    });
                });

                await database.SaveChangesAsync().ConfigureAwait(false);
            }
        }
Exemple #17
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);
        }
Exemple #18
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);
        }
Exemple #19
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);
            }
        }
Exemple #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);
            }
        }
Exemple #21
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);
            }
        }
Exemple #22
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);
        }
Exemple #23
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);
        }
Exemple #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);
                });
            }
        }
Exemple #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);
            }
        }
Exemple #26
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;
            }
        }
Exemple #27
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);
            }
        }
Exemple #28
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));
        }
Exemple #29
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);
        }
Exemple #30
0
        public async Task Merge(ulong oldId, ulong newId)
        {
            if (Context.Client.GetUser(newId) == null)
            {
                await $"No. {newId} is not a valid user Id"
                .QueueMessageAsync(Context).ConfigureAwait(false);
                return;
            }
            if (newId == oldId)
            {
                await $"No.".QueueMessageAsync(Context).ConfigureAwait(false);
                return;
            }
            try
            {
                //UserAccount
                {
                    using var db = new SkuldDbContextFactory()
                                   .CreateDbContext();

                    var oldUser = db.Users.Find(oldId);
                    var newUser = db.Users.Find(newId);

                    if (oldUser != null && newUser != null)
                    {
                        TransactionService.DoTransaction(new TransactionStruct
                        {
                            Amount   = oldUser.Money,
                            Receiver = newUser
                        });
                        newUser.Title          = oldUser.Title;
                        newUser.Language       = oldUser.Language;
                        newUser.Patted         = oldUser.Patted;
                        newUser.Pats           = oldUser.Pats;
                        newUser.UnlockedCustBG = oldUser.UnlockedCustBG;
                        newUser.Background     = oldUser.Background;

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

                //Reputation
                {
                    using var db = new SkuldDbContextFactory()
                                   .CreateDbContext();

                    var repee = db.Reputations.AsQueryable()
                                .Where(x => x.Repee == oldId);
                    var reper = db.Reputations.AsQueryable()
                                .Where(x => x.Reper == oldId);

                    if (repee.Any())
                    {
                        foreach (var rep in repee)
                        {
                            if (!db.Reputations
                                .Any(x =>
                                     x.Repee == newId &&
                                     x.Reper == rep.Reper
                                     )
                                )
                            {
                                rep.Repee = newId;
                            }
                        }
                    }

                    if (reper.Any())
                    {
                        foreach (var rep in reper)
                        {
                            if (!db.Reputations
                                .Any(x =>
                                     x.Reper == newId &&
                                     x.Repee == rep.Repee
                                     )
                                )
                            {
                                rep.Reper = newId;
                            }
                        }
                    }

                    if (repee.Any() || reper.Any())
                    {
                        await db.SaveChangesAsync().ConfigureAwait(false);
                    }
                }

                //Pastas
                {
                    using var db = new SkuldDbContextFactory()
                                   .CreateDbContext();

                    var pastas = db.Pastas.AsQueryable()
                                 .Where(x => x.OwnerId == oldId);

                    if (pastas.Any())
                    {
                        foreach (var pasta in pastas)
                        {
                            pasta.OwnerId = newId;
                        }

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

                //PastaVotes
                {
                    using var db = new SkuldDbContextFactory()
                                   .CreateDbContext();

                    var pastaVotes = db.PastaVotes.AsQueryable()
                                     .Where(x => x.VoterId == oldId);

                    if (pastaVotes.Any())
                    {
                        foreach (var pasta in pastaVotes)
                        {
                            pasta.VoterId = newId;
                        }
                    }

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

                //CommandUsage
                {
                    using var db = new SkuldDbContextFactory()
                                   .CreateDbContext();

                    var commands = db.UserCommandUsage.AsQueryable()
                                   .Where(x => x.UserId == oldId);

                    if (commands.Any())
                    {
                        foreach (var command in commands)
                        {
                            command.UserId = newId;
                        }

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

                //Experience
                {
                    using var db = new SkuldDbContextFactory()
                                   .CreateDbContext();

                    var experiences = db.UserXp.AsQueryable()
                                      .Where(x => x.UserId == oldId);

                    var newExperiences = db.UserXp.AsQueryable()
                                         .Where(x => x.UserId == newId);

                    if (experiences.Any() && !newExperiences.Any())
                    {
                        foreach (var experience in experiences)
                        {
                            experience.UserId = newId;
                        }
                    }
                    else if (experiences.Any() && newExperiences.Any())
                    {
                        foreach (var experience in experiences)
                        {
                            if (newExperiences
                                .Any(x =>
                                     x.GuildId == experience.GuildId
                                     )
                                )
                            {
                                var xp = newExperiences
                                         .FirstOrDefault(x =>
                                                         x.GuildId == experience.GuildId
                                                         );

                                xp.TotalXP = xp.TotalXP
                                             .Add(experience.TotalXP);
                            }
                        }
                    }

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

                //Prune Old User
                {
                    using var db = new SkuldDbContextFactory().CreateDbContext();

                    await db.DropUserAsync(oldId).ConfigureAwait(false);
                }

                await $"Successfully merged data from {oldId} into {newId}".QueueMessageAsync(Context).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Log.Error("MergeCmd", ex.Message, Context, ex);
                await "Check the console log".QueueMessageAsync(Context).ConfigureAwait(false);
            }
        }