Beispiel #1
0
        public async Task ModifyPointsTCAsync(ulong id, [FromBody, Required] long value)
        {
            using (var db = new Database.UserContext(_config))
            {
                var user = db.Users.FirstOrDefault(x => x.Shinden == id);
                if (user == null)
                {
                    await "User not found!".ToResponse(404).ExecuteResultAsync(ControllerContext);
                    return;
                }

                var exe = new Executable($"api-tc su{id}", new Task(() =>
                {
                    using (var dbs = new Database.UserContext(_config))
                    {
                        user        = dbs.Users.FirstOrDefault(x => x.Shinden == id);
                        user.TcCnt += value;

                        dbs.SaveChanges();

                        QueryCacheManager.ExpireTag(new string[] { $"user-{user.Id}", "users" });
                    }
                }));

                await _executor.TryAdd(exe, TimeSpan.FromSeconds(1));

                await "TC added!".ToResponse(200).ExecuteResultAsync(ControllerContext);
            }
        }
Beispiel #2
0
        public async Task ShowTopAsync([Summary("rodzaj topki(poziom/sc/tc/posty(m/ms)/karty)")] TopType type = TopType.Level)
        {
            var session = new ListSession <string>(Context.User, Context.Client.CurrentUser);
            await _session.KillSessionIfExistAsync(session);

            using (var db = new Database.UserContext(Config))
            {
                var users = await db.GetCachedAllUsersAsync();

                session.ListItems = _profile.BuildListView(_profile.GetTopUsers(users, type), type, Context.Guild);
            }

            session.Event = ExecuteOn.ReactionAdded;
            session.Embed = new EmbedBuilder
            {
                Color = EMType.Info.Color(),
                Title = $"Topka {type.Name()}"
            };

            var msg = await ReplyAsync("", embed : session.BuildPage(0));

            await msg.AddReactionsAsync(new[] { new Emoji("⬅"), new Emoji("➡") });

            session.Message = msg;
            await _session.TryAddSession(session);
        }
Beispiel #3
0
        public async Task ChangeBackgroundAsync([Summary("bezpośredni adres do obrazka (450 x 150)")] string imgUrl)
        {
            using (var db = new Database.UserContext(Config))
            {
                var botuser = await db.GetUserOrCreateAsync(Context.User.Id);

                if (botuser.ScCnt < 5000)
                {
                    await ReplyAsync("", embed : $"{Context.User.Mention} nie posiadasz wystarczającej liczby SC!".ToEmbedMessage(EMType.Error).Build());

                    return;
                }

                if (await _profile.SaveProfileImageAsync(imgUrl, $"./GOut/Saved/BG{botuser.Id}.png", 450, 150, true))
                {
                    botuser.BackgroundProfileUri = $"./GOut/Saved/BG{botuser.Id}.png";
                }
                else
                {
                    await ReplyAsync("", embed : "Nie wykryto obrazka! Upewnij się, że podałeś poprawny adres!".ToEmbedMessage(EMType.Error).Build());

                    return;
                }

                botuser.ScCnt -= 5000;

                await db.SaveChangesAsync();

                QueryCacheManager.ExpireTag(new string[] { $"user-{botuser.Id}", "users" });

                await ReplyAsync("", embed : $"Zmieniono tło profilu użytkownika: {Context.User.Mention}!".ToEmbedMessage(EMType.Success).Build());
            }
        }
