Esempio n. 1
0
        public async Task DailyCmd()
        {
            bool  newDaily = false;
            Daily daily    = DailyDb.GetDaily(Context.User.Id, Context.Guild.Id);

            if (daily == null)
            {
                daily = new Daily
                {
                    UserId  = Context.User.Id,
                    GuildId = Context.Guild.Id,
                    Date    = 0
                };
                newDaily = true;
            }

            long timeNow = DateTimeOffset.Now.ToUnixTimeMilliseconds();
            int  ms      = 72000000;

            if (PremiumDb.IsPremium(Context.User.Id, ProType.ProPlus))
            {
                ms /= 2;
            }

            if ((daily.Date + ms) < timeNow)
            {
                if ((daily.Date + 172800000) < timeNow && !newDaily)
                {
                    long   mslate     = timeNow - (daily.Date + 172800000);
                    long   dayslate   = (mslate / (1000 * 60 * 60 * 24)) + 1;
                    double multiplier = dayslate > 3 ? 0 : 1 - dayslate * 0.25;
                    daily.Streak = (int)(daily.Streak * multiplier);
                    await ReplyAsync($"You are **{dayslate}** days late to claim your daily. For every day missed, you lose 25% of your streak.");
                }

                daily.Streak++;
                daily.Date = timeNow;
                int amount = ToastieUtil.DailyAmount(daily.Streak);
                int tax    = ToastieUtil.DailyTax(amount, BalanceDb.GetToasties(Context.User.Id, Context.Guild.Id), BalanceDb.GetToasties(Context.Client.CurrentUser.Id, Context.Guild.Id), await BalanceDb.TotalToasties(Context.Guild.Id));
                amount -= tax / 2;
                //int cap = Constants.dailycap;
                //amount = amount > cap ? cap : amount;

                await DailyDb.SetDaily(daily);

                await BalanceDb.AddToasties(Context.User.Id, amount, Context.Guild.Id);

                await BalanceDb.AddToasties(Context.Client.CurrentUser.Id, tax, Context.Guild.Id);

                await Context.Channel.SendMessageAsync("", false, ToastieUtil.DailyGetEmbed(Context.User, daily.Streak, amount, BalanceDb.GetToasties(Context.User.Id, Context.Guild.Id), Program.GetPrefix(Context)).Build());
            }
            else
            {
                long wait    = (daily.Date + ms - timeNow) / 1000;
                int  hours   = (int)wait / 3600;
                int  minutes = (int)wait % 3600 / 60;
                int  seconds = (int)wait % 60;
                await Context.Channel.SendMessageAsync("", false, ToastieUtil.DailyWaitEmbed(Context.User, hours, minutes, seconds, Program.GetPrefix(Context)).Build());
            }
        }
Esempio n. 2
0
        public static async Task <int> SendRewards(IEnumerable <ulong> voters)
        {
            int sent = 0;

            foreach (var x in voters)
            {
                try
                {
                    var type = LootBoxType.Vote;
                    if (PremiumDb.IsPremium(x, ProType.ProPlus))
                    {
                        type = LootBoxType.Premium;
                    }

                    await LootBoxDb.AddLootbox(x, type, 1);

                    sent++;
                    var user = Program.GetClient().GetUser(x);
                    var ch   = await user.CreateDMChannelAsync();

                    await ch.SendMessageAsync(embed : new EmbedBuilderPrepared(user)
                                              .WithDescription($"Thank you for voting for me! I have given you a **{type.ToString()} Lootbox**! :star:\n" +
                                                               $"You can open it in a server of your choice by typing `!open`")
                                              .Build());
                }
                catch { }
            }
            return(sent);
        }
Esempio n. 3
0
 public override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
 {
     try
     {
         if (context.User.Id == AppSettings.OwnerId || ((SocketGuildUser)context.User).Roles.Any(x => x.Id == AppSettings.InsiderRoleId))
         {
             return(Task.FromResult(PreconditionResult.FromSuccess()));
         }
         else if (PremiumDb.IsPremium(context.Guild.Id, ProType.GuildPlus))
         {
             return(Task.FromResult(PreconditionResult.FromSuccess()));
         }
         else
         {
             return(Task.FromResult(PreconditionResult.FromError("This command is only for my insiders or Pro Guild+ Servers.")));
         }
     }
     catch
     {
         if (PremiumDb.IsPremium(context.Guild.Id, ProType.GuildPlus))
         {
             return(Task.FromResult(PreconditionResult.FromSuccess()));
         }
         return(Task.FromResult(PreconditionResult.FromError("This command is only for my insiders or Pro Guild+ Servers.")));
     }
 }
Esempio n. 4
0
        public async Task Weekly()
        {
            var weekly = WeeklyDb.GetWeekly(Context.User.Id, Context.Guild.Id);

            if (weekly == null)
            {
                weekly = new Weekly
                {
                    GuildId = Context.Guild.Id,
                    UserId  = Context.User.Id
                };
            }

            int hours = 164;

            if (PremiumDb.IsPremium(Context.Guild.Id, ProType.Guild) || PremiumDb.IsPremium(Context.Guild.Id, ProType.GuildPlus))
            {
                hours /= 2;
            }

            if (weekly.Date.AddHours(hours).CompareTo(DateTime.Now) < 0)
            {
                int streak = await DailyDb.GetHighest(Context.Guild.Id) + 15;

                int amount = ToastieUtil.DailyAmount(streak);
                int tax    = ToastieUtil.DailyTax(amount, BalanceDb.GetToasties(Context.User.Id, Context.Guild.Id), BalanceDb.GetToasties(Context.Client.CurrentUser.Id, Context.Guild.Id), await BalanceDb.TotalToasties(Context.Guild.Id));
                amount -= tax / 2;
                if (PremiumDb.IsPremium(Context.Guild.Id, ProType.GuildPlus))
                {
                    amount += 1000;
                }

                string text = "";
                if (PremiumDb.IsPremium(Context.User.Id, ProType.ProPlus))
                {
                    await LootBoxDb.AddLootbox(Context.User.Id, LootBoxType.WaifuT1, 1, Context.Guild.Id);

                    text = "You receive a T1 Waifu lootbox! :star2:";
                }

                await BalanceDb.AddToasties(Context.User.Id, amount, Context.Guild.Id);

                await BalanceDb.AddToasties(Context.Client.CurrentUser.Id, tax / 2, Context.Guild.Id);

                weekly.Date = DateTime.Now;
                await WeeklyDb.SetWeekly(weekly);

                await Context.Channel.SendMessageAsync(text, false, ToastieUtil.WeeklyGetEmbed(amount, BalanceDb.GetToasties(Context.User.Id, Context.Guild.Id), Context.User, Program.GetPrefix(Context)).Build());

                return;
            }

            await Context.Channel.SendMessageAsync("", false, ToastieUtil.WeeklyWaitEmbed(weekly.Date.AddHours(hours), Context.User, Program.GetPrefix(Context)).Build());
        }