Beispiel #4
0
        public async Task GiveHourlyScAsync()
        {
            using (var db = new Database.UserContext(Config))
            {
                var botuser = await db.GetUserOrCreateAsync(Context.User.Id);

                var hourly = botuser.TimeStatuses.FirstOrDefault(x => x.Type == Database.Models.StatusType.Hourly);
                if (hourly == null)
                {
                    hourly = new Database.Models.TimeStatus
                    {
                        Type   = Database.Models.StatusType.Hourly,
                        EndsAt = DateTime.MinValue
                    };
                    botuser.TimeStatuses.Add(hourly);
                }

                if (hourly.IsActive())
                {
                    var timeTo = (int)hourly.RemainingSeconds();
                    await ReplyAsync("", embed : $"{Context.User.Mention} następne zaskórniaki możesz otrzymać dopiero za {timeTo / 60}m {timeTo % 60}s!".ToEmbedMessage(EMType.Error).Build());

                    return;
                }

                hourly.EndsAt  = DateTime.Now.AddHours(1);
                botuser.ScCnt += 5;

                await db.SaveChangesAsync();

                QueryCacheManager.ExpireTag(new string[] { $"user-{botuser.Id}", "users" });

                await ReplyAsync("", embed : $"{Context.User.Mention} łap piątaka!".ToEmbedMessage(EMType.Success).Build());
            }
        }
Beispiel #5
0
 public async Task <Database.Models.User> GetUserByDiscordIdAsync(ulong id)
 {
     using (var db = new Database.UserContext(_config))
     {
         return(await db.GetCachedFullUserAsync(id));
     }
 }
Beispiel #6
0
        public async Task SlotMachineSettingsAsync([Summary("typ nastaw(info - wyświetla informacje)")] SlotMachineSetting setting = SlotMachineSetting.Info, [Summary("wartość nastawy")] string value = "info")
        {
            if (setting == SlotMachineSetting.Info)
            {
                await ReplyAsync("", false, $"{_fun.GetSlotMachineInfo()}".ToEmbedMessage(EMType.Info).Build());

                return;
            }

            using (var db = new Database.UserContext(Config))
            {
                var botuser = await db.GetUserOrCreateAsync(Context.User.Id);

                if (!botuser.ApplySlotMachineSetting(setting, value))
                {
                    await ReplyAsync("", embed : $"Podano niewłaściwą wartość parametru!".ToEmbedMessage(EMType.Error).Build());

                    return;
                }

                await db.SaveChangesAsync();

                QueryCacheManager.ExpireTag(new string[] { $"user-{botuser.Id}", "users" });
            }

            await ReplyAsync("", embed : $"{Context.User.Mention} zmienił nastawy automatu.".ToEmbedMessage(EMType.Success).Build());
        }
Beispiel #7
0
        public async Task ShowRiddleAsync()
        {
            var riddles = new List <Question>();

            using (var db = new Database.UserContext(Config))
            {
                riddles = await db.GetCachedAllQuestionsAsync();
            }

            riddles = riddles.Shuffle().ToList();
            var riddle = riddles.FirstOrDefault();

            riddle.Answers = riddle.Answers.OrderBy(x => x.Number).ToList();

            var msg = await ReplyAsync(riddle.Get());

            await msg.AddReactionsAsync(riddle.GetEmotes());

            await Task.Delay(15000);

            var react = await msg.GetReactionUsersAsync(riddle.GetRightEmote(), 100).FlattenAsync();

            await msg.RemoveAllReactionsAsync();

            if (react.Any(x => x.Id == Context.User.Id))
            {
                await ReplyAsync("", false, $"{Context.User.Mention} zgadłeś!".ToEmbedMessage(EMType.Success).Build());
            }
            else
            {
                await ReplyAsync("", false, $"{Context.User.Mention} pudło!".ToEmbedMessage(EMType.Error).Build());
            }
        }
Beispiel #8
0
        public async Task RestoreCardsAsync([Summary("użytkownik")] SocketGuildUser user)
        {
            using (var db = new Database.UserContext(Config))
            {
                var bUser = await db.GetUserOrCreateAsync(user.Id);

                var thisCards = db.Cards.Include(x => x.TagList).Where(x => (x.LastIdOwner == user.Id || (x.FirstIdOwner == user.Id && x.LastIdOwner == 0)) && x.GameDeckId == 1).ToList();
                if (thisCards.Count < 1)
                {
                    await ReplyAsync("", embed : "Nie odnaleziono kart!".ToEmbedMessage(EMType.Bot).Build());

                    return;
                }

                string reply = $"Karta {thisCards.First().GetString(false, false, true)} została przeniesiona.";
                if (thisCards.Count > 1)
                {
                    reply = $"Przeniesiono {thisCards.Count} kart.";
                }

                foreach (var thisCard in thisCards)
                {
                    thisCard.Active = false;
                    thisCard.InCage = false;
                    thisCard.TagList.Clear();
                    thisCard.GameDeckId = user.Id;
                }

                await db.SaveChangesAsync();

                QueryCacheManager.ExpireTag(new string[] { $"user-{Context.User.Id}", "users" });

                await ReplyAsync("", embed : reply.ToEmbedMessage(EMType.Success).Build());
            }
        }
Beispiel #9
0
        public async Task FactoryUserAsync([Summary("id użytkownika")] ulong id, [Summary("czy usunąć karty?")] bool cards = false)
        {
            using (var db = new Database.UserContext(Config))
            {
                var fakeu = await db.GetUserOrCreateAsync(1);

                var user = await db.GetUserOrCreateAsync(id);

                if (!cards)
                {
                    foreach (var card in user.GameDeck.Cards)
                    {
                        card.InCage = false;
                        card.TagList.Clear();
                        card.LastIdOwner = id;
                        fakeu.GameDeck.Cards.Add(card);
                    }
                    user.GameDeck.Cards.Clear();
                }

                db.Users.Remove(user);
                await db.SaveChangesAsync();

                QueryCacheManager.ExpireTag(new string[] { "users", $"user-{id}" });
            }

            await ReplyAsync("", embed : $"Użytkownik o id: `{id}` został wymazany.".ToEmbedMessage(EMType.Success).Build());
        }
Beispiel #10
0
        public async Task ForceUpdateCardsAsync([Summary("WID kart")] params ulong[] ids)
        {
            using (var db = new Database.UserContext(Config))
            {
                var cards = db.Cards.Where(x => ids.Any(c => c == x.Id)).ToList();
                if (cards.Count < 1)
                {
                    await ReplyAsync("", embed : $"{Context.User.Mention} nie odnaleziono kart.".ToEmbedMessage(EMType.Error).Build());

                    return;
                }

                foreach (var card in cards)
                {
                    try
                    {
                        await card.Update(null, _shClient);

                        _waifu.DeleteCardImageIfExist(card);
                    }
                    catch (Exception) { }
                }

                await db.SaveChangesAsync();

                QueryCacheManager.ExpireTag(new string[] { $"users" });

                await ReplyAsync("", embed : $"Zaktualizowano {cards.Count} kart.".ToEmbedMessage(EMType.Success).Build());
            }
        }
Beispiel #11
0
        public async Task TransferCardAsync([Summary("użytkownik")] SocketGuildUser user, [Summary("WIDs")] params ulong[] wids)
        {
            using (var db = new Database.UserContext(Config))
            {
                var thisCards = db.Cards.Include(x => x.TagList).Where(x => wids.Any(c => c == x.Id)).ToList();
                if (thisCards.Count < 1)
                {
                    await ReplyAsync("", embed : "Nie odnaleziono kart!".ToEmbedMessage(EMType.Bot).Build());

                    return;
                }

                string reply = $"Karta {thisCards.First().GetString(false, false, true)} została przeniesiona.";
                if (thisCards.Count > 1)
                {
                    reply = $"Przeniesiono {thisCards.Count} kart.";
                }

                foreach (var thisCard in thisCards)
                {
                    thisCard.Active = false;
                    thisCard.InCage = false;
                    thisCard.TagList.Clear();
                    thisCard.GameDeckId = user.Id;
                }

                await db.SaveChangesAsync();

                QueryCacheManager.ExpireTag(new string[] { $"user-{Context.User.Id}", "users" });

                await ReplyAsync("", embed : reply.ToEmbedMessage(EMType.Success).Build());
            }
        }