Esempio n. 5
0
        public async Task WishWaifu([Remainder] string str = "")
        {
            var   user  = Context.User;
            Waifu waifu = await WaifuUtil.ProcessWaifuListAndRespond(await WaifuDb.SearchWaifus(str), this);

            if (waifu == null)
            {
                return;
            }

            var waifus = await WaifuWishlistDb.GetWishlist(user.Id, Context.Guild.Id);

            int cap = 5;

            if (PremiumDb.IsPremium(Context.User.Id, ProType.ProPlus))
            {
                cap = 12;
            }

            string prefix = Program.GetPrefix(Context);

            if (waifus.Count >= cap)
            {
                await Context.Channel.SendMessageAsync(embed : new EmbedBuilderPrepared(Context.User)
                                                       .WithDescription($"You have reached your wishlist limit of **{cap}**.\n" +
                                                                        $"Try `{prefix}rww` to remove a waifu.")
                                                       .WithFooter($"Increase the limit: `{prefix}pro`")
                                                       .Build());

                return;
            }

            if (waifus.Any(x => x.Name == waifu.Name))
            {
                await Context.Channel.SendMessageAsync($"**{waifu.Name}** is already in your wishlist. Baka.");

                return;
            }

            if (UserInventoryDb.OwnsWaifu(user.Id, waifu, Context.Guild.Id))
            {
                await Context.Channel.SendMessageAsync($"You already own **{waifu.Name}**. Baka.");

                return;
            }

            await WaifuWishlistDb.AddWaifuWish(Context.User.Id, waifu, Context.Guild.Id);

            waifus = await WaifuWishlistDb.GetWishlist(user.Id, Context.Guild.Id);

            await Context.Channel.SendMessageAsync($"Added **{waifu.Name}** to your wishlist!", false, WaifuUtil.WishlistEmbed(waifus, (SocketGuildUser)user).Build());
        }
Esempio n. 6
0
        public static async Task<List<ShopWaifu>> GenerateGachaShopList(ulong guildId)
        {
            int t1amount = Constants.gachat1amount;
            int t2amount = Constants.gachat2amount;
            int t3amount = Constants.gachat3amount;
            int pages = 1;
            if (PremiumDb.IsPremium(guildId, ProType.GuildPlus) || PremiumDb.IsPremium(guildId, ProType.Guild))
                pages = 3;
            int randomizerMultiplier = 7 - pages;

            var waifus = new List<Waifu>();

            var gachaSource = GetGachaSources();
            waifus.AddRange(await WaifuDb.RandomWaifus(1, t1amount * pages * randomizerMultiplier, includeSource: gachaSource));
            waifus.AddRange(await WaifuDb.RandomWaifus(2, t2amount * pages * randomizerMultiplier, includeSource: gachaSource));
            waifus.AddRange(await WaifuDb.RandomWaifus(3, t3amount * pages * randomizerMultiplier, includeSource: gachaSource));

            var wishlists = await WaifuWishlistDb.GetAllPremiumWishlists(guildId, ProType.Pro);
            wishlists.RemoveAll(x => !gachaSource.Contains(x.Waifu.Source));
            var ids = wishlists.Select(x => x.UserId).Distinct().ToArray();
            var guild = Program.GetClient().GetGuild(guildId);
            foreach (var id in ids)
            {
                SocketGuildUser user = null;
                try
                {
                    user = guild.GetUser(id);
                }
                catch
                {
                    wishlists.RemoveAll(x => x.UserId == id);
                }
                if (user == null)
                    wishlists.RemoveAll(x => x.UserId == id);
            }
            waifus.AddRange(wishlists.Select(x => x.Waifu));

            ShopWaifu item = null;
            List<ShopWaifu> finalWaifus = new List<ShopWaifu>();
            var rnd = new Random();
            int r = 0;

            for (int k = 0; k < Constants.gachatotal * pages; k++)
            {
                r = rnd.Next(0, waifus.Count);
                item = new ShopWaifu { Waifu = waifus.ElementAt(r), Limited = -1, BoughtBy = 0 };
                finalWaifus.Add(item);
                waifus.RemoveAll(x => x.Name.Equals(waifus[r].Name));
            }

            return finalWaifus.OrderBy(x => x.Waifu.Tier).ToList();
        }
Esempio n. 7
0
        public static EmbedBuilder WeeklyGetEmbed(int amount, int current, IUser user, string prefix)
        {
            var eb = new EmbedBuilder();

            eb.WithAuthor(user.ToString(), user.GetAvatarUrl(), LinkHelper.GetRedirectUrl(LinkHelper.Patreon, "Patreon", "cmd-embed-weekly"));
            eb.WithDescription($"You received **{amount.ToString("n0")}** {RandomEmote()}\nNow you have **{current.ToString("n0")}** {RandomEmote()}");
            eb.WithColor(BasicUtil.RandomColor());

            if (!(PremiumDb.IsPremium(user.Id, ProType.Pro) || PremiumDb.IsPremium(user.Id, ProType.ProPlus)))
            {
                eb.WithFooter($"Check out Pro upgrades! `{prefix}Pro`");
            }
            return(eb);
        }
Esempio n. 8
0
        public static int GetMarriageLimit(ulong userId)
        {
            int limit = Constants.MarriageLimit;

            if (PremiumDb.IsPremium(userId, ProType.Pro))
            {
                limit = Constants.ProMarriageLimit;
            }
            if (PremiumDb.IsPremium(userId, ProType.ProPlus))
            {
                limit = Constants.ProPlusMarriageLimit;
            }

            return(limit);
        }
Esempio n. 9
0
        public static EmbedBuilder DailyGetEmbed(IUser user, int streak, int amount, int balance, string prefix)
        {
            var eb = new EmbedBuilder();

            eb.WithAuthor(user.ToString(), user.GetAvatarUrl(), LinkHelper.GetRedirectUrl(LinkHelper.Patreon, "Patreon", "cmd-embed-daily"));
            eb.WithDescription($"You're on a **{streak.ToString("n0")}** day streak. You receive **{amount.ToString("n0")}** {ToastieUtil.RandomEmote()}\n" +
                               $"Now you have **{balance.ToString("n0")}** {ToastieUtil.RandomEmote()}\n\n" +
                               $"Vote for me on [Discord Bots]({LinkHelper.GetRedirectUrl(LinkHelper.Vote, "Vote", "cmd-daily")}) every day to receive a lootbox!");
            eb.WithColor(BasicUtil.RandomColor());

            if (!(PremiumDb.IsPremium(user.Id, ProType.Pro) || PremiumDb.IsPremium(user.Id, ProType.ProPlus)))
            {
                eb.WithFooter($"Check out Pro upgrades! `{prefix}Pro`");
            }
            return(eb);
        }