Beispiel #12
0
        public async Task RepairCardsAsync(ulong oldId, ulong newId)
        {
            var response = await _shClient.GetCharacterInfoAsync(newId);

            if (!response.IsSuccessStatusCode())
            {
                await "New character ID is invalid!".ToResponse(500).ExecuteResultAsync(ControllerContext);
                return;
            }

            var exe = new Executable($"api-repair oc{oldId} c{newId}", new Task(() =>
            {
                using (var db = new Database.UserContext(_config))
                {
                    var cards = db.Cards.Where(x => x.Character == oldId);
                    foreach (var card in cards)
                    {
                        card.Character = newId;
                    }

                    db.SaveChanges();

                    QueryCacheManager.ExpireTag(new string[] { "users" });
                }
            }));

            await _executor.TryAdd(exe, TimeSpan.FromSeconds(1));

            await "Success".ToResponse(200).ExecuteResultAsync(ControllerContext);
        }
Beispiel #13
0
        public async Task ToggleCardStatusAsync(ulong wid)
        {
            var currUser = ControllerContext.HttpContext.User;

            if (currUser.HasClaim(x => x.Type == "DiscordId"))
            {
                if (ulong.TryParse(currUser.Claims.First(x => x.Type == "DiscordId").Value, out var discordId))
                {
                    using (var db = new Database.UserContext(_config))
                    {
                        var botUserCh = await db.GetCachedFullUserAsync(discordId);

                        if (botUserCh == null)
                        {
                            await "User not found!".ToResponse(404).ExecuteResultAsync(ControllerContext);
                            return;
                        }

                        var thisCardCh = botUserCh.GameDeck.Cards.FirstOrDefault(x => x.Id == wid);
                        if (thisCardCh == null)
                        {
                            await "Card not found!".ToResponse(404).ExecuteResultAsync(ControllerContext);
                            return;
                        }

                        if (thisCardCh.InCage)
                        {
                            await "Card is in cage!".ToResponse(403).ExecuteResultAsync(ControllerContext);
                            return;
                        }

                        if (!thisCardCh.Active && botUserCh.GameDeck.Cards.Where(x => x.Active).Count() >= 3)
                        {
                            await "Limit of active cards triggered!".ToResponse(403).ExecuteResultAsync(ControllerContext);
                            return;
                        }
                    }

                    var exe = new Executable($"api-deck u{discordId}", new Task(() =>
                    {
                        using (var db = new Database.UserContext(_config))
                        {
                            var botUser     = db.GetUserOrCreateAsync(discordId).Result;
                            var thisCard    = botUser.GameDeck.Cards.FirstOrDefault(x => x.Id == wid);
                            thisCard.Active = !thisCard.Active;

                            db.SaveChanges();

                            QueryCacheManager.ExpireTag(new string[] { $"user-{botUser.Id}", "users" });
                        }
                    }));

                    await _executor.TryAdd(exe, TimeSpan.FromSeconds(1));

                    await "Card status toggled".ToResponse(200).ExecuteResultAsync(ControllerContext);
                    return;
                }
            }
            await "The appropriate claim was not found".ToResponse(403).ExecuteResultAsync(ControllerContext);
        }
Beispiel #14
0
 public async Task <IEnumerable <Database.Models.Card> > GetCardsWithTagAsync(string tag)
 {
     using (var db = new Database.UserContext(_config))
     {
         return(await db.Cards.Include(x => x.ArenaStats).Where(x => x.Tags != null).Where(x => x.Tags.Contains(tag, StringComparison.CurrentCultureIgnoreCase)).ToListAsync());
     }
 }
Beispiel #15
0
        private async Task CyclicCheckAsync(Database.UserContext context, Database.GuildConfigContext guildContext)
        {
            var subs = context.TimeStatuses.AsNoTracking().FromCache(new[] { "users" }).Where(x => x.Type.IsSubType());

            foreach (var sub in subs)
            {
                if (sub.IsActive())
                {
                    continue;
                }

                var guild = _client.GetGuild(sub.Guild);
                switch (sub.Type)
                {
                case StatusType.Globals:
                    var guildConfig = await guildContext.GetCachedGuildFullConfigAsync(sub.Guild);
                    await RemoveRoleAsync(guild, guildConfig?.GlobalEmotesRole ?? 0, sub.UserId);

                    break;

                case StatusType.Color:
                    await RomoveUserColorAsync(guild.GetUser(sub.UserId));

                    break;

                default:
                    break;
                }
            }
        }
Beispiel #16
0
        public async Task ChangeTitleCardAsync([Summary("WID")] ulong wid, [Summary("tytuł")][Remainder] string title = null)
        {
            using (var db = new Database.UserContext(Config))
            {
                var thisCard = db.Cards.FirstOrDefault(x => x.Id == wid);
                if (thisCard == null)
                {
                    await ReplyAsync("", embed : $"Taka karta nie istnieje.".ToEmbedMessage(EMType.Error).Build());

                    return;
                }

                if (title != null)
                {
                    thisCard.Title = title;
                }
                else
                {
                    var res = await _shClient.GetCharacterInfoAsync(thisCard.Character);

                    if (res.IsSuccessStatusCode())
                    {
                        thisCard.Title = res.Body?.Relations?.OrderBy(x => x.Id)?.FirstOrDefault()?.Title ?? "????";
                    }
                }

                await db.SaveChangesAsync();

                QueryCacheManager.ExpireTag(new string[] { "users" });

                await ReplyAsync("", embed : $"Nowy tytuł to: `{thisCard.Title}`".ToEmbedMessage(EMType.Success).Build());
            }
        }
Beispiel #17
0
        public Profile(DiscordSocketClient client, ShindenClient shClient, ImageProcessing img, ILogger logger, IConfig config)
        {
            _shClient = shClient;
            _client   = client;
            _logger   = logger;
            _config   = config;
            _img      = img;

            _timer = new Timer(async _ =>
            {
                try
                {
                    using (var db = new Database.UserContext(_config))
                    {
                        using (var dbg = new Database.GuildConfigContext(_config))
                        {
                            await CyclicCheckAsync(db, dbg);
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.Log($"in profile check: {ex}");
                }
            },
                               null,
                               TimeSpan.FromMinutes(1),
                               TimeSpan.FromMinutes(1));
        }
Beispiel #18
0
        public async Task GenerateItemAsync([Summary("użytkownik")] SocketGuildUser user, [Summary("przedmiot")] ItemType itemType, [Summary("liczba przedmiotów")] uint count = 1,
                                            [Summary("jakość przedmiotu")] Quality quality = Quality.Broken)
        {
            var item = itemType.ToItem(count, quality);

            using (var db = new Database.UserContext(Config))
            {
                var botuser = await db.GetUserOrCreateAsync(user.Id);

                var thisItem = botuser.GameDeck.Items.FirstOrDefault(x => x.Type == item.Type && x.Quality == item.Quality);
                if (thisItem == null)
                {
                    thisItem = item;
                    botuser.GameDeck.Items.Add(thisItem);
                }
                else
                {
                    thisItem.Count += count;
                }

                await db.SaveChangesAsync();

                QueryCacheManager.ExpireTag(new string[] { $"user-{botuser.Id}", "users" });

                string cnt = (count > 1) ? $" x{count}" : "";
                await ReplyAsync("", embed : $"{user.Mention} otrzymał _{item.Name}_{cnt}.".ToEmbedMessage(EMType.Success).Build());
            }
        }
Beispiel #19
0
        public async Task PlayOnSlotMachineAsync([Summary("typ(info - wyświetla informacje)")] string type = "game")
        {
            if (type != "game")
            {
                await ReplyAsync("", false, $"{_fun.GetSlotMachineGameInfo()}".ToEmbedMessage(EMType.Info).Build());

                return;
            }

            using (var db = new Database.UserContext(Config))
            {
                var botuser = await db.GetUserOrCreateAsync(Context.User.Id);

                var machine = new SlotMachine(botuser);

                var toPay = machine.ToPay();
                if (botuser.ScCnt < toPay)
                {
                    await ReplyAsync("", embed : $"{Context.User.Mention} brakuje Ci SC, aby za tyle zagrać.".ToEmbedMessage(EMType.Error).Build());

                    return;
                }
                var win = machine.Play(new SlotEqualRandom());
                botuser.ScCnt += win - toPay;

                await db.SaveChangesAsync();

                QueryCacheManager.ExpireTag(new string[] { $"user-{botuser.Id}", "users" });

                await ReplyAsync("", embed : $"{_fun.GetSlotMachineResult(machine.Draw(), Context.User, botuser, win)}".ToEmbedMessage(EMType.Bot).Build());
            }
        }
Beispiel #20
0
        public async Task <UserWithToken> GetUserByShindenIdSimpleAsync(ulong id)
        {
            using (var db = new Database.UserContext(_config))
            {
                var user = db.Users.Where(x => x.Shinden == id).Include(x => x.GameDeck).AsNoTracking().FirstOrDefault();
                if (user == null)
                {
                    await "User not found!".ToResponse(404).ExecuteResultAsync(ControllerContext);
                    return(null);
                }

                TokenData tokenData = null;
                var       currUser  = ControllerContext.HttpContext.User;
                if (currUser.HasClaim(x => x.Type == ClaimTypes.Webpage))
                {
                    tokenData = UserTokenBuilder.BuildUserToken(_config, user);
                }

                return(new UserWithToken()
                {
                    Expire = tokenData?.Expire,
                    Token = tokenData?.Token,
                    User = user,
                });
            }
        }
Beispiel #21
0
        public async Task GiveDailyScAsync()
        {
            using (var db = new Database.UserContext(Config))
            {
                var botuser = await db.GetUserOrCreateAsync(Context.User.Id);

                var daily = botuser.TimeStatuses.FirstOrDefault(x => x.Type == Database.Models.StatusType.Daily);
                if (daily == null)
                {
                    daily = new Database.Models.TimeStatus
                    {
                        Type   = Database.Models.StatusType.Daily,
                        EndsAt = DateTime.MinValue
                    };
                    botuser.TimeStatuses.Add(daily);
                }

                if (daily.IsActive())
                {
                    var timeTo = (int)daily.RemainingMinutes();
                    await ReplyAsync("", embed : $"{Context.User.Mention} następne drobne możesz otrzymać dopiero za {timeTo / 60}h {timeTo % 60}m!".ToEmbedMessage(EMType.Error).Build());

                    return;
                }

                daily.EndsAt   = DateTime.Now.AddHours(20);
                botuser.ScCnt += 100;

                await db.SaveChangesAsync();

                QueryCacheManager.ExpireTag(new string[] { $"user-{botuser.Id}" });

                await ReplyAsync("", embed : $"{Context.User.Mention} łap drobne na waciki!".ToEmbedMessage(EMType.Success).Build());
            }
        }
Beispiel #22
0
        private Executable GetSafariExe(EmbedBuilder embed, IUserMessage msg, Card newCard,
                                        SafariImage pokeImage, ICharacterInfo character, ITextChannel trashChannel, IUser winner)
        {
            return(new Executable("safari", new Task(() =>
            {
                using (var db = new Database.UserContext(_config))
                {
                    var botUser = db.GetUserOrCreateAsync(winner.Id).Result;

                    newCard.FirstIdOwner = winner.Id;
                    newCard.Affection += botUser.GameDeck.AffectionFromKarma();
                    botUser.GameDeck.RemoveCharacterFromWishList(newCard.Character);

                    botUser.GameDeck.Cards.Add(newCard);
                    db.SaveChanges();

                    QueryCacheManager.ExpireTag(new string[] { $"user-{botUser.Id}", "users" });

                    using (var dba = new Database.AnalyticsContext(_config))
                    {
                        dba.UsersData.Add(new Database.Models.Analytics.UserAnalytics
                        {
                            Value = 1,
                            UserId = winner.Id,
                            MeasureDate = DateTime.Now,
                            GuildId = trashChannel?.Guild?.Id ?? 0,
                            Type = Database.Models.Analytics.UserAnalyticsEventType.Card
                        });
                        dba.SaveChanges();
                    }
                }

                _ = Task.Run(async() =>
                {
                    try
                    {
                        embed.ImageUrl = await _waifu.GetSafariViewAsync(pokeImage, newCard, trashChannel);
                        embed.Description = $"{winner.Mention} zdobył na polowaniu i wsadził do klatki:\n"
                                            + $"{newCard.GetString(false, false, true)}\n({newCard.Title})";
                        await msg.ModifyAsync(x => x.Embed = embed.Build());

                        var privEmb = new EmbedBuilder()
                        {
                            Color = EMType.Info.Color(),
                            Description = $"Na [polowaniu]({msg.GetJumpUrl()}) zdobyłeś: {newCard.GetString(false, false, true)}"
                        };

                        var priv = await winner.GetOrCreateDMChannelAsync();
                        if (priv != null)
                        {
                            await priv.SendMessageAsync("", false, privEmb.Build());
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.Log($"In Safari: {ex}");
                    }
                });
            })));
        }
Beispiel #23
0
        public IExecutable GetExecutableGMwK(FightHistory history, List <PlayerInfo> players)
        {
            return(new Executable("GMwK", new Task(() =>
            {
                using (var db = new Database.UserContext(_config))
                {
                    bool isWinner = history.Winner != null;
                    foreach (var p in players)
                    {
                        var u = db.GetUserOrCreateAsync(p.User.Id).Result;
                        var stat = new CardPvPStats
                        {
                            Type = FightType.BattleRoyale,
                            Result = isWinner ? FightResult.Lose : FightResult.Draw
                        };

                        if (isWinner)
                        {
                            if (u.Id == history.Winner.User.Id)
                            {
                                stat.Result = FightResult.Win;
                            }
                        }

                        u.GameDeck.PvPStats.Add(stat);
                    }

                    db.SaveChanges();
                }
            })));
        }
Beispiel #24
0
        private void SpawnUserPacket(SocketUser user)
        {
            var exe = new Executable($"packet u{user.Id}", new Task(() =>
            {
                using (var db = new Database.UserContext(_config))
                {
                    var botUser = db.GetUserOrCreateAsync(user.Id).Result;
                    if (botUser.IsBlacklisted)
                    {
                        return;
                    }

                    botUser.GameDeck.BoosterPacks.Add(new BoosterPack
                    {
                        CardCnt   = 2,
                        MinRarity = Rarity.E,
                        IsCardFromPackTradable = true,
                        Name = "Pakiet kart za aktywność",
                        CardSourceFromPack = CardSource.Activity
                    });
                    db.SaveChanges();
                }
            }));

            _executor.TryAdd(exe, TimeSpan.FromSeconds(1));
        }
Beispiel #25
0
        public async Task <UserWithToken> GetUserByShindenIdAsync(ulong id)
        {
            using (var db = new Database.UserContext(_config))
            {
                var user = await db.GetCachedFullUserByShindenIdAsync(id);

                if (user == null)
                {
                    await "User not found!".ToResponse(404).ExecuteResultAsync(ControllerContext);
                    return(null);
                }

                TokenData tokenData = null;
                var       currUser  = ControllerContext.HttpContext.User;
                if (currUser.HasClaim(x => x.Type == ClaimTypes.Webpage))
                {
                    tokenData = UserTokenBuilder.BuildUserToken(_config, user);
                }

                return(new UserWithToken()
                {
                    Expire = tokenData?.Expire,
                    Token = tokenData?.Token,
                    User = user,
                });
            }
        }
Beispiel #26
0
 public async Task <List <Database.Models.Question> > GetQuestionsAsync()
 {
     using (var db = new Database.UserContext(_config))
     {
         return(await db.GetCachedAllQuestionsAsync());
     }
 }
Beispiel #27
0
        public async Task ShowUserProfileAsync([Summary("użytkownik(opcjonalne)")] SocketGuildUser user = null)
        {
            var usr = user ?? Context.User as SocketGuildUser;

            if (usr == null)
            {
                return;
            }

            using (var db = new Database.UserContext(Config))
            {
                var allUsers = await db.GetCachedAllUsersAsync();

                var botUser = allUsers.FirstOrDefault(x => x.Id == usr.Id);
                if (botUser == null)
                {
                    await ReplyAsync("", embed : "Ta osoba nie ma profilu bota.".ToEmbedMessage(EMType.Error).Build());

                    return;
                }

                using (var stream = await _profile.GetProfileImageAsync(usr, botUser, allUsers.OrderByDescending(x => x.ExpCnt).ToList().IndexOf(botUser) + 1))
                {
                    await Context.Channel.SendFileAsync(stream, $"{usr.Id}.png");
                }
            }
        }
Beispiel #28
0
 public async Task <Database.Models.Question> GetQuestionAsync(ulong id)
 {
     using (var db = new Database.UserContext(_config))
     {
         return(await db.GetCachedQuestionAsync(id));
     }
 }
Beispiel #29
0
        public async Task AddGlobalEmotesAsync()
        {
            var user = Context.User as SocketGuildUser;

            if (user == null)
            {
                return;
            }

            using (var db = new Database.UserContext(Config))
            {
                var botuser = await db.GetUserOrCreateAsync(user.Id);

                if (botuser.TcCnt < 4000)
                {
                    await ReplyAsync("", embed : $"{user.Mention} nie posiadasz wystarczającej liczby TC!".ToEmbedMessage(EMType.Error).Build());

                    return;
                }

                using (var cdb = new Database.GuildConfigContext(Config))
                {
                    var gConfig = await cdb.GetCachedGuildFullConfigAsync(Context.Guild.Id);

                    var gRole = Context.Guild.GetRole(gConfig.GlobalEmotesRole);
                    if (gRole == null)
                    {
                        await ReplyAsync("", embed : "Serwer nie ma ustawionej roli globalnych emotek.".ToEmbedMessage(EMType.Bot).Build());

                        return;
                    }

                    var global = botuser.TimeStatuses.FirstOrDefault(x => x.Type == Database.Models.StatusType.Globals && x.Guild == Context.Guild.Id);
                    if (global == null)
                    {
                        global = new Database.Models.TimeStatus
                        {
                            Type   = StatusType.Globals,
                            Guild  = Context.Guild.Id,
                            EndsAt = DateTime.Now,
                        };
                        botuser.TimeStatuses.Add(global);
                    }

                    if (!user.Roles.Contains(gRole))
                    {
                        await user.AddRoleAsync(gRole);
                    }

                    global.EndsAt  = global.EndsAt.AddMonths(1);
                    botuser.TcCnt -= 4000;
                }

                await db.SaveChangesAsync();

                QueryCacheManager.ExpireTag(new string[] { $"user-{botuser.Id}", "users" });

                await ReplyAsync("", embed : $"{user.Mention} wykupił miesiąc globalnych emotek!".ToEmbedMessage(EMType.Success).Build());
            }
        }
Beispiel #30
0
 public static async Task <List <User> > GetCachedAllUsersAsync(this Database.UserContext context)
 {
     return((await context.Users.Include(x => x.Stats).Include(x => x.SMConfig).Include(x => x.TimeStatuses).Include(x => x.GameDeck).ThenInclude(x => x.PvPStats)
             .Include(x => x.GameDeck).ThenInclude(x => x.Items).Include(x => x.GameDeck).ThenInclude(x => x.Cards).ThenInclude(x => x.ArenaStats).Include(x => x.GameDeck)
             .ThenInclude(x => x.BoosterPacks).ThenInclude(x => x.Characters).Include(x => x.GameDeck).ThenInclude(x => x.BoosterPacks).ThenInclude(x => x.RarityExcludedFromPack)
             .FromCacheAsync(new string[] { $"users" })).ToList());
 }