Esempio n. 10
0
        // WEEKLIES

        public static EmbedBuilder WeeklyWaitEmbed(DateTime date, IUser user, string prefix)
        {
            var eb = new EmbedBuilder();

            eb.WithAuthor(user.ToString(), user.GetAvatarUrl(), LinkHelper.GetRedirectUrl(LinkHelper.Patreon, "Patreon", "cmd-embed-weekly"));
            DateTime now  = DateTime.Now;
            string   wait = $"{(date - now).Days} Days {(date - now).Hours} Hours {(date - now).Minutes} Minutes";

            eb.WithDescription($"You already claimed your weekly reward.\nYou must wait `{wait}`");
            eb.WithColor(BasicUtil.RandomColor());

            if (!(PremiumDb.IsPremium(user.Id, ProType.Pro) || PremiumDb.IsPremium(user.Id, ProType.ProPlus)))
            {
                eb.WithFooter($"Check out Pro upgrades! `{prefix}Pro`");
            }
            return(eb);
        }
Esempio n. 11
0
        public static EmbedBuilder DailyWaitEmbed(IUser user, int hours, int minutes, int seconds, string prefix)
        {
            var eb = new EmbedBuilder();

            eb.WithAuthor(user.ToString(), user.GetAvatarUrl(), LinkHelper.GetRedirectUrl(LinkHelper.Patreon, "Patreon", "cmd-embed-daily"));
            eb.WithDescription($"You already claimed your daily reward today.\nYou must wait `{hours} hours {minutes} minutes {seconds} seconds`");
            if (new Random().Next(20) == 1)
            {
                eb.WithImageUrl("https://i.imgur.com/LcqpKmo.png");
            }
            eb.WithColor(BasicUtil.RandomColor());

            if (!(PremiumDb.IsPremium(user.Id, ProType.Pro) || PremiumDb.IsPremium(user.Id, ProType.ProPlus)))
            {
                eb.WithFooter($"Check out Pro upgrades! `{prefix}Pro`");
            }
            return(eb);
        }
Esempio n. 12
0
        private async Task Commands_CommandExecuted(Optional <CommandInfo> cmd, ICommandContext context, IResult res)
        {
            string cmdName = cmd.IsSpecified ? cmd.Value.Name : null;
            bool   success = res.IsSuccess;

            if (!res.IsSuccess)
            {
                // Try sending a reaction image if there is no such command
                if (await new Images().SendRandomImage(context))
                {
                    cmdName = "ReactionImage";
                    success = true;
                }

                // If the command is found but failed then send help message for said command
                else
                if (!(res.Error == CommandError.UnknownCommand || res.Error == CommandError.Exception))
                {
                    string reason = res.ErrorReason + "\n";
                    if (res.Error != CommandError.UnmetPrecondition)
                    {
                        reason += CommandHelpString(context.Message.Content.Split(null)[0].Replace(GetPrefix(context.Guild), ""), GetPrefix(context.Guild));
                    }
                    await context.Channel.SendMessageAsync(embed : new EmbedBuilder().WithColor(Color.DarkRed).WithDescription(":x: " + reason).Build());
                }
            }
            // If the command is found and completed but it is a music command in a guild with no premium - set as failed
            else
            if ((cmdName == nameof(Music.Join) || cmdName == nameof(Music.Play) || cmdName == nameof(Music.PlayNext) || cmdName == nameof(Music.PlayFirst)) &&
                !(PremiumDb.IsPremium(context.Guild.Id, ProType.GuildPlus) || PremiumDb.IsPremium(context.Guild.Id, ProType.Guild)))
            {
                success = false;
            }


            // If command is found - save a log of it
            if (cmdName != null && Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") != "Development")
            {
                await Stats.LogCommand(cmdName, context, success);
            }
        }
Esempio n. 13
0
        private static async void Timer_ExpirePremium(object sender, ElapsedEventArgs e)
        {
            var now     = System.DateTime.Now;
            var expired = PremiumDb.GetNewlyExpired();
            var client  = Program.GetClient();
            var ntr     = client.GetGuild((ulong)ProType.HomeGuildId_NOTAPREMIUMTYPE);

            foreach (var premium in expired)
            {
                SocketGuildUser user = null;
                try
                {
                    user = ntr.GetUser(premium.UserId);
                }
                catch { }

                if (user == null)
                {
                    premium.ExpireSent = true;
                    await PremiumDb.UpdatePremium(premium);

                    try
                    {
                        var ch = await client.GetUser(premium.UserId).CreateDMChannelAsync();

                        await ch.SendMessageAsync(embed : new EmbedBuilderPrepared()
                                                  .WithDescription($"Your **{premium.Type.ToString()}** subscription has expired. It's sad to see you go...\n" +
                                                                   $"You can renew your subscription [Here]({LinkHelper.GetRedirectUrl(LinkHelper.Patreon, "Patreon", "pro-expired")})\n" +
                                                                   $"If you think this is a mistake contact taiHen#2839 [Here]({LinkHelper.SupportServerInvite})")
                                                  .Build());
                    }
                    catch { }
                    await WebhookClients.PremiumLogChannel.SendMessageAsync($"{premium.UserId} - {premium.Type.ToString()} subscription has expired.");
                }

                else if (!user.Roles.Any(x => x.Id == (ulong)premium.Type))
                {
                    premium.ExpireSent = true;
                    await PremiumDb.UpdatePremium(premium);

                    try
                    {
                        var ch = await client.GetUser(premium.UserId).CreateDMChannelAsync();

                        await ch.SendMessageAsync(embed : new EmbedBuilderPrepared()
                                                  .WithDescription($"Your **{premium.Type.ToString()}** subscription has expired. It's sad to see you go...\n" +
                                                                   $"You can renew your subscription [Here]({LinkHelper.GetRedirectUrl(LinkHelper.Patreon, "Patreon", "pro-expired")})\n" +
                                                                   $"If you think this is a mistake contact taiHen#2839 [Here]({LinkHelper.SupportServerInvite})")
                                                  .Build());
                    }
                    catch { }
                    await WebhookClients.PremiumLogChannel.SendMessageAsync($"{premium.UserId} - {premium.Type.ToString()} subscription has expired.");
                }

                else
                {
                    premium.ExpiresAt = premium.ExpiresAt.AddMonths(1);
                    await PremiumDb.UpdatePremium(premium);

                    await WebhookClients.PremiumLogChannel.SendMessageAsync($"{user.Mention} ({premium.UserId}) - {premium.Type.ToString()} subscription extended.");
                }
            }
        }
Esempio n. 14
0
        public static async Task<List<ShopWaifu>> GenerateWaifuShopList(ulong guildId)
        {
            int limitedamount = Constants.shoplimitedamount;
            int t1amount = Constants.shopt1amount;
            int t2amount = Constants.shopt2amount;
            int t3amount = Constants.shopt3amount;
            int pages = 1;
            if (PremiumDb.IsPremium(guildId, ProType.GuildPlus) || PremiumDb.IsPremium(guildId, ProType.Guild))
                pages = 3;
            int randomizerMultiplier = 7 - pages;

            var gachaSource = GetGachaSources();
            var tier0 = await WaifuDb.GetWaifusByTier(0);
            var tier1 = await WaifuDb.RandomWaifus(1, (limitedamount + t1amount) * pages * randomizerMultiplier, excludeSource: gachaSource);
            var tier2 = await WaifuDb.RandomWaifus(2, t2amount * pages * randomizerMultiplier, excludeSource: gachaSource);
            var tier3 = await WaifuDb.RandomWaifus(3, t3amount * pages * randomizerMultiplier, excludeSource: gachaSource);

            var wishlists = await WaifuWishlistDb.GetAllPremiumWishlists(guildId, ProType.Pro);
            wishlists.RemoveAll(x => gachaSource.Contains(x.Waifu.Source));
            var ids = wishlists.Select(x => x.UserId).Distinct().ToArray();
            var guild = Program.GetClient().GetGuild(guildId);
            foreach (var id in ids)
            {
                SocketGuildUser user = null;
                try
                {
                    user = guild.GetUser(id);
                }
                catch
                {
                    wishlists.RemoveAll(x => x.UserId == id);
                }
                if (user == null)
                    wishlists.RemoveAll(x => x.UserId == id);
            }

            tier1.AddRange(wishlists.Where(x => x.Waifu.Tier == 1).Select(x => x.Waifu));
            tier2.AddRange(wishlists.Where(x => x.Waifu.Tier == 2).Select(x => x.Waifu));
            tier3.AddRange(wishlists.Where(x => x.Waifu.Tier == 3).Select(x => x.Waifu));

            ShopWaifu item = null;
            List<ShopWaifu> waifus = new List<ShopWaifu>();
            var rnd = new Random();
            int r = 0;

            for (int k = 0; k < pages; k++)
            {
                // LIMITED WAIFU
                for (int i = 0; i < limitedamount; i++)
                {
                    r = rnd.Next(0, tier1.Count);
                    item = new ShopWaifu { Waifu = tier1.ElementAt(r), Discount = GenerateDiscount(), Limited = 1, BoughtBy = 0 };
                    waifus.Add(item);
                    tier1.RemoveAll(x => x.Name.Equals(tier1[r].Name));
                }

                // TIER 0 AND 1 WAIFUS
                for (int i = 0; i < t1amount; i++)
                {
                    r = rnd.Next(0, tier1.Count + tier0.Count);

                    if (r < tier1.Count)
                    {
                        item = new ShopWaifu { Waifu = tier1.ElementAt(r), Limited = -1, BoughtBy = 0 };
                        tier1.RemoveAll(x => x.Name.Equals(tier1[r].Name));
                    }
                    else
                    {
                        r -= tier1.Count;
                        item = new ShopWaifu { Waifu = tier0[r], Limited = -1, BoughtBy = 0 };
                        tier0.RemoveAll(x => x.Name.Equals(tier0[r].Name));
                    }

                    waifus.Add(item);
                }

                // TIER 2 WAIFUS
                for (int i = 0; i < t2amount; i++)
                {
                    r = rnd.Next(0, tier2.Count);
                    item = new ShopWaifu { Waifu = tier2.ElementAt(r), Limited = -1, BoughtBy = 0 };
                    waifus.Add(item);
                    tier2.RemoveAll(x => x.Name.Equals(tier2[r].Name));
                }

                // TIER 3 WAIFUS
                for (int i = 0; i < t3amount; i++)
                {
                    r = rnd.Next(0, tier3.Count);
                    item = new ShopWaifu { Waifu = tier3.ElementAt(r), Limited = -1, BoughtBy = 0 };
                    waifus.Add(item);
                    tier3.RemoveAll(x => x.Name.Equals(tier3[r].Name));
                }
            }

            return waifus;
        }
Esempio n. 15
0
        public async Task ActivateServerPremium([Remainder] string str = "")
        {
            var             ntr  = Context.Client.GetGuild((ulong)ProType.HomeGuildId_NOTAPREMIUMTYPE);
            SocketGuildUser user = ntr.GetUser(Context.User.Id);

            if (user == null)
            {
                await Context.Channel.SendMessageAsync($"You are not in my server! {LinkHelper.SupportServerInvite}");

                return;
            }

            var current = PremiumDb.GetGuildPremium(Context.Guild.Id);
            var roles   = user.Roles;

            bool   log  = false;
            string text = "";

            foreach (var role in roles)
            {
                if (role.Id == (ulong)ProType.GuildPlus)
                {
                    if (current.Any(x => x.Type == ProType.GuildPlus))
                    {
                        text += "**Pro Guild+** is already activated in this server!\n";
                    }
                    else
                    {
                        if (PremiumDb.IsPremium(user.Id, ProType.GuildPlus))
                        {
                            text += "You used your **Pro Guild+** premium upgrade in another server...\n";
                        }

                        else
                        {
                            await PremiumDb.AddPremium(user.Id, ProType.GuildPlus, Context.Guild.Id);

                            try
                            {
                                await PremiumDb.DeletePremium(PremiumDb.GetGuildPremium(Context.Guild.Id).FirstOrDefault(x => x.Type == ProType.Guild));
                            }
                            catch { }
                            text += "**Pro Guild+** activated!\n";
                            log   = true;
                        }
                    }
                    break;
                }
                if (role.Id == (ulong)ProType.Guild)
                {
                    if (current.Any(x => x.Type == ProType.GuildPlus))
                    {
                        text += "**Pro Guild+** is already activated in this server!\n";
                    }
                    else if (current.Any(x => x.Type == ProType.Guild))
                    {
                        text += "**Pro Guild** is already activated in this server!\n";
                    }
                    else
                    {
                        if (PremiumDb.IsPremium(user.Id, ProType.Guild))
                        {
                            text += "You used your **Pro Guild** premium upgrade in another server...\n";
                        }

                        else
                        {
                            await PremiumDb.AddPremium(user.Id, ProType.Guild, Context.Guild.Id);

                            text += "**Pro Guild** activated!\n";
                            log   = true;
                        }
                    }
                    break;
                }
            }
            if (text == "")
            {
                text += $"You have no Pro Guild... Try `{Program.GetPrefix(Context)}Pro`";
            }

            await Context.Channel.SendMessageAsync(text);

            if (log)
            {
                await WebhookClients.PremiumLogChannel.SendMessageAsync(embeds : new List <Embed>
                {
                    new EmbedBuilderPrepared(Context.User)
                    .WithDescription($"{Context.User.Mention} `{Context.User.Id}`\n{Context.Guild.Name} `{Context.Guild.Id}`\n{text}")
                    .WithFooter(System.DateTime.Now.ToLongDateString())
                    .Build()
                });
            }
        }
Esempio n. 16
0
        public async Task ModShopAddWaifu([Remainder] string name)
        {
            var prefix = Program.GetPrefix(Context);

            if (!PremiumDb.IsPremium(Context.Guild.Id, ProType.GuildPlus))
            {
                await Context.Channel.SendMessageAsync(embed : new EmbedBuilderPrepared(Context.User)
                                                       .WithDescription($"*~ This command requires Pro Guild+ ~*")
                                                       .WithFooter($"`{prefix}pro`")
                                                       .Build());

                return;
            }

            var shop = await WaifuUtil.GetShop(Context.Guild.Id, ShopType.Mod);

            var waifus = shop.ShopWaifus.Select(x => x.Waifu);

            var waifu = await WaifuUtil.ProcessWaifuListAndRespond(await WaifuDb.SearchWaifus(name), this);

            if (waifu == null)
            {
                return;
            }

            if (waifu.Tier < 1 || waifu.Tier > 3)
            {
                await Context.Channel.SendMessageAsync(embed : new EmbedBuilderPrepared(Context.User)
                                                       .WithDescription($"*~ You can only add Tier 1-3 waifus ~*")
                                                       .Build());

                return;
            }
            if (shop.ShopWaifus.Count >= 15)
            {
                await Context.Channel.SendMessageAsync(embed : new EmbedBuilderPrepared(Context.User)
                                                       .WithDescription($"*~ The Mod Shop is limited to 15 waifus. `{prefix}msrw` to remove ~*")
                                                       .Build());

                return;
            }
            if (waifus.Any(x => x.Name.Equals(waifu.Name)))
            {
                await Context.Channel.SendMessageAsync(embed : new EmbedBuilderPrepared(Context.User)
                                                       .WithDescription($"*~ **{waifu.Name}** is already in the mod shop ~*")
                                                       .Build());

                return;
            }

            await WaifuShopDb.UpdateItem(new ShopWaifu
            {
                Discount  = 0,
                Limited   = -1,
                WaifuShop = shop,
                Waifu     = waifu
            });

            await Context.Channel.SendMessageAsync($"Added **{waifu.Name}** to the Mod Shop", embed : WaifuUtil.WaifuEmbedBuilder(waifu).Build());

            return;
        }
Esempio n. 17
0
        public static async Task <EmbedBuilder> ServerInfo(SocketGuild guild)
        {
            var eb = new EmbedBuilder();

            string name = guild.Name;

            if (PremiumDb.IsPremium(guild.Id, ProType.GuildPlus))
            {
                name += " | T1 Guild 🌟";
            }
            else if (PremiumDb.IsPremium(guild.Id, ProType.Guild))
            {
                name += " | T2 Guild ⭐";
            }
            eb.WithAuthor(name, guild.IconUrl, LinkHelper.GetRedirectUrl(LinkHelper.Patreon, "Patreon", "cmd-embed-info"));

            var toasties = (await BalanceDb.GetAllToastiesRaw(guild.Id)).OrderByDescending(x => x.Amount).ToList();
            var waifus   = await UserInventoryDb.GetAllWaifuItems(guild.Id);

            string field = "";

            field += $"Total toasties: **{toasties.Sum(x => (long)x.Amount).ToString("n0")}**\n";
            SocketGuildUser user = null;
            int             i    = 0;

            while (i < toasties.Count && (user == null || user.IsBot))
            {
                user = guild.GetUser(toasties[i++].UserId);
            }
            if (user != null)
            {
                field += $"Richest user: {user.Mention} - **{toasties.FirstOrDefault(x => x.UserId == user.Id).Amount.ToString("n0")}**\n";
            }

            var bank = toasties.FirstOrDefault(x => x.UserId == Program.GetClient().CurrentUser.Id);

            field += $"Bank balance: **{(bank == null ? "0" : bank.Amount.ToString("n0"))}**\n";
            eb.AddField("Toasties <:toastie3:454441133876183060>", field);

            field  = "";
            field += $"Total waifus: **{waifus.Count.ToString("n0")}**\n";
            field += $"Total waifu value: **{waifus.Sum(x => Convert.ToInt64(WaifuUtil.GetPrice(x.Waifu.Tier, 0))).ToString("n0")}**\n";
            var groupedwaifus = waifus.GroupBy(x => x.UserId).OrderByDescending(x => x.Count()).ToList();
            IGrouping <ulong, UserInventory> most = null;

            user = null;
            i    = 0;
            while (i < groupedwaifus.Count && (user == null || user.IsBot))
            {
                most = groupedwaifus[i];
                user = guild.GetUser(groupedwaifus[i++].Key);
            }
            if (most != null && user != null)
            {
                field += $"Most waifus: {user.Mention} - **{most.Count().ToString("n0")}**\n";
            }

            groupedwaifus = groupedwaifus.OrderByDescending(x => x.Sum(y => WaifuUtil.GetPrice(y.Waifu.Tier, 0))).ToList();
            most          = null;
            user          = null;
            i             = 0;
            while (i < groupedwaifus.Count && (user == null || user.IsBot))
            {
                most = groupedwaifus[i];
                user = guild.GetUser(groupedwaifus[i++].Key);
            }
            if (most != null && user != null)
            {
                field += $"Highest value: {user.Mention} - **{most.Sum(y => WaifuUtil.GetPrice(y.Waifu.Tier, 0)).ToString("n0")}**\n";
            }
            eb.AddField("Waifus :two_hearts:", field);

            eb.WithColor(BasicUtil.RandomColor());
            eb.WithFooter("To be expanded");
            eb.WithThumbnailUrl(guild.IconUrl);
            return(eb);
        }
Esempio n. 18
0
        public async Task Open([Remainder] string str = "")
        {
            var boxes = await LootBoxDb.GetAll(Context.User.Id, Context.Guild.Id);

            if (boxes.Count == 0)
            {
                await Context.Channel.SendMessageAsync("", false, ToastieUtil.NoBoxEmbed(Context.User).Build());

                return;
            }

            LootBox box = null;

            if (boxes.Count == 1)
            {
                box = boxes[0];
            }

            else
            {
                var listMsg = await Context.Channel.SendMessageAsync(embed : ToastieUtil.BoxListEmbed(boxes, Context.User)
                                                                     .WithFooter("Times out in 23 seconds")
                                                                     .WithDescription("Enter the number of the Lootbox you wish to open.")
                                                                     .Build());

                var response = await NextMessageAsync(
                    new Criteria <IMessage>()
                    .AddCriterion(new EnsureSourceUserCriterion())
                    .AddCriterion(new EnsureSourceChannelCriterion())
                    .AddCriterion(new EnsureRangeCriterion(boxes.Count, Program.GetPrefix(Context))),
                    new TimeSpan(0, 0, 23));

                _ = listMsg.DeleteAsync();
                int i = 0;
                try
                {
                    i = int.Parse(response.Content);
                }
                catch
                {
                    _ = Context.Message.DeleteAsync();
                    return;
                }
                _ = response.DeleteAsync();

                box = boxes[i - 1];
            }

            var type = LootboxStats.Lootboxes[box.Type];

            try
            {
                await LootBoxDb.AddLootbox(Context.User.Id, box.Type, -1, box.GuildId);
            } catch
            {
                await Context.Channel.SendMessageAsync("You tried.");

                return;
            }
            var msg = await Context.Channel.SendMessageAsync("", false, ToastieUtil.BoxOpeningEmbed(Context.User).Build());

            await ProfileDb.IncrementLootboxOpened(Context.User.Id);

            int waitms = 4200;

            if (type.IsWaifu())
            {
                bool isPremium = PremiumDb.IsPremium(Context.User.Id, ProType.Pro);
                var  waifu     = await ToastieUtil.UnboxWaifu(type, isPremium, Context.User.Id, Context.Guild.Id);

                while (UserInventoryDb.OwnsWaifu(Context.User.Id, waifu, Context.Guild.Id))
                {
                    waifu = await ToastieUtil.UnboxWaifu(type, isPremium, Context.User.Id, Context.Guild.Id);
                }

                await UserInventoryDb.AddWaifu(Context.User.Id, waifu, Context.Guild.Id);

                await Task.Delay(waitms);

                var embed = WaifuUtil.WaifuEmbedBuilder(waifu, Context).Build();
                await msg.ModifyAsync(x => {
                    x.Embed   = embed;
                    x.Content = $"{Context.User.Mention} Congratulations! You found **{waifu.Name}**!";
                });

                return;
            }

            var amountWon = type.GetRandomToasties();
            await BalanceDb.AddToasties(Context.User.Id, amountWon, Context.Guild.Id);

            var bal = BalanceDb.GetToasties(Context.User.Id, Context.Guild.Id);
            await Task.Delay(waitms);

            await msg.ModifyAsync(x => {
                x.Embed = new EmbedBuilder()
                          .WithAuthor($"{Context.User} | {box.Type.ToString()}", Context.User.GetAvatarUrl(), LinkHelper.GetRedirectUrl(LinkHelper.Patreon, "Patreon", "cmd-embed-lootbox"))
                          .WithColor(BasicUtil.RandomColor())
                          .WithThumbnailUrl("https://i.imgur.com/4JQmxa6.png")
                          .WithDescription($"Congratulations! You found **{amountWon.ToString("n0")}** {ToastieUtil.RandomEmote()}!\nNow you have **{bal.ToString("n0")}** {ToastieUtil.RandomEmote()}!")
                          .Build();
            });
        }
Esempio n. 19
0
        public async Task BulkOpen([Remainder] string str = "")
        {
            var boxes = await LootBoxDb.GetAll(Context.User.Id, Context.Guild.Id);

            if (boxes.Count == 0)
            {
                await Context.Channel.SendMessageAsync("", false, ToastieUtil.NoBoxEmbed(Context.User).Build());

                return;
            }

            LootBox box = null;

            if (boxes.Count == 1)
            {
                box = boxes[0];
            }

            else
            {
                var listMsg = await Context.Channel.SendMessageAsync(embed : ToastieUtil.BoxListEmbed(boxes, Context.User)
                                                                     .WithFooter("Times out in 23 seconds")
                                                                     .WithDescription("Enter the number of the Lootbox type you wish to open.")
                                                                     .Build());

                var response = await NextMessageAsync(
                    new Criteria <IMessage>()
                    .AddCriterion(new EnsureSourceUserCriterion())
                    .AddCriterion(new EnsureSourceChannelCriterion())
                    .AddCriterion(new EnsureRangeCriterion(boxes.Count, Program.GetPrefix(Context))),
                    new TimeSpan(0, 0, 23));

                _ = listMsg.DeleteAsync();
                int i = 0;
                try
                {
                    i = int.Parse(response.Content);
                }
                catch
                {
                    _ = Context.Message.DeleteAsync();
                    return;
                }
                _ = response.DeleteAsync();

                box = boxes[i - 1];
            }

            var type      = LootboxStats.Lootboxes[box.Type];
            var dialoague = await ReplyAsync(embed : new EmbedBuilderPrepared(Context.User).WithDescription($"How many {type.Emote} **{type.Name}** lootboxes do you wish to open?").Build());

            var amountMsg = await NextMessageAsync(
                new Criteria <IMessage>()
                .AddCriterion(new EnsureSourceUserCriterion())
                .AddCriterion(new EnsureSourceChannelCriterion())
                .AddCriterion(new EnsureRangeCriterion(int.MaxValue, Program.GetPrefix(Context))),
                new TimeSpan(0, 0, 23));

            int amount;

            try
            {
                amount = int.Parse(amountMsg.Content);
            }
            catch
            {
                _ = Context.Message.DeleteAsync();
                return;
            }
            _ = dialoague.DeleteAsync();

            try
            {
                await LootBoxDb.AddLootbox(Context.User.Id, box.Type, -amount, box.GuildId);
            }
            catch
            {
                await Context.Channel.SendMessageAsync("You tried.");

                return;
            }
            _ = amountMsg.DeleteAsync();

            var msg = await Context.Channel.SendMessageAsync("", false, ToastieUtil.BoxOpeningEmbed(Context.User).Build());

            await ProfileDb.IncrementLootboxOpened(Context.User.Id, amount);

            int waitms = 4200;

            int  toasties    = 0;
            var  waifusFound = new List <Waifu>();
            var  waifus      = UserInventoryDb.GetWaifus(Context.User.Id, Context.Guild.Id);
            bool isPremium   = PremiumDb.IsPremium(Context.User.Id, ProType.Pro);

            for (int i = 0; i < amount; i++)
            {
                if (type.IsWaifu())
                {
                    var waifu = await ToastieUtil.UnboxWaifu(type, isPremium, Context.User.Id, Context.Guild.Id);

                    while (waifu == null || waifus.Any(x => x.Name.Equals(waifu.Name)) || waifusFound.Any(x => x.Name.Equals(waifu.Name)))
                    {
                        waifu = await ToastieUtil.UnboxWaifu(type, isPremium, Context.User.Id, Context.Guild.Id);
                    }

                    waifusFound.Add(waifu);
                    await UserInventoryDb.AddWaifu(Context.User.Id, waifu, Context.Guild.Id);
                }
                else
                {
                    toasties += type.GetRandomToasties();
                }
            }

            await BalanceDb.AddToasties(Context.User.Id, toasties, Context.Guild.Id);

            var bal = BalanceDb.GetToasties(Context.User.Id, Context.Guild.Id);

            await Task.Delay(waitms);

            var eb = new EmbedBuilder()
                     .WithAuthor($"{Context.User} | {box.Type.ToString()} x{amount}", Context.User.GetAvatarUrl(), LinkHelper.GetRedirectUrl(LinkHelper.Patreon, "Patreon", "cmd-embed-lootbox"))
                     .WithColor(BasicUtil.RandomColor())
                     .WithThumbnailUrl("https://i.imgur.com/4JQmxa6.png");

            string desc = $"You found **{toasties.ToString("n0")}** {ToastieUtil.RandomEmote()}!\nNow you have **{bal.ToString("n0")}** {ToastieUtil.RandomEmote()}!\n\n";

            if (waifusFound.Any())
            {
                desc += "**Waifus Found:**\n";
                foreach (var w in waifusFound)
                {
                    desc += $"`T{w.Tier}` **{w.Name}** - *{(w.Source.Length > 37 ? w.Source.Substring(0, 33) + "..." : w.Source)}*\n";
                }
            }

            eb.WithDescription(desc.Length > 2000 ? desc.Substring(0, 1970) + "\n*And more...*" : desc);
            await msg.ModifyAsync(x => {
                x.Embed = eb.Build();
            });
        }
Esempio n. 20
0
        public async Task BuyLootbox([Remainder] string str = "")
        {
            var prefix = Program.GetPrefix(Context);

            if (!PremiumDb.IsPremium(Context.Guild.Id, ProType.GuildPlus))
            {
                await Context.Channel.SendMessageAsync(embed : new EmbedBuilderPrepared(Context.User)
                                                       .WithDescription($"*~ This command requires Pro Guild+ ~*\n" +
                                                                        $"Try `{prefix}lootboxstats` to see drop rates.")
                                                       .WithFooter($"`{prefix}pro`")
                                                       .Build());

                return;
            }

            LootboxStat box   = null;
            var         boxes = LootboxStats.Lootboxes.Where(x => x.Value.Price >= 0).Select(x => x.Value).ToList();

            if (str != "")
            {
                var matches = boxes.Where(x => x.Name.Contains(str, StringComparison.OrdinalIgnoreCase));
                if (matches.Count() == 1)
                {
                    box = matches.First();
                }
            }
            if (box == null)
            {
                var listMsg = await Context.Channel.SendMessageAsync(embed : ToastieUtil.BoxShopEmbed(Context.User)
                                                                     .WithFooter("Times out in 23 seconds. Try the `lootboxstats` command")
                                                                     .WithDescription("Enter the number of the lootbox you wish to purchase.")
                                                                     .Build());

                var response = await NextMessageAsync(
                    new Criteria <IMessage>()
                    .AddCriterion(new EnsureSourceUserCriterion())
                    .AddCriterion(new EnsureSourceChannelCriterion())
                    .AddCriterion(new EnsureRangeCriterion(boxes.Count(), Program.GetPrefix(Context))),
                    new TimeSpan(0, 0, 23));

                _ = listMsg.DeleteAsync();
                int i = 0;
                try
                {
                    i = int.Parse(response.Content);
                }
                catch
                {
                    _ = Context.Message.DeleteAsync();
                    return;
                }
                _ = response.DeleteAsync();

                box = boxes[i - 1];
            }

            var msg = await Context.Channel.SendMessageAsync($"How many **{box.Name}** lootboxes do you wish to buy? (max 100)");

            var resp = await NextMessageAsync(
                new Criteria <IMessage>()
                .AddCriterion(new EnsureSourceUserCriterion())
                .AddCriterion(new EnsureSourceChannelCriterion())
                .AddCriterion(new EnsureRangeCriterion(100, Program.GetPrefix(Context))),
                new TimeSpan(0, 0, 23));

            _ = msg.DeleteAsync();
            int amount = 0;

            try
            {
                amount = int.Parse(resp.Content);
            }
            catch
            {
                _ = Context.Message.DeleteAsync();
                return;
            }
            _ = resp.DeleteAsync();

            try
            {
                await BalanceDb.AddToasties(Context.User.Id, -box.Price *amount, Context.Guild.Id);
            } catch (Exception ex)
            {
                await Context.Channel.SendMessageAsync(ex.Message);

                return;
            }

            await LootBoxDb.AddLootbox(Context.User.Id, (LootBoxType)box.TypeId, amount, Context.Guild.Id);

            await Context.Channel.SendMessageAsync(embed : new EmbedBuilderPrepared(Context.User)
                                                   .WithDescription($"You bought {amount}x **{box.Name}**!\nType `{Program.GetPrefix(Context)}open` to open it!")
                                                   .Build());
        }
Esempio n. 21
0
        public async Task NewImage(string name, string url = null, [Remainder] string str = "")
        {
            await Context.Channel.TriggerTypingAsync();

            bool insider = Context.Guild.Id == 418900885079588884;

            url ??= Context.Message.Attachments.FirstOrDefault()?.Url;

            if (!insider)
            {
                if (!PremiumDb.IsPremium(Context.Guild.Id, ProType.GuildPlus))
                {
                    await Context.Channel.SendMessageAsync($"This server does not have Pro Guild+. `{Program.GetPrefix(Context)}pro`");

                    return;
                }

                if ((await ImageDb.GetImages(name, 0)).Any())
                {
                    await Context.Channel.SendMessageAsync($"There is already a default image command called **{name}**. It will be replaced with your custom one.");
                }
            }

            if (url == null)
            {
                await Context.Channel.SendMessageAsync("Can't get your attachment, there probably isn't one. *Heh, dummy...*");

                return;
            }

            url = url.EndsWith(".gifv") ? url.Replace(".gifv", ".gif") : url;
            url = url.EndsWith(".mp4") ? url.Replace(".mp4", ".gif") : url;

            if (ImgurAPI.RateLimit.ClientRemaining < 50)
            {
                await ReplyAsync("Not enough imgur credits to upload. Please try again later.");

                return;
            }

            string albumId;
            string albumName = insider ? name : name + Context.Guild.Id;

            if (!ImageDb.AlbumExists(albumName))
            {
                albumId = (await ImgurAPI.CreateAlbumAsync(albumName)).Id;
                await ImageDb.CreateAlbum(albumName, albumId);
            }
            else
            {
                albumId = ImageDb.GetAlbum(albumName).AlbumId;
            }

            var iImage = await ImgurAPI.UploadImageAsync(url, albumId);

            var img = await ImageDb.AddImage(name.ToLower(), iImage.Link, insider? 0 : Context.Guild.Id);

            if (!ReactionImageCommands.Contains(name.ToLower()))
            {
                ReactionImageCommands.Add(name.ToLower());
            }

            await ImgurAPI.EditImageAsync(iImage.Id.ToString(), null, img.Id.ToString());

            var rl = ImgurAPI.RateLimit;
            await ImageUtil.UploadReactionImage(img, Context.Channel);

            await Context.Channel.SendMessageAsync($"{rl.ClientRemaining-20}/{rl.ClientLimit} imgur credits remaining.", false, ImageUtil.ToEmbed(img).Build());
        }
Esempio n. 22
0
File: Web.cs Progetto: ta1H3n/Namiko
        public async Task Subreddit(string name, int upvotes)
        {
            var subs  = SpecialChannelDb.GetChannelsByGuild(Context.Guild.Id, Model.ChannelType.Reddit);
            int limit = 1;

            if (PremiumDb.IsPremium(Context.Guild.Id, ProType.Guild))
            {
                limit = 5;
            }
            if (PremiumDb.IsPremium(Context.Guild.Id, ProType.GuildPlus))
            {
                limit = 10;
            }

            if (subs.Count() >= limit)
            {
                await Context.Channel.SendMessageAsync($"Limit {limit} subscription per guild. Upgrade server to increase the limit! `{Program.GetPrefix(Context)}Pro`", embed : WebUtil.SubListEmbed(Context.Guild.Id).Build());

                return;
            }

            if (upvotes < 100)
            {
                await Context.Channel.SendMessageAsync("Upvote minimum must be at least 100.");

                return;
            }

            await Context.Channel.TriggerTypingAsync();

            Subreddit sub = null;

            try
            {
                sub = await RedditAPI.GetSubreddit(name);
            } catch
            {
                await Context.Channel.SendMessageAsync($"Subreddit **{name}** not found.");

                return;
            }
            if (sub.Subscribers < 20000)
            {
                await Context.Channel.SendMessageAsync("The Subreddit must have at least **20,000** subscribers.\n" +
                                                       $"**{sub.Name}** has **{sub.Subscribers?.ToString("n0")}**.");

                return;
            }
            try
            {
                if (sub.Over18.Value && !((SocketTextChannel)Context.Channel).IsNsfw)
                {
                    await Context.Channel.SendMessageAsync($"**{sub.Name}** is a NSFW subreddit. This channel must be marked as NSFW.");

                    return;
                }
            } catch { }

            var old = subs.FirstOrDefault(x => x.ChannelId == Context.Channel.Id && x.Args.Split(",")[0].Equals(sub.Name));

            if (old != null)
            {
                await SpecialChannelDb.Delete(old);
            }

            await SpecialChannelDb.AddChannel(Context.Channel.Id, Model.ChannelType.Reddit, Context.Guild.Id, sub.Name + "," + upvotes);

            await Context.Channel.SendMessageAsync(embed : WebUtil.SubredditSubscribedEmbed(sub, upvotes).Build());
        }
Esempio n. 23
0
        // Embeds
        //Embed Method: profile
        public static async Task <EmbedBuilder> ProfileEmbed(SocketGuildUser user)
        {
            var eb = new EmbedBuilder();

            string name = user.Username;

            var role = RoleUtil.GetMemberRole(user.Guild, user) ?? RoleUtil.GetLeaderRole(user.Guild, user);

            if (role != null)
            {
                var team = TeamDb.TeamByMember(role.Id) ?? TeamDb.TeamByLeader(role.Id);
                if (team != null)
                {
                    role = user.Roles.FirstOrDefault(x => x.Id == team.LeaderRoleId);
                    if (role == null)
                    {
                        role = user.Roles.FirstOrDefault(x => x.Id == team.MemberRoleId);
                    }

                    name += $" | {role.Name}";
                }
            }

            if (PremiumDb.IsPremium(user.Id, ProType.ProPlus))
            {
                name += " | Pro+ 🌟";
            }
            else if (PremiumDb.IsPremium(user.Id, ProType.Pro))
            {
                name += " | Pro ⭐";
            }
            eb.WithAuthor(name, user.GetAvatarUrl(), $"https://namiko.moe/Guild/{user.Guild.Id}/{user.Id}");

            var waifus     = UserInventoryDb.GetWaifus(user.Id, user.Guild.Id);
            int waifucount = waifus.Count();
            int waifuprice = WaifuUtil.WaifuValue(waifus);

            var  daily   = DailyDb.GetDaily(user.Id, user.Guild.Id);
            long timeNow = DateTimeOffset.Now.ToUnixTimeMilliseconds();

            string text = "";

            text += $"Amount: {BalanceDb.GetToasties(user.Id, user.Guild.Id).ToString("n0")}\n" +
                    $"Daily: {(daily == null ? "0" : ((daily.Date + 172800000) < timeNow ? "0" : daily.Streak.ToString()))}\n" +
                    $"Boxes Opened: {ProfileDb.GetLootboxOpenedAmount(user.Id)}\n";
            eb.AddField("Toasties <:toastie3:454441133876183060>", text, true);

            text = $"Amount: {waifucount}\n" +
                   $"Value: {waifuprice.ToString("n0")}\n";
            foreach (var x in MarriageDb.GetMarriages(user.Id, user.Guild.Id))
            {
                try
                {
                    if (!text.Contains("Married: "))
                    {
                        text += "Married: ";
                    }
                    text += $"{BasicUtil.IdToMention(GetWifeId(x, user.Id))}\n";
                } catch { }
            }
            eb.AddField("Waifus :two_hearts:", text, true);

            var waifu = FeaturedWaifuDb.GetFeaturedWaifu(user.Id, user.Guild.Id);

            if (waifu != null)
            {
                eb.WithImageUrl(waifu.HostImageUrl);
                eb.AddField("Featured Waifu <:MiaHug:536580304018735135>", $"**{waifu.Name}** - *{waifu.Source}*");
            }

            var    rep    = ProfileDb.GetRepAmount(user.Id);
            string footer = $"Votes: {await VoteDb.VoteCount(user.Id)} • ";

            footer += $"Rep: {rep} • ";
            // Activities require guildpresence
            //footer += $"Status: '{user.Status}'";
            //var activity = user.Activities.FirstOrDefault();
            //if (activity != null)
            //    footer += $", {activity.Type}: '{activity.Name}'";
            eb.WithFooter(footer);

            //quote
            string quote = ProfileDb.GetQuote(user.Id);

            if (!String.IsNullOrEmpty(quote) & !WebUtil.IsValidUrl(quote))
            {
                eb.WithDescription(quote);
            }

            //image
            string image = ProfileDb.GetImage(user.Id);

            if (WebUtil.IsValidUrl(image))
            {
                eb.WithThumbnailUrl(image);
            }

            eb.Color = ProfileDb.GetHex(out string colour, user.Id)? (Discord.Color)HexToColor(colour) : BasicUtil.RandomColor();
            return(eb);
        }
Esempio n. 24
0
        public static async Task <Premium> RedeemCode(string id, ulong userId, ulong guildId)
        {
            var db = new NamikoDbContext();

            var res = await db.PremiumCodes
                      .Include(x => x.Uses.Where(x => x.UserId == userId || x.GuildId == guildId))
                      .FirstOrDefaultAsync(x => x.Id == id && (x.ExpiresAt == null || x.ExpiresAt > DateTime.Now) && x.UsesLeft > 0);

            if (res == null)
            {
                throw new NamikoException("Code invalid");
            }

            bool used = res.Type switch
            {
                ProType.Guild => res.Uses.Any(x => x.GuildId == guildId),
                ProType.GuildPlus => res.Uses.Any(x => x.GuildId == guildId),
                ProType.Pro => res.Uses.Any(x => x.UserId == guildId),
                ProType.ProPlus => res.Uses.Any(x => x.UserId == guildId),
                _ => throw new ArgumentException("Unknown pro type")
            };

            if (used)
            {
                throw new NamikoException("Code already redeemed on this account/server");
            }

            bool active = res.Type switch
            {
                ProType.Guild => PremiumDb.IsPremium(guildId, res.Type),
                ProType.GuildPlus => PremiumDb.IsPremium(guildId, res.Type),
                ProType.Pro => PremiumDb.IsPremium(userId, res.Type),
                ProType.ProPlus => PremiumDb.IsPremium(userId, res.Type),
                _ => throw new ArgumentException("Unknown pro type")
            };

            if (active)
            {
                throw new NamikoException($"{res.Type.ToString()} already active");
            }

            var premium = new Premium
            {
                GuildId    = guildId,
                UserId     = userId,
                Type       = res.Type,
                ClaimDate  = System.DateTime.Now,
                ExpireSent = false,
                ExpiresAt  = DateTime.Now.AddDays(res.DurationDays)
            };

            var use = new PremiumCodeUse
            {
                GuildId       = guildId,
                UserId        = userId,
                PremiumCode   = res,
                PremiumCodeId = res.Id,
                ClaimedAt     = DateTime.Now
            };

            res.UsesLeft--;

            db.PremiumCodeUses.Add(use);
            db.Premiums.Add(premium);
            db.Update(res);

            await db.SaveChangesAsync();

            return(premium);
        }