Example #1
0
        public async Task ProfileAsync(EventContext e)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();

            using (var context = new MikiContext())
            {
                long  id  = 0;
                ulong uid = 0;

                var arg = e.Arguments.FirstOrDefault();

                if (arg != null)
                {
                    uid = (await arg.GetUserAsync(e.Guild)).Id;
                    id  = uid.ToDbLong();
                }
                else
                {
                    uid = e.message.Author.Id;
                    id  = uid.ToDbLong();
                }

                IDiscordGuildUser discordUser = await e.Guild.GetUserAsync(uid);

                User account = await User.GetAsync(context, discordUser);

                string icon = "";

                if (await account.IsDonatorAsync(context))
                {
                    icon = "https://cdn.discordapp.com/emojis/421969679561785354.png";
                }

                if (account != null)
                {
                    EmbedBuilder embed = Utils.Embed
                                         .SetDescription(account.Title)
                                         .SetAuthor(e.GetResource("miki_global_profile_user_header", account.Name), icon, "https://patreon.com/mikibot")
                                         .SetThumbnail(discordUser.GetAvatarUrl());

                    long serverid = e.Guild.Id.ToDbLong();

                    LocalExperience localExp = await LocalExperience.GetAsync(context, e.Guild.Id.ToDbLong(), discordUser);

                    if (localExp == null)
                    {
                        localExp = await LocalExperience.CreateAsync(context, serverid, discordUser);
                    }

                    int rank = await localExp.GetRank(context);

                    int localLevel  = User.CalculateLevel(localExp.Experience);
                    int maxLocalExp = User.CalculateLevelExperience(localLevel);
                    int minLocalExp = User.CalculateLevelExperience(localLevel - 1);

                    EmojiBar expBar = new EmojiBar(maxLocalExp - minLocalExp, onBarSet, offBarSet, 6);

                    string infoValue = new MessageBuilder()
                                       .AppendText(e.GetResource("miki_module_accounts_information_level", localLevel, localExp.Experience, maxLocalExp))
                                       .AppendText(await expBar.Print(localExp.Experience - minLocalExp, e.Guild, (IDiscordGuildChannel)e.Channel))
                                       .AppendText(e.GetResource("miki_module_accounts_information_rank", rank))
                                       .AppendText("Reputation: " + account.Reputation, MessageFormatting.Plain, false)
                                       .Build();

                    embed.AddInlineField(e.GetResource("miki_generic_information"), infoValue);

                    int globalLevel  = User.CalculateLevel(account.Total_Experience);
                    int maxGlobalExp = User.CalculateLevelExperience(globalLevel);
                    int minGlobalExp = User.CalculateLevelExperience(globalLevel - 1);

                    int globalRank = await account.GetGlobalRankAsync();

                    EmojiBar globalExpBar = new EmojiBar(maxGlobalExp - minGlobalExp, onBarSet, offBarSet, 6);

                    string globalInfoValue = new MessageBuilder()
                                             .AppendText(e.GetResource("miki_module_accounts_information_level", globalLevel, account.Total_Experience, maxGlobalExp))
                                             .AppendText(
                        await globalExpBar.Print(account.Total_Experience - minGlobalExp, e.Guild, e.Channel as IDiscordGuildChannel)
                        )
                                             .AppendText(e.GetResource("miki_module_accounts_information_rank", globalRank), MessageFormatting.Plain, false)
                                             .Build();

                    embed.AddInlineField(e.GetResource("miki_generic_global_information"), globalInfoValue);
                    embed.AddInlineField(e.GetResource("miki_generic_mekos"), account.Currency + "<:mekos:421972155484471296>");

                    List <UserMarriedTo> Marriages = await Marriage.GetMarriagesAsync(context, id);

                    Marriages.RemoveAll(x => x.Marriage.IsProposing);

                    List <string> users = new List <string>();

                    int maxCount = Marriages?.Count ?? 0;

                    for (int i = 0; i < maxCount; i++)
                    {
                        users.Add(await User.GetNameAsync(context, Marriages[i].GetOther(id)));
                    }

                    if (Marriages?.Count > 0)
                    {
                        List <string> MarriageStrings = new List <string>();

                        for (int i = 0; i < maxCount; i++)
                        {
                            if (Marriages[i].GetOther(id) != 0)
                            {
                                MarriageStrings.Add($"รฐลธโ€™โ€ข {users[i]} (_{Marriages[i].Marriage.TimeOfMarriage.ToShortDateString()}_)");
                            }
                        }

                        string marriageText = string.Join("\n", MarriageStrings);
                        if (string.IsNullOrEmpty(marriageText))
                        {
                            marriageText = e.GetResource("miki_placeholder_null");
                        }

                        embed.AddInlineField(
                            e.GetResource("miki_module_accounts_profile_marriedto"),
                            marriageText);
                    }

                    Random r = new Random((int)id - 3);
                    Color  c = new Color((float)r.NextDouble(), (float)r.NextDouble(), (float)r.NextDouble());

                    embed.SetColor(c);

                    CommandUsage favouriteCommand = await context.CommandUsages
                                                    .OrderByDescending(x => x.Amount)
                                                    .FirstOrDefaultAsync(x => x.UserId == id);

                    string favCommand = $"{favouriteCommand?.Name ?? e.GetResource("miki_placeholder_null")} ({ favouriteCommand?.Amount ?? 0 })";

                    embed.AddInlineField(e.GetResource("miki_module_accounts_profile_favourite_command"),
                                         favCommand);

                    List <Achievement> allAchievements = await context.Achievements.Where(x => x.Id == id).ToListAsync();

                    string achievements = e.GetResource("miki_placeholder_null");

                    if (allAchievements != null)
                    {
                        if (allAchievements.Count > 0)
                        {
                            achievements = AchievementManager.Instance.PrintAchievements(allAchievements);
                        }
                    }

                    embed.AddInlineField(
                        e.GetResource("miki_generic_achievements"),
                        achievements);

                    embed.SetFooter(
                        e.GetResource("miki_module_accounts_profile_footer", account.DateCreated.ToShortDateString(),
                                      sw.ElapsedMilliseconds), "");

                    sw.Stop();

                    embed.ToEmbed().QueueToChannel(e.Channel);
                }
                else
                {
                    e.ErrorEmbed(e.GetResource("error_account_null"))
                    .ToEmbed().QueueToChannel(e.Channel);
                }
            }
        }
Example #2
0
        public async Task BanAsync(EventContext e)
        {
            if (e.Guild.CurrentUser.HasPermissions(e.Channel, DiscordGuildPermission.BanMembers))
            {
                List <string> arg        = e.arguments.Split(' ').ToList();
                IDiscordUser  bannedUser = null;

                if (e.message.MentionedUserIds.Count > 0)
                {
                    bannedUser = await e.Guild.GetUserAsync(e.message.MentionedUserIds.First());

                    arg.RemoveAll(x => x.Contains(e.message.MentionedUserIds.First().ToString()));
                }
                else
                {
                    if (arg.Count > 0)
                    {
                        bannedUser = await e.Guild.GetUserAsync(ulong.Parse(arg[0]));

                        arg.RemoveAt(0);
                    }
                }

                if (bannedUser == null)
                {
                    await e.ErrorEmbed(e.GetResource("ban_error_user_null"))
                    .SendToChannel(e.Channel);

                    return;
                }

                if (bannedUser.Hierarchy >= e.Guild.CurrentUser.Hierarchy)
                {
                    await e.ErrorEmbed(e.GetResource("permission_error_low", "ban"))
                    .SendToChannel(e.Channel);

                    return;
                }

                string reason = string.Join(" ", arg);

                IDiscordEmbed embed = Utils.Embed;
                embed.Title       = "๐Ÿ›‘ BAN";
                embed.Description = e.GetResource("ban_header", $"**{e.Guild.Name}**");

                if (!string.IsNullOrWhiteSpace(reason))
                {
                    embed.AddInlineField($"๐Ÿ’ฌ {e.GetResource("miki_module_admin_kick_reason")}", reason);
                }

                embed.AddInlineField($"๐Ÿ’ {e.GetResource("miki_module_admin_kick_by")}", e.Author.Username + "#" + e.Author.Discriminator);

                await bannedUser.SendMessage(embed);

                await bannedUser.Ban(e.Guild, 1, reason);
            }
            else
            {
                await e.ErrorEmbed(e.GetResource("permission_needed_error", $"`{e.GetResource("permission_ban_members")}`"))
                .SendToChannel(e.Channel);
            }
        }
Example #3
0
        public async Task PruneAsync(EventContext e, int _amount = 100, ulong _target = 0)
        {
            Locale locale = Locale.GetEntity(e.Channel.Id.ToDbLong());

            IDiscordUser invoker = await e.Guild.GetUserAsync(Bot.instance.Client.GetShard( 0 ).CurrentUser.Id);

            if (!invoker.HasPermissions(e.Channel, DiscordGuildPermission.ManageMessages))
            {
                await e.Channel.SendMessage(locale.GetString("miki_module_admin_prune_error_no_access"));

                return;
            }

            int amount = _amount;

            string[] argsSplit = e.arguments.Split(' ');
            ulong    target    = e.message.MentionedUserIds.Count > 0 ? (await e.Guild.GetUserAsync(e.message.MentionedUserIds.First())).Id : _target;

            if (!string.IsNullOrEmpty(argsSplit[0]))
            {
                if (int.TryParse(argsSplit[0], out amount))
                {
                    if (amount < 0)
                    {
                        IDiscordEmbed errorMessage = Utils.ErrorEmbed(e, locale.GetString("miki_module_admin_prune_error_negative"));
                        await errorMessage.SendToChannel(e.Channel);

                        return;
                    }
                    if (amount > 100)
                    {
                        IDiscordEmbed errorMessage = Utils.ErrorEmbed(e, locale.GetString("miki_module_admin_prune_error_max"));
                        await errorMessage.SendToChannel(e.Channel);

                        return;
                    }
                }
                else
                {
                    IDiscordEmbed errorMessage = Utils.ErrorEmbed(e, locale.GetString("miki_module_admin_prune_error_parse"));
                    await errorMessage.SendToChannel(e.Channel);

                    return;
                }
            }

            await e.message.DeleteAsync();             // Delete the calling message before we get the message history.

            List <IDiscordMessage> messages = await e.Channel.GetMessagesAsync(amount);

            List <IDiscordMessage> deleteMessages = new List <IDiscordMessage>();

            if (messages.Count < amount)
            {
                amount = messages.Count;                 // Checks if the amount of messages to delete is more than the amount of messages availiable.
            }

            if (amount <= 1)
            {
                string prefix = await PrefixInstance.Default.GetForGuildAsync(e.Guild.Id);

                await e.message.DeleteAsync();

                IDiscordEmbed errorMessage = Utils.ErrorEmbed(e, locale.GetString("miki_module_admin_prune_no_messages", new object[] { prefix }));
                await errorMessage.SendToChannel(e.Channel);

                return;
            }

            for (int i = 0; i < amount; i++)
            {
                if (target != 0 && messages[i]?.Author.Id != target)
                {
                    continue;
                }

                if (messages[i].Timestamp.AddDays(14) > DateTime.Now)
                {
                    deleteMessages.Add(messages[i]);
                }
            }

            if (deleteMessages.Count > 0)
            {
                await e.Channel.DeleteMessagesAsync(deleteMessages);
            }

            Task.WaitAll();

            string[] titles = new string[]
            {
                "POW!",
                "BANG!",
                "BAM!",
                "KAPOW!",
                "BOOM!",
                "ZIP!",
                "ZING!",
                "SWOOSH!",
                "POP!"
            };

            IDiscordEmbed embed = Utils.Embed;

            embed.Title       = titles[MikiRandom.Next(titles.Length - 1)];
            embed.Description = e.GetResource("miki_module_admin_prune_success", deleteMessages.Count);

            embed.Color = IA.SDK.Color.GetColor(IAColor.YELLOW);

            IDiscordMessage _dMessage = await embed.SendToChannel(e.Channel);

            await Task.Delay(5000);

            await _dMessage.DeleteAsync();
        }
Example #4
0
        public async Task GuildWeekly(EventContext e)
        {
            using (MikiContext database = new MikiContext())
            {
                LocalExperience thisUser = await database.LocalExperience.FindAsync(e.Guild.Id.ToDbLong(), e.Author.Id.ToDbLong());

                GuildUser thisGuild = await database.GuildUsers.FindAsync(e.Guild.Id.ToDbLong());

                Timer timer = await database.Timers.FindAsync(e.Guild.Id.ToDbLong(), e.Author.Id.ToDbLong());

                if (thisUser == null)
                {
                    return;
                }

                if (thisGuild == null)
                {
                    return;
                }

                if (thisUser.Experience >= thisGuild.MinimalExperienceToGetRewards)
                {
                    if (timer == null)
                    {
                        timer = (await database.Timers.AddAsync(new Timer()
                        {
                            GuildId = e.Guild.Id.ToDbLong(),
                            UserId = e.Author.Id.ToDbLong(),
                            Value = DateTime.Now.AddDays(-30)
                        })).Entity;
                        await database.SaveChangesAsync();
                    }

                    if (timer.Value.AddDays(7) <= DateTime.Now)
                    {
                        IGuild guild = Bot.Instance.Client.GetGuild(thisGuild.Id.FromDbLong());

                        GuildUser rival = await thisGuild.GetRival();

                        if (rival == null)
                        {
                            Utils.Embed
                            .WithTitle(e.GetResource("miki_terms_weekly"))
                            .WithDescription(e.GetResource("guildweekly_error_no_rival"))
                            .Build().QueueToChannel(e.Channel);
                            return;
                        }

                        if (rival.Experience > thisGuild.Experience)
                        {
                            Utils.Embed
                            .WithTitle(e.GetResource("miki_terms_weekly"))
                            .WithDescription(e.GetResource("guildweekly_error_low_level"))
                            .Build().QueueToChannel(e.Channel);
                            return;
                        }

                        int mekosGained = (int)Math.Round((((MikiRandom.NextDouble() + 1.25) * 0.5) * 10) * thisGuild.CalculateLevel(thisGuild.Experience));

                        User user = await database.Users.FindAsync(e.Author.Id.ToDbLong());

                        if (user == null)
                        {
                            // TODO: Add response
                            return;
                        }

                        await user.AddCurrencyAsync(mekosGained, e.Channel);

                        Utils.Embed
                        .WithTitle(e.GetResource("miki_terms_weekly"))
                        .AddInlineField("Mekos", mekosGained.ToString())
                        .Build().QueueToChannel(e.Channel);

                        timer.Value = DateTime.Now;
                        await database.SaveChangesAsync();
                    }
                    else
                    {
                        Utils.Embed
                        .WithTitle(e.GetResource("miki_terms_weekly"))
                        .WithDescription(e.GetResource("guildweekly_error_timer_running", (timer.Value.AddDays(7) - DateTime.Now).ToTimeString(e.Channel.Id)))
                        .Build().QueueToChannel(e.Channel);
                    }
                }
                else
                {
                    Utils.Embed
                    .WithTitle(e.GetResource("miki_terms_weekly"))
                    .WithDescription(e.GetResource("miki_guildweekly_insufficient_exp", thisGuild.MinimalExperienceToGetRewards))
                    .Build().QueueToChannel(e.Channel);
                }
            }
        }
Example #5
0
 public static EmbedBuilder ErrorEmbed(this EventContext e, string message)
 => new EmbedBuilder()
 .SetTitle($"๐Ÿšซ {e.GetResource(LocaleTags.ErrorMessageGeneric)}")
 .SetDescription(message)
 .SetColor(1.0f, 0.0f, 0.0f);
Example #6
0
        public async Task RollAsync(EventContext e)
        {
            string rollResult;

            if (string.IsNullOrWhiteSpace(e.Arguments.ToString()))             // No Arguments.
            {
                rollResult = MikiRandom.Roll(100).ToString();
            }
            else
            {
                if (int.TryParse(e.Arguments.ToString(), out int max))                 // Simple number argument.
                {
                    rollResult = MikiRandom.Roll(max).ToString();
                }
                else                 // Assume the user has entered an advanced expression.
                {
                    Regex  regex           = new Regex(@"(?<dieCount>\d+)d(?<dieSides>\d+)");
                    string fullExpression  = e.Arguments.ToString();
                    int    expressionCount = 0;

                    foreach (Match match in regex.Matches(e.Arguments.ToString()))
                    {
                        GroupCollection groupCollection   = match.Groups;
                        int             dieCount          = int.Parse(groupCollection["dieCount"].Value);
                        int             dieSides          = int.Parse(groupCollection["dieSides"].Value);
                        string          partialExpression = "";

                        for (int i = 0; i < dieCount; i++)
                        {
                            partialExpression += MikiRandom.Roll(dieSides).ToString();
                            if (i + 1 < dieCount)
                            {
                                partialExpression += " + ";
                            }
                        }

                        fullExpression = regex.Replace(fullExpression, $"( {partialExpression} )", 1);
                        expressionCount++;
                    }

                    if (expressionCount > 1)
                    {
                        fullExpression = $"( {fullExpression} )";
                    }

                    Expression evaluation = new Expression(fullExpression);
                    rollResult = evaluation.Evaluate().ToString() + $" `{fullExpression}`";
                }
            }

            if (rollResult == "1" || rollResult.StartsWith("1 "))
            {
                await AchievementManager.Instance.GetContainerById("badluck").CheckAsync(new BasePacket()
                {
                    discordUser    = e.Author,
                    discordChannel = e.Channel
                });
            }

            rollResult = Regex.Replace(rollResult, @"(\s)\s+", "$1");
            rollResult = Regex.Replace(rollResult, @"(\S)([^\d\s])", "$1 $2");

            e.Channel.QueueMessageAsync(e.GetResource(LocaleTags.RollResult, e.Author.Username, rollResult));
        }
Example #7
0
        public async Task GiveMekosAsync(EventContext e)
        {
            Locale locale = new Locale(e.Guild.Id);

            string[] arguments = e.arguments.Split(' ');

            if (arguments.Length < 2)
            {
                e.ErrorEmbedResource("give_error_no_arg")
                .QueueToChannel(e.Channel);
                return;
            }

            if (e.message.MentionedUserIds.Count <= 0)
            {
                e.ErrorEmbedResource("give_error_no_mention")
                .QueueToChannel(e.Channel);
                return;
            }

            if (!int.TryParse(arguments[1], out int goldSent))
            {
                e.ErrorEmbedResource("give_error_amount_unparsable")
                .QueueToChannel(e.Channel);
                return;
            }

            if (goldSent > 999999)
            {
                e.ErrorEmbedResource("give_error_max_mekos")
                .QueueToChannel(e.Channel);
                return;
            }

            if (goldSent <= 0)
            {
                e.ErrorEmbedResource("give_error_min_mekos")
                .QueueToChannel(e.Channel);
                return;
            }

            using (MikiContext context = new MikiContext())
            {
                User sender = await User.GetAsync(context, e.Author);

                User receiver = await User.GetAsync(context, await e.Guild.GetUserAsync(e.message.MentionedUserIds.First()));

                if (goldSent <= sender.Currency)
                {
                    await sender.AddCurrencyAsync(-goldSent, e.Channel, sender);

                    IDiscordEmbed em = Utils.Embed;
                    em.Title       = "รฐลธโ€ยธ transaction";
                    em.Description = e.GetResource("give_description", sender.Name, receiver.Name, goldSent);

                    em.Color = new Miki.Common.Color(255, 140, 0);

                    em.QueueToChannel(e.Channel);
                    await context.SaveChangesAsync();
                }
                else
                {
                    e.ErrorEmbedResource("user_error_insufficient_mekos")
                    .QueueToChannel(e.Channel);
                }
            }
        }
Example #8
0
        private async Task StartFlip(EventContext e, int bet)
        {
            string[] arguments = e.arguments.Split(' ');

            if (bet <= 0)
            {
                return;
            }

            if (arguments.Length < 2)
            {
                return;
            }

            int pickedSide = -1;

            if (arguments[1].ToLower() == "heads" || arguments[1].ToLower() == "h")
            {
                pickedSide = 1;
            }
            else if (arguments[1].ToLower() == "tails" || arguments[1].ToLower() == "t")
            {
                pickedSide = 0;
            }

            if (pickedSide == -1)
            {
                return;
            }

            string headsUrl = "https://miki.ai/assets/img/miki-default-heads.png";
            string tailsUrl = "https://miki.ai/assets/img/miki-default-tails.png";

            if (e.arguments.Contains("-bonus"))
            {
                headsUrl = "https://miki.ai/assets/img/miki-secret-heads.png";
                tailsUrl = "https://miki.ai/assets/img/miki-secret-tails.png";
            }

            int    side     = MikiRandom.Next(2);
            string imageUrl = side == 1 ? headsUrl : tailsUrl;

            bool win         = (side == pickedSide);
            int  currencyNow = 0;

            using (MikiContext context = new MikiContext())
            {
                User u = await context.Users.FindAsync(e.Author.Id.ToDbLong());

                if (!win)
                {
                    bet = -bet;
                }
                u.Currency += bet;
                currencyNow = u.Currency;
                await context.SaveChangesAsync();
            }

            string output = "";

            if (win)
            {
                output = e.GetResource("flip_description_win", $"`{bet}`");
            }
            else
            {
                output = e.GetResource("flip_description_lose");
            }

            output += "\n" + e.GetResource("miki_blackjack_new_balance", currencyNow);

            IDiscordEmbed embed = Utils.Embed
                                  .SetAuthor(e.GetResource("flip_header") + " | " + e.Author.Username, e.Author.AvatarUrl,
                                             "https://patreon.com/mikibot")
                                  .SetDescription(output)
                                  .SetThumbnailUrl(imageUrl);

            await embed.SendToChannel(e.Channel);
        }
Example #9
0
        public async Task ValidateBet(EventContext e, Func <EventContext, int, Task> callback = null, int maxBet = 1000000)
        {
            if (!string.IsNullOrEmpty(e.arguments))
            {
                int       bet;
                const int noAskLimit = 10000;

                using (MikiContext context = new MikiContext())
                {
                    User user = await context.Users.FindAsync(e.Author.Id.ToDbLong());

                    if (user == null)
                    {
                        // TODO: add user null error
                        return;
                    }

                    string checkArg = e.arguments.Split(' ')[0];

                    if (int.TryParse(checkArg, out bet))
                    {
                    }
                    else if (checkArg.ToLower() == "all" || e.arguments == "*")
                    {
                        bet = user.Currency;
                    }
                    else
                    {
                        await e.ErrorEmbed(e.GetResource("miki_error_gambling_parse_error"))
                        .SendToChannel(e.Channel);

                        return;
                    }

                    if (bet < 1)
                    {
                        await e.ErrorEmbed(e.GetResource("miki_error_gambling_zero_or_less"))
                        .SendToChannel(e.Channel);
                    }
                    else if (bet > user.Currency)
                    {
                        await e.ErrorEmbed(e.GetResource("miki_mekos_insufficient"))
                        .SendToChannel(e.Channel);
                    }
                    else if (bet > maxBet)
                    {
                        await e.ErrorEmbed($"you cannot bet more than {maxBet} mekos!")
                        .SendToChannel(e.Channel);

                        return;
                    }
                    else if (bet > noAskLimit)
                    {
                        IDiscordEmbed embed = Utils.Embed;
                        embed.Description =
                            $"Are you sure you want to bet **{bet}**? You currently have `{user.Currency}` mekos.\n\nType `yes` to confirm.";
                        embed.Color = new IA.SDK.Color(0.4f, 0.6f, 1f);
                        await embed.SendToChannel(e.Channel);

                        CommandHandler confirmCommand = new CommandHandlerBuilder(Bot.instance.Events)
                                                        .AddPrefix("")
                                                        .DisposeInSeconds(20)
                                                        .SetOwner(e.message)
                                                        .AddCommand(
                            new RuntimeCommandEvent("yes")
                            .Default(async(ec) =>
                        {
                            await ec.commandHandler.RequestDisposeAsync();
                            await ec.message.DeleteAsync();
                            if (callback != null)
                            {
                                if (bet > user.Currency)
                                {
                                    await e.ErrorEmbed(e.GetResource("miki_mekos_insufficient"))
                                    .SendToChannel(e.Channel);
                                    return;
                                }
                                await callback(e, bet);
                            }
                        })).Build();

                        Bot.instance.Events.AddPrivateCommandHandler(e.message, confirmCommand);
                    }
                    else
                    {
                        if (callback != null)
                        {
                            await callback(e, bet);
                        }
                    }
                }
            }
            else
            {
                await Utils.ErrorEmbed(e.Channel.GetLocale(), e.GetResource("miki_error_gambling_no_arg"))
                .SendToChannel(e.Channel);
            }
        }
Example #10
0
        public async Task SetRoleLevelAsync(EventContext e)
        {
            using (var context = new MikiContext())
            {
                Locale locale = Locale.GetEntity(e.Channel.Id.ToDbLong());

                List <string> allArgs = new List <string>();
                allArgs.AddRange(e.arguments.Split(' '));
                if (allArgs.Count >= 2)
                {
                    int levelrequirement = int.Parse(allArgs[allArgs.Count - 1]);
                    allArgs.RemoveAt(allArgs.Count - 1);
                    IDiscordRole role = e.Guild.Roles
                                        .Find(r => r.Name.ToLower() == string.Join(" ", allArgs).TrimEnd(' ').TrimStart(' ').ToLower());

                    if (role == null)
                    {
                        await e.ErrorEmbed(e.GetResource("error_role_not_found"))
                        .QueueToChannel(e.Channel);

                        return;
                    }

                    LevelRole lr = await context.LevelRoles.FindAsync(e.Guild.Id.ToDbLong(), role.Id.ToDbLong());

                    if (lr == null)
                    {
                        lr = context.LevelRoles.Add(new LevelRole()
                        {
                            GuildId       = e.Guild.Id.ToDbLong(),
                            RoleId        = role.Id.ToDbLong(),
                            RequiredLevel = levelrequirement
                        }).Entity;

                        IDiscordEmbed embed = Utils.Embed;
                        embed.Title       = "Added Role!";
                        embed.Description = $"I'll give someone the role {role.Name} when he/she reaches level {levelrequirement}!";

                        IDiscordUser currentUser = await e.GetCurrentUserAsync();

                        if (!currentUser.HasPermissions(e.Channel, DiscordGuildPermission.ManageRoles))
                        {
                            embed.AddInlineField(e.GetResource("miki_warning"), e.GetResource("setrolelevel_error_no_permissions", $"`{e.GetResource("permission_manage_roles")}`"));
                        }

                        await embed.QueueToChannel(e.Channel);
                    }
                    else
                    {
                        lr.RequiredLevel = levelrequirement;

                        IDiscordEmbed embed = Utils.Embed;
                        embed.Title       = "Updated Role!";
                        embed.Description = $"I'll give someone the role {role.Name} when he/she reaches level {levelrequirement}!";
                        await embed.QueueToChannel(e.Channel);
                    }
                    await context.SaveChangesAsync();
                }
                else
                {
                    await Utils.ErrorEmbed(locale, "Make sure to fill out both the role and the level when creating this!")
                    .QueueToChannel(e.Channel);
                }
            }
        }
Example #11
0
        public async Task GuildWeekly(EventContext context)
        {
            using (MikiContext database = new MikiContext())
            {
                Locale          locale   = Locale.GetEntity(context.Channel.Id);
                LocalExperience thisUser = await database.Experience.FindAsync(context.Guild.Id.ToDbLong(), context.Author.Id.ToDbLong());

                GuildUser thisGuild = await database.GuildUsers.FindAsync(context.Guild.Id.ToDbLong());

                Timer timer = await database.Timers.FindAsync(context.Guild.Id.ToDbLong(), context.Author.Id.ToDbLong());

                if (thisUser == null)
                {
                    Log.ErrorAt("Guildweekly", "User is null");
                    return;
                }

                if (thisGuild == null)
                {
                    Log.ErrorAt("Guildweekly", "Guild is null");
                    return;
                }

                if (thisUser.Experience > thisGuild.MinimalExperienceToGetRewards)
                {
                    if (timer == null)
                    {
                        timer = database.Timers.Add(new Timer()
                        {
                            GuildId = context.Guild.Id.ToDbLong(),
                            UserId  = context.Author.Id.ToDbLong(),
                            Value   = DateTime.Now.AddDays(-30)
                        });
                        await database.SaveChangesAsync();
                    }

                    if (timer.Value.AddDays(7) <= DateTime.Now)
                    {
                        SocketGuild guild = Bot.instance.Client.GetGuild(thisGuild.Id.FromDbLong());

                        GuildUser rival = await thisGuild.GetRival();

                        if (rival == null)
                        {
                            await Utils.Embed
                            .SetTitle(locale.GetString("miki_terms_weekly"))
                            .SetDescription(context.GetResource("guildweekly_error_no_rival"))
                            .SendToChannel(context.Channel);

                            return;
                        }

                        if (rival.Experience > thisGuild.Experience)
                        {
                            await Utils.Embed
                            .SetTitle(locale.GetString("miki_terms_weekly"))
                            .SetDescription(context.GetResource("guildweekly_error_low_level"))
                            .SendToChannel(context.Channel);

                            return;
                        }

                        int mekosGained = (int)Math.Round((((Global.random.NextDouble() + 1.25) * 0.5) * 10) * thisGuild.CalculateLevel(thisGuild.Experience));

                        User user = await database.Users.FindAsync(context.Author.Id.ToDbLong());

                        if (user == null)
                        {
                            // TODO: Add response
                            return;
                        }

                        await user.AddCurrencyAsync(mekosGained, context.Channel);

                        await Utils.Embed
                        .SetTitle(locale.GetString("miki_terms_weekly"))
                        .AddInlineField("Mekos", mekosGained.ToString())
                        .SendToChannel(context.Channel);

                        timer.Value = DateTime.Now;
                        await database.SaveChangesAsync();
                    }
                    else
                    {
                        await Utils.Embed
                        .SetTitle(locale.GetString("miki_terms_weekly"))
                        .SetDescription(context.GetResource("guildweekly_error_timer_running", (timer.Value.AddDays(7) - DateTime.Now).ToTimeString(locale)))
                        .SendToChannel(context.Channel);
                    }
                }
                else
                {
                    await Utils.Embed
                    .SetTitle(locale.GetString("miki_terms_weekly"))
                    .SetDescription(locale.GetString("miki_guildweekly_insufficient_exp", thisGuild.MinimalExperienceToGetRewards))
                    .SendToChannel(context.Channel);
                }
            }
        }
Example #12
0
        public async Task GetDailyAsync(EventContext e)
        {
            using (var context = new MikiContext())
            {
                User u = await User.GetAsync(context, e.Author);

                if (u == null)
                {
                    e.ErrorEmbed(e.GetResource("user_error_no_account"))
                    .ToEmbed().QueueToChannel(e.Channel);
                    return;
                }

                int dailyAmount       = 100;
                int dailyStreakAmount = 20;

                if (await u.IsDonatorAsync(context))
                {
                    dailyAmount       *= 2;
                    dailyStreakAmount *= 2;
                }

                if (u.LastDailyTime.AddHours(23) >= DateTime.Now)
                {
                    e.ErrorEmbed($"You already claimed your daily today! Please wait another `{(u.LastDailyTime.AddHours(23) - DateTime.Now).ToTimeString(e.Channel.Id)}` before using it again.")
                    .AddInlineField("Need more mekos?", "Vote for us every day on [DiscordBots](https://discordbots.org/bot/160105994217586689/vote) for a bonus daily!")
                    .ToEmbed().QueueToChannel(e.Channel);
                    return;
                }

                int    streak   = 0;
                string redisKey = $"user:{e.Author.Id}:daily";

                if (await Global.RedisClient.ExistsAsync(redisKey))
                {
                    streak = await Global.RedisClient.GetAsync <int>(redisKey);

                    streak++;
                }

                int amount = dailyAmount + (dailyStreakAmount * Math.Min(100, streak));

                await u.AddCurrencyAsync(amount, e.Channel);

                u.LastDailyTime = DateTime.Now;

                var embed = Utils.Embed.SetTitle("รฐลธโ€™ยฐ Daily")
                            .SetDescription($"Received **{amount}** Mekos! You now have `{u.Currency}` Mekos")
                            .SetColor(253, 216, 136);

                if (streak > 0)
                {
                    embed.AddInlineField("Streak!", $"You're on a {streak} day daily streak!");
                }

                embed.ToEmbed().QueueToChannel(e.Channel);

                await Global.RedisClient.UpsertAsync(redisKey, streak, new TimeSpan(48, 0, 0));

                await context.SaveChangesAsync();
            }
        }
Example #13
0
        public async Task GiveMekosAsync(EventContext e)
        {
            if (e.Arguments.Count < 2)
            {
                e.ErrorEmbedResource("give_error_no_arg")
                .ToEmbed().QueueToChannel(e.Channel);
                return;
            }

            ArgObject arg = e.Arguments.FirstOrDefault();

            IDiscordUser user = null;

            if (arg != null)
            {
                user = await arg.GetUserAsync(e.Guild);
            }

            if (user == null)
            {
                e.ErrorEmbedResource("give_error_no_mention")
                .ToEmbed().QueueToChannel(e.Channel);
                return;
            }

            arg = arg.Next();

            int?amount = arg?.AsInt() ?? null;

            if (amount == null)
            {
                e.ErrorEmbedResource("give_error_amount_unparsable")
                .ToEmbed().QueueToChannel(e.Channel);
                return;
            }

            if (amount <= 0)
            {
                e.ErrorEmbedResource("give_error_min_mekos")
                .ToEmbed().QueueToChannel(e.Channel);
                return;
            }

            using (MikiContext context = new MikiContext())
            {
                User sender = await User.GetAsync(context, e.Author);

                User receiver = await User.GetAsync(context, user);

                if (amount.Value <= sender.Currency)
                {
                    await sender.AddCurrencyAsync(-amount.Value, e.Channel, sender);

                    await receiver.AddCurrencyAsync(amount.Value, e.Channel, sender);

                    new EmbedBuilder()
                    {
                        Title       = "รฐลธโ€ยธ transaction",
                        Description = e.GetResource("give_description", sender.Name, receiver.Name, amount.Value),
                        Color       = new Color(255, 140, 0),
                    }.ToEmbed().QueueToChannel(e.Channel);

                    await context.SaveChangesAsync();
                }
                else
                {
                    e.ErrorEmbedResource("user_error_insufficient_mekos")
                    .ToEmbed().QueueToChannel(e.Channel);
                }
            }
        }
Example #14
0
        public async Task GiveReputationAsync(EventContext e)
        {
            using (var context = new MikiContext())
            {
                User giver = await context.Users.FindAsync(e.Author.Id.ToDbLong());

                var repObject = await Global.RedisClient.GetAsync <ReputationObject>($"user:{giver.Id}:rep");

                if (repObject == null)
                {
                    repObject = new ReputationObject()
                    {
                        LastReputationGiven  = DateTime.Now,
                        ReputationPointsLeft = 3
                    };

                    await Global.RedisClient.UpsertAsync(
                        $"user:{giver.Id}:rep",
                        repObject,
                        DateTime.UtcNow.AddDays(1).Date - DateTime.UtcNow
                        );
                }

                ArgObject arg = e.Arguments.FirstOrDefault();

                if (arg == null)
                {
                    TimeSpan pointReset = (DateTime.Now.AddDays(1).Date - DateTime.Now);

                    new EmbedBuilder()
                    {
                        Title       = (e.GetResource("miki_module_accounts_rep_header")),
                        Description = (e.GetResource("miki_module_accounts_rep_description"))
                    }.AddInlineField(e.GetResource("miki_module_accounts_rep_total_received"), giver.Reputation.ToString())
                    .AddInlineField(e.GetResource("miki_module_accounts_rep_reset"), pointReset.ToTimeString(e.Channel.Id))
                    .AddInlineField(e.GetResource("miki_module_accounts_rep_remaining"), repObject.ReputationPointsLeft)
                    .ToEmbed().QueueToChannel(e.Channel);
                    return;
                }
                else
                {
                    Dictionary <IDiscordUser, short> usersMentioned = new Dictionary <IDiscordUser, short>();

                    EmbedBuilder embed = new EmbedBuilder();

                    int  totalAmountGiven = 0;
                    bool mentionedSelf    = false;

                    while (true || totalAmountGiven <= repObject.ReputationPointsLeft)
                    {
                        if (arg == null)
                        {
                            break;
                        }

                        IDiscordUser u = await arg.GetUserAsync(e.Guild);

                        short amount = 1;

                        if (u == null)
                        {
                            break;
                        }

                        arg = arg?.Next();

                        if ((arg?.AsInt() ?? -1) != -1)
                        {
                            amount = (short)arg.AsInt().Value;
                            arg    = arg.Next();
                        }
                        else if (Utils.IsAll(arg))
                        {
                            amount = repObject.ReputationPointsLeft;
                            arg    = arg.Next();
                        }

                        if (u.Id == e.Author.Id)
                        {
                            mentionedSelf = true;
                            continue;
                        }

                        totalAmountGiven += amount;

                        if (usersMentioned.Keys.Where(x => x.Id == u.Id).Count() > 0)
                        {
                            usersMentioned[usersMentioned.Keys.Where(x => x.Id == u.Id).First()] += amount;
                        }
                        else
                        {
                            usersMentioned.Add(u, amount);
                        }
                    }

                    if (mentionedSelf)
                    {
                        embed.Footer = new EmbedFooter()
                        {
                            Text = e.GetResource("warning_mention_self"),
                        };
                    }

                    if (usersMentioned.Count == 0)
                    {
                        return;
                    }
                    else
                    {
                        if (totalAmountGiven <= 0)
                        {
                            e.ErrorEmbedResource("miki_module_accounts_rep_error_zero")
                            .ToEmbed().QueueToChannel(e.Channel);
                            return;
                        }

                        if (usersMentioned.Sum(x => x.Value) > repObject.ReputationPointsLeft)
                        {
                            e.ErrorEmbedResource("error_rep_limit", usersMentioned.Count, usersMentioned.Sum(x => x.Value), repObject.ReputationPointsLeft)
                            .ToEmbed().QueueToChannel(e.Channel);
                            return;
                        }
                    }

                    embed.Title       = (e.GetResource("miki_module_accounts_rep_header"));
                    embed.Description = (e.GetResource("rep_success"));

                    foreach (var user in usersMentioned)
                    {
                        User receiver = await User.GetAsync(context, user.Key);

                        receiver.Reputation += user.Value;

                        embed.AddInlineField(
                            receiver.Name,
                            string.Format("{0} => {1} (+{2})", receiver.Reputation - user.Value, receiver.Reputation, user.Value)
                            );
                    }

                    repObject.ReputationPointsLeft -= (short)usersMentioned.Sum(x => x.Value);

                    await Global.RedisClient.UpsertAsync(
                        $"user:{giver.Id}:rep",
                        repObject,
                        DateTime.UtcNow.AddDays(1).Date - DateTime.UtcNow
                        );

                    embed.AddInlineField(e.GetResource("miki_module_accounts_rep_points_left"), repObject.ReputationPointsLeft)
                    .ToEmbed().QueueToChannel(e.Channel);

                    await context.SaveChangesAsync();
                }
            }
        }
Example #15
0
 public async Task LunchAsync(EventContext e)
 {
     e.Channel.QueueMessageAsync(e.GetResource("lunch_line") + "\n" + lunchposts[MikiRandom.Next(0, lunchposts.Length)]);
 }
Example #16
0
        private async Task StartFlip(EventContext e, int bet)
        {
            if (e.Arguments.Count < 2)
            {
                e.ErrorEmbed("Please pick either `heads` or `tails`!")
                .ToEmbed().QueueToChannel(e.Channel);
                return;
            }

            string sideParam = e.Arguments.Get(1).Argument.ToLower();

            if (bet <= 0)
            {
                // TODO: add a error message
                return;
            }

            int pickedSide = -1;

            if (sideParam[0] == 'h')
            {
                pickedSide = 1;
            }
            else if (sideParam[0] == 't')
            {
                pickedSide = 0;
            }

            if (pickedSide == -1)
            {
                e.ErrorEmbed("This is not a valid option!")
                .ToEmbed().QueueToChannel(e.Channel);
                return;
            }

            string headsUrl = "https://miki-cdn.nyc3.digitaloceanspaces.com/commands/miki-default-heads.png";
            string tailsUrl = "https://miki-cdn.nyc3.digitaloceanspaces.com/commands/miki-default-tails.png";

            if (e.Arguments.Contains("-bonus"))
            {
                headsUrl = "https://miki-cdn.nyc3.digitaloceanspaces.com/commands/miki-secret-heads.png";
                tailsUrl = "https://miki-cdn.nyc3.digitaloceanspaces.com/commands/miki-secret-tails.png";
            }

            int    side     = MikiRandom.Next(2);
            string imageUrl = side == 1 ? headsUrl : tailsUrl;

            bool win         = (side == pickedSide);
            int  currencyNow = 0;

            using (MikiContext context = new MikiContext())
            {
                User u = await context.Users.FindAsync(e.Author.Id.ToDbLong());

                if (!win)
                {
                    bet = -bet;
                }
                u.Currency += bet;
                currencyNow = u.Currency;
                await context.SaveChangesAsync();
            }

            string output = "";

            if (win)
            {
                output = e.GetResource("flip_description_win", $"`{bet}`");
            }
            else
            {
                output = e.GetResource("flip_description_lose");
            }

            output += "\n" + e.GetResource("miki_blackjack_new_balance", currencyNow);

            DiscordEmbed embed = Utils.Embed
                                 .SetAuthor(e.GetResource("flip_header") + " | " + e.Author.Username, e.Author.GetAvatarUrl(),
                                            "https://patreon.com/mikibot")
                                 .SetDescription(output)
                                 .SetThumbnail(imageUrl)
                                 .ToEmbed();

            embed.QueueToChannel(e.Channel);
        }
Example #17
0
 public async Task PunAsync(EventContext e)
 {
     e.Channel.QueueMessageAsync(e.GetResource(puns[MikiRandom.Next(0, puns.Length)]));
 }
Example #18
0
        public async Task StartSlots(EventContext e, int bet)
        {
            using (var context = new MikiContext())
            {
                User u = await context.Users.FindAsync(e.Author.Id.ToDbLong());

                int moneyReturned = 0;

                string[] objects =
                {
                    "๐Ÿ’", "๐Ÿ’", "๐Ÿ’", "๐Ÿ’",
                    "๐ŸŠ", "๐ŸŠ", "๐ŸŠ",
                    "๐Ÿ“", "๐Ÿ“",
                    "๐Ÿ", "๐Ÿ",
                    "๐Ÿ‡", "๐Ÿ‡",
                    "๐Ÿ‰", "๐Ÿ‰",
                    "โญ", "โญ",
                    "๐Ÿ‰",
                    "๐Ÿ", "๐Ÿ",
                    "๐Ÿ“", "๐Ÿ“",
                    "๐ŸŠ", "๐ŸŠ", "๐ŸŠ",
                    "๐Ÿ’", "๐Ÿ’", "๐Ÿ’", "๐Ÿ’",
                };

                EmbedBuilder embed = new EmbedBuilder()
                                     .SetAuthor(e.GetResource(LocaleTags.SlotsHeader) + " | " + e.Author.Username, e.Author.GetAvatarUrl(), "https://patreon.com/mikibot");

                string[] objectsChosen =
                {
                    objects[MikiRandom.Next(objects.Length)],
                    objects[MikiRandom.Next(objects.Length)],
                    objects[MikiRandom.Next(objects.Length)]
                };

                Dictionary <string, int> score = new Dictionary <string, int>();

                foreach (string o in objectsChosen)
                {
                    if (score.ContainsKey(o))
                    {
                        score[o]++;
                        continue;
                    }
                    score.Add(o, 1);
                }

                if (score.ContainsKey("๐Ÿ’"))
                {
                    if (score["๐Ÿ’"] == 2)
                    {
                        moneyReturned = (int)Math.Ceiling(bet * 0.5f);
                    }
                    else if (score["๐Ÿ’"] == 3)
                    {
                        moneyReturned = (int)Math.Ceiling(bet * 1f);
                    }
                }
                if (score.ContainsKey("๐ŸŠ"))
                {
                    if (score["๐ŸŠ"] == 2)
                    {
                        moneyReturned = (int)Math.Ceiling(bet * 0.8f);
                    }
                    else if (score["๐ŸŠ"] == 3)
                    {
                        moneyReturned = (int)Math.Ceiling(bet * 1.5f);
                    }
                }
                if (score.ContainsKey("๐Ÿ“"))
                {
                    if (score["๐Ÿ“"] == 2)
                    {
                        moneyReturned = (int)Math.Ceiling(bet * 1f);
                    }
                    else if (score["๐Ÿ“"] == 3)
                    {
                        moneyReturned = (int)Math.Ceiling(bet * 2f);
                    }
                }
                if (score.ContainsKey("๐Ÿ"))
                {
                    if (score["๐Ÿ"] == 2)
                    {
                        moneyReturned = (int)Math.Ceiling(bet * 1f);
                    }
                    if (score["๐Ÿ"] == 3)
                    {
                        moneyReturned = (int)Math.Ceiling(bet * 4f);
                    }
                }
                if (score.ContainsKey("๐Ÿ‡"))
                {
                    if (score["๐Ÿ‡"] == 2)
                    {
                        moneyReturned = (int)Math.Ceiling(bet * 1.2f);
                    }
                    if (score["๐Ÿ‡"] == 3)
                    {
                        moneyReturned = (int)Math.Ceiling(bet * 6f);
                    }
                }
                if (score.ContainsKey("๐Ÿ‰"))
                {
                    if (score["๐Ÿ‰"] == 2)
                    {
                        moneyReturned = (int)Math.Ceiling(bet * 1.5f);
                    }
                    if (score["๐Ÿ‰"] == 3)
                    {
                        moneyReturned = (int)Math.Ceiling(bet * 10f);
                    }
                }
                if (score.ContainsKey("โญ"))
                {
                    if (score["โญ"] == 2)
                    {
                        moneyReturned = (int)Math.Ceiling(bet * 2f);
                    }
                    if (score["โญ"] == 3)
                    {
                        moneyReturned = (int)Math.Ceiling(bet * 12f);

                        await AchievementManager.Instance.GetContainerById("slots").CheckAsync(new BasePacket()
                        {
                            discordChannel = e.Channel,
                            discordUser    = e.Author
                        });
                    }
                }

                if (moneyReturned == 0)
                {
                    moneyReturned = -bet;
                    embed.AddField(e.GetResource("miki_module_fun_slots_lose_header"),
                                   e.GetResource("miki_module_fun_slots_lose_amount", bet, u.Currency - bet));
                }
                else
                {
                    embed.AddField(e.GetResource(LocaleTags.SlotsWinHeader),
                                   e.GetResource(LocaleTags.SlotsWinMessage, moneyReturned, u.Currency + moneyReturned));
                }

                embed.Description = string.Join(" ", objectsChosen);
                await u.AddCurrencyAsync(moneyReturned, e.Channel);

                await context.SaveChangesAsync();

                embed.ToEmbed().QueueToChannel(e.Channel);
            }
        }
Example #19
0
        public async Task GiveReputationAsync(EventContext e)
        {
            using (var context = new MikiContext())
            {
                Locale locale = new Locale(e.Channel.Id.ToDbLong());

                User giver = await context.Users.FindAsync(e.Author.Id.ToDbLong());

                List <ulong> mentionedUsers = e.message.MentionedUserIds.ToList();
                string[]     args           = e.arguments.Split(' ');
                short        repAmount      = 1;

                bool mentionedSelf = mentionedUsers.RemoveAll(x => x == e.Author.Id) > 0;

                var repObject = Global.redisClient.Get <ReputationObject>($"user:{giver.Id}:rep");

                if (repObject == null)
                {
                    repObject = new ReputationObject()
                    {
                        LastReputationGiven  = DateTime.Now,
                        ReputationPointsLeft = 3
                    };
                }

                IDiscordEmbed embed = Utils.Embed;

                if (mentionedSelf)
                {
                    embed.SetFooter(e.GetResource("warning_mention_self"), "");
                }

                if (mentionedUsers.Count == 0)
                {
                    TimeSpan pointReset = (DateTime.Now.AddDays(1).Date - DateTime.Now);

                    embed.SetTitle(locale.GetString("miki_module_accounts_rep_header"))
                    .SetDescription(locale.GetString("miki_module_accounts_rep_description"))
                    .AddInlineField(locale.GetString("miki_module_accounts_rep_total_received"), giver.Reputation.ToString())
                    .AddInlineField(locale.GetString("miki_module_accounts_rep_reset"), pointReset.ToTimeString(e.Channel.GetLocale()))
                    .AddInlineField(locale.GetString("miki_module_accounts_rep_remaining"), repObject.ReputationPointsLeft)
                    .QueueToChannel(e.Channel);
                    return;
                }
                else
                {
                    if (args.Length > 1)
                    {
                        if (Utils.IsAll(args[args.Length - 1], e.Channel.GetLocale()))
                        {
                            repAmount = repObject.ReputationPointsLeft;
                        }
                        else if (short.TryParse(args[1], out short x))
                        {
                            repAmount = x;
                        }
                    }

                    if (repAmount <= 0)
                    {
                        e.ErrorEmbedResource("miki_module_accounts_rep_error_zero")
                        .QueueToChannel(e.Channel);
                        return;
                    }

                    if (mentionedUsers.Count * repAmount > repObject.ReputationPointsLeft)
                    {
                        e.ErrorEmbedResource("error_rep_limit", mentionedUsers.Count, repAmount, repObject.ReputationPointsLeft)
                        .QueueToChannel(e.Channel);
                        return;
                    }
                }

                embed.SetTitle(locale.GetString("miki_module_accounts_rep_header"))
                .SetDescription(locale.GetString("rep_success"));

                foreach (ulong user in mentionedUsers)
                {
                    IDiscordUser u = await e.Guild.GetUserAsync(user);

                    User receiver = await User.GetAsync(context, u);

                    receiver.Reputation += repAmount;

                    embed.AddInlineField(receiver.Name, string.Format("{0} => {1} (+{2})", receiver.Reputation - repAmount, receiver.Reputation, repAmount));
                }

                repObject.ReputationPointsLeft -= (short)(repAmount * mentionedUsers.Count);

                await Global.redisClient.AddAsync($"user:{giver.Id}:rep", repObject);

                embed.AddInlineField(locale.GetString("miki_module_accounts_rep_points_left"), repObject.ReputationPointsLeft)
                .QueueToChannel(e.Channel);

                await context.SaveChangesAsync();
            }
        }
Example #20
0
        // TODO: probable rewrite at some point
        public async Task ValidateBet(EventContext e, Func <EventContext, int, Task> callback = null, int maxBet = 1000000)
        {
            ArgObject arg = e.Arguments.FirstOrDefault();

            if (arg != null)
            {
                const int noAskLimit = 10000;

                using (MikiContext context = new MikiContext())
                {
                    User user = await context.Users.FindAsync(e.Author.Id.ToDbLong());

                    if (user == null)
                    {
                        // TODO: add user null error
                        return;
                    }

                    string checkArg = arg.Argument;

                    if (int.TryParse(checkArg, out int bet))
                    {
                    }
                    else if (checkArg.ToLower() == "all" || checkArg == "*")
                    {
                        bet = user.Currency > maxBet ? maxBet : user.Currency;
                    }
                    else
                    {
                        e.ErrorEmbed(e.GetResource("miki_error_gambling_parse_error"))
                        .ToEmbed().QueueToChannel(e.Channel);
                        return;
                    }

                    if (bet < 1)
                    {
                        e.ErrorEmbed(e.GetResource("miki_error_gambling_zero_or_less"))
                        .ToEmbed().QueueToChannel(e.Channel);
                    }
                    else if (bet > user.Currency)
                    {
                        e.ErrorEmbed(e.GetResource("miki_mekos_insufficient"))
                        .ToEmbed().QueueToChannel(e.Channel);
                    }
                    else if (bet > maxBet)
                    {
                        e.ErrorEmbed($"you cannot bet more than {maxBet} mekos!")
                        .ToEmbed().QueueToChannel(e.Channel);
                        return;
                    }
                    else if (bet > noAskLimit)
                    {
                        IDiscordMessage confirmationMessage = null;

                        Framework.Events.CommandMap map = new Framework.Events.CommandMap();
                        map.AddCommand(new CommandEvent()
                        {
                            Name           = "yes",
                            ProcessCommand = async(ec) => {
                                await confirmationMessage.DeleteAsync();
                                await ValidateGlitch(ec, callback, bet);
                            }
                        });

                        SimpleCommandHandler commandHandler = new SimpleCommandHandler(map);
                        commandHandler.AddPrefix("");

                        e.EventSystem.GetCommandHandler <SessionBasedCommandHandler>()
                        .AddSession(new CommandSession {
                            ChannelId = e.Channel.Id, UserId = e.Author.Id
                        }, commandHandler, new TimeSpan(0, 2, 0));

                        EmbedBuilder embed = Utils.Embed;
                        embed.Description =
                            $"Are you sure you want to bet **{bet}**? You currently have `{user.Currency}` mekos.\n\nType `yes` to confirm.";
                        embed.Color         = new Color(0.4f, 0.6f, 1f);
                        confirmationMessage = await embed.ToEmbed().SendToChannel(e.Channel);
                    }
                    else
                    {
                        if (callback != null)
                        {
                            await callback(e, bet);
                        }
                    }
                }
            }
            else
            {
                e.ErrorEmbed(e.GetResource("miki_error_gambling_no_arg"))
                .ToEmbed().QueueToChannel(e.Channel);
            }
        }
Example #21
0
        public async Task SetGuildConfig(EventContext e)
        {
            using (MikiContext context = new MikiContext())
            {
                GuildUser g = await context.GuildUsers.FindAsync(e.Guild.Id.ToDbLong());

                ArgObject arg = e.Arguments.FirstOrDefault();

                if (arg == null)
                {
                    // TODO: error message
                    return;
                }

                switch (arg.Argument)
                {
                case "expneeded":
                {
                    arg = arg.Next();

                    if (arg != null)
                    {
                        if (int.TryParse(arg.Argument, out int value))
                        {
                            g.MinimalExperienceToGetRewards = value;

                            Utils.Embed
                            .WithTitle(e.GetResource("miki_terms_config"))
                            .WithDescription(e.GetResource("guildconfig_expneeded", value))
                            .Build().QueueToChannel(e.Channel);
                        }
                    }
                }
                break;

                case "visible":
                {
                    arg = arg.Next();

                    if (arg != null)
                    {
                        bool?result = arg.AsBoolean();

                        if (!result.HasValue)
                        {
                            return;
                        }

                        g.VisibleOnLeaderboards = result.Value;

                        string resourceString = g.VisibleOnLeaderboards ? "guildconfig_visibility_true" : "guildconfig_visibility_false";

                        Utils.Embed
                        .WithTitle(e.GetResource("miki_terms_config"))
                        .WithDescription(resourceString)
                        .Build().QueueToChannel(e.Channel);
                    }
                }
                break;
                }
                await context.SaveChangesAsync();
            }
        }
Example #22
0
        public async Task HelpAsync(EventContext e)
        {
            ArgObject arg = e.Arguments.FirstOrDefault();

            if (arg != null)
            {
                CommandEvent ev = e.EventSystem.GetCommandHandler <SimpleCommandHandler>().Commands.FirstOrDefault(x => x.Name.ToLower() == arg.Argument.ToString().ToLower());

                if (ev == null)
                {
                    EmbedBuilder helpListEmbed = Utils.Embed;
                    helpListEmbed.Title = e.GetResource("miki_module_help_error_null_header");

                    helpListEmbed.Description = e.GetResource("miki_module_help_error_null_message", await e.EventSystem.GetCommandHandler <SimpleCommandHandler>().GetPrefixAsync(e.Guild.Id));
                    helpListEmbed.Color       = new Color(0.6f, 0.6f, 1.0f);

                    API.StringComparison.StringComparer   comparer = new API.StringComparison.StringComparer(e.EventSystem.GetCommandHandler <SimpleCommandHandler>().Commands.Select(x => x.Name));
                    API.StringComparison.StringComparison best     = comparer.GetBest(arg.Argument);

                    helpListEmbed.AddField(e.GetResource("miki_module_help_didyoumean"), best.text);

                    helpListEmbed.Build()
                    .QueueToChannel(e.Channel);
                }
                else
                {
                    if (e.EventSystem.GetCommandHandler <SimpleCommandHandler>().GetUserAccessibility(e.message) < ev.Accessibility)
                    {
                        return;
                    }

                    EmbedBuilder explainedHelpEmbed = new EmbedBuilder()
                    {
                        Title = ev.Name.ToUpper()
                    };

                    if (ev.Aliases.Length > 0)
                    {
                        explainedHelpEmbed.AddInlineField(
                            e.GetResource("miki_module_general_help_aliases"),
                            string.Join(", ", ev.Aliases));
                    }

                    explainedHelpEmbed.AddField(
                        e.GetResource("miki_module_general_help_description"),
                        (Locale.HasString(e.Channel.Id, "miki_command_description_" + ev.Name.ToLower()))
                                                        ? e.GetResource("miki_command_description_" + ev.Name.ToLower()) : e.GetResource("miki_placeholder_null"));

                    explainedHelpEmbed.AddField(
                        e.GetResource("miki_module_general_help_usage"),
                        (Locale.HasString(e.Channel.Id, "miki_command_usage_" + ev.Name.ToLower()))
                                                        ? e.GetResource("miki_command_usage_" + ev.Name.ToLower()) : e.GetResource("miki_placeholder_null"));

                    explainedHelpEmbed.Build().QueueToChannel(e.Channel);
                }
                return;
            }

            new EmbedBuilder()
            {
                Description = e.GetResource("miki_module_general_help_dm"),
                Color       = new Color(0.6f, 0.6f, 1.0f)
            }.Build().QueueToChannel(e.Channel);


            EmbedBuilder embedBuilder = new EmbedBuilder();

            foreach (Module m in e.EventSystem.GetCommandHandler <SimpleCommandHandler>().Modules.OrderBy(x => x.Name))
            {
                List <CommandEvent> events = m.Events
                                             .Where(x => e.EventSystem.GetCommandHandler <SimpleCommandHandler>().GetUserAccessibility(e.message) >= x.Accessibility).ToList();

                if (events.Count > 0)
                {
                    embedBuilder.AddField(m.Name.ToUpper(), string.Join(", ", events.Select(x => "`" + x.Name + "`")));
                }
            }

            embedBuilder.Build().QueueToUser(e.Author);
        }
Example #23
0
        public async Task MarryAsync(EventContext e)
        {
            long askerId    = 0;
            long receiverId = 0;

            ArgObject args = e.Arguments.FirstOrDefault();

            if (args == null)
            {
                return;
            }

            IDiscordGuildUser user = await args.GetUserAsync(e.Guild);

            if (user == null)
            {
                e.Channel.QueueMessageAsync("Couldn't find this person..");
                return;
            }

            if (user.Id == (await e.Guild.GetSelfAsync()).Id)
            {
                e.Channel.QueueMessageAsync("(ยดใƒปฯ‰ใƒป`)");
                return;
            }

            using (MikiContext context = new MikiContext())
            {
                User mentionedPerson = await User.GetAsync(context, user);

                User currentUser = await User.GetAsync(context, e.Author);

                askerId    = currentUser.Id;
                receiverId = mentionedPerson.Id;

                if (currentUser == null || mentionedPerson == null)
                {
                    e.ErrorEmbed(e.GetResource("miki_module_accounts_marry_error_null")).ToEmbed().QueueToChannel(e.Channel);
                    return;
                }

                if (mentionedPerson.Banned)
                {
                    e.ErrorEmbed("This person has been banned from Miki.").ToEmbed().QueueToChannel(e.Channel);
                    return;
                }

                if (mentionedPerson.Id == currentUser.Id)
                {
                    e.ErrorEmbed(e.GetResource("miki_module_accounts_marry_error_null")).ToEmbed().QueueToChannel(e.Channel);
                    return;
                }

                if (await Marriage.ExistsAsync(context, mentionedPerson.Id, currentUser.Id))
                {
                    e.ErrorEmbed(e.GetResource("miki_module_accounts_marry_error_exists")).ToEmbed().QueueToChannel(e.Channel);
                    return;
                }
            }

            await Marriage.ProposeAsync(askerId, receiverId);

            Utils.Embed
            .SetTitle("๐Ÿ’" + e.GetResource("miki_module_accounts_marry_text", $"**{e.Author.Username}**", $"**{user.Username}**"))
            .SetDescription(e.GetResource("miki_module_accounts_marry_text2", user.Username, e.Author.Username))
            .SetColor(0.4f, 0.4f, 0.8f)
            .SetThumbnail("https://i.imgur.com/TKZSKIp.png")
            .AddInlineField("โœ… To accept", $">acceptmarriage @user")
            .AddInlineField("โŒ To decline", $">declinemarriage @user")
            .SetFooter("Take your time though! This proposal won't disappear", "")
            .ToEmbed().QueueToChannel(e.Channel);
        }
Example #24
0
 public async Task InviteAsync(EventContext e)
 {
     e.Channel.QueueMessageAsync(e.GetResource("miki_module_general_invite_message"));
     (await e.Author.GetOrCreateDMChannelAsync()).QueueMessageAsync(e.GetResource("miki_module_general_invite_dm")
                                                                    + "\nhttps://discordapp.com/oauth2/authorize?&client_id=160185389313818624&scope=bot&permissions=355593334");
 }
Example #25
0
 public static EmbedBuilder ErrorEmbedResource(this EventContext e, string resourceId, params object[] args)
 => ErrorEmbed(e, e.GetResource(resourceId, args));
Example #26
0
        public async Task MyPasta(EventContext e)
        {
            int page = 0;

            if (!string.IsNullOrWhiteSpace(e.Arguments.ToString()))
            {
                if (int.TryParse(e.Arguments.FirstOrDefault().Argument, out page))
                {
                    page -= 1;
                }
            }
            long   userId;
            string userName;

            if (e.message.MentionedUserIds.Count() > 0)
            {
                userId   = e.message.MentionedUserIds.First().ToDbLong();
                userName = (await e.Guild.GetUserAsync(userId.FromDbLong())).Username;
            }
            else
            {
                userId   = e.Author.Id.ToDbLong();
                userName = e.Author.Username;
            }

            using (var context = new MikiContext())
            {
                var pastasFound = context.Pastas.Where(x => x.CreatorId == userId)
                                  .OrderByDescending(x => x.Id)
                                  .Skip(page * 25)
                                  .Take(25)
                                  .ToList();

                var totalCount = context.Pastas.Where(x => x.CreatorId == userId)
                                 .Count();

                if (page * 25 > totalCount)
                {
                    e.ErrorEmbed(e.GetResource("pasta_error_out_of_index"))
                    .ToEmbed().QueueToChannel(e.Channel);
                    return;
                }

                if (pastasFound?.Count > 0)
                {
                    string resultString = "";

                    pastasFound.ForEach(x => { resultString += "`" + x.Id + "` "; });

                    Utils.Embed
                    .SetTitle(e.GetResource("mypasta_title", userName))
                    .SetDescription(resultString)
                    .SetFooter(e.GetResource("page_index", page + 1, (Math.Ceiling((double)totalCount / 25)).ToString()), null)
                    .ToEmbed().QueueToChannel(e.Channel);
                    return;
                }

                e.ErrorEmbed(e.GetResource("mypasta_error_no_pastas"))
                .ToEmbed().QueueToChannel(e.Channel);
            }
        }
Example #27
0
        public async Task KickAsync(EventContext e)
        {
            if (e.Guild.CurrentUser.HasPermissions(e.Channel, DiscordGuildPermission.KickMembers))
            {
                List <string> arg = e.arguments.Split(' ').ToList();

                for (int i = 0; i < arg.Count; i++)
                {
                    if (string.IsNullOrWhiteSpace(arg[i]))
                    {
                        arg.RemoveAt(i);
                        i--;
                    }
                }

                IDiscordUser bannedUser = null;
                Locale       locale     = Locale.GetEntity(e.Channel.Id.ToDbLong());

                if (e.message.MentionedUserIds.Count > 0)
                {
                    bannedUser = await e.Guild.GetUserAsync(e.message.MentionedUserIds.First());
                }
                else
                {
                    if (arg.Count > 0)
                    {
                        bannedUser = await e.Guild.GetUserAsync(ulong.Parse(arg[0]));
                    }
                }

                if (bannedUser == null)
                {
                    await e.ErrorEmbed(e.GetResource("ban_error_user_null"))
                    .SendToChannel(e.Channel);

                    return;
                }

                if (bannedUser.Hierarchy >= e.Guild.CurrentUser.Hierarchy)
                {
                    await e.ErrorEmbed(e.GetResource("permission_error_low", "kick"))
                    .SendToChannel(e.Channel);

                    return;
                }

                arg.RemoveAt(0);

                string reason = string.Join(" ", arg);

                IDiscordEmbed embed = Utils.Embed;
                embed.Title       = locale.GetString("miki_module_admin_kick_header");
                embed.Description = locale.GetString("miki_module_admin_kick_description", new object[] { e.Guild.Name });

                if (!string.IsNullOrWhiteSpace(reason))
                {
                    embed.AddInlineField(locale.GetString("miki_module_admin_kick_reason"), reason);
                }

                embed.AddInlineField(locale.GetString("miki_module_admin_kick_by"), e.Author.Username + "#" + e.Author.Discriminator);

                embed.Color = new IA.SDK.Color(1, 1, 0);

                await bannedUser.SendMessage(embed);

                await bannedUser.Kick(reason);
            }
            else
            {
                await e.ErrorEmbed(e.GetResource("permission_needed_error", $"`{e.GetResource("permission_kick_members")}`"))
                .SendToChannel(e.Channel);
            }
        }
Example #28
0
        //[Command(Name = "reportpasta")]
        //public async Task ReportPastaAsync(EventContext e)
        //{
        //	ArgObject arg = e.Arguments.FirstOrDefault();

        //	if(arg == null)
        //	{
        //		// TODO: error message
        //		return;
        //	}

        //	string pastaId = arg.Argument;
        //	arg = arg.Next();

        //	string reason = arg?.TakeUntilEnd()?.Argument ?? "";

        //	if(string.IsNullOrEmpty(reason))
        //	{
        //		// TODO: reason empty error
        //		return;
        //	}

        //	Utils.SuccessEmbed(e.Channel.Id, "Your report has been received!").QueueToChannel(e.Channel);

        //	Utils.Embed.SetAuthor(e.Author.Username, e.Author.GetAvatarUrl(), "")
        //		.SetDescription($"Reported pasta `{pastaId}`.```{reason}```")
        //		.SetColor(255, 0 , 0)
        //		.SetFooter(DateTime.Now.ToString(), "")
        //		.ToEmbed().QueueToChannel(Bot.Instance.Client.GetChannel(PastaReportsChannelId) as IMessageChannel);
        //}

        public async Task FavouritePastaList(EventContext e, bool lovedPastas = true)
        {
            IDiscordUser targetUser   = e.Author;
            float        totalPerPage = 25f;
            int          page         = 0;

            ArgObject arg = e.Arguments.FirstOrDefault();

            if (arg == null)
            {
                // TODO: error no user found
                return;
            }

            IDiscordUser user = await arg.GetUserAsync(e.Guild);

            if (user != null)
            {
                arg = arg.Next();
            }
            else
            {
                user = e.Author;
            }

            page = arg.AsInt() ?? 0;

            using (MikiContext context = new MikiContext())
            {
                long authorId = targetUser.Id.ToDbLong();
                IEnumerable <PastaVote> pastaVotes = context.Votes.Where(x => x.UserId == authorId && x.PositiveVote == lovedPastas);

                int maxPage = (int)Math.Floor(pastaVotes.Count() / totalPerPage);
                page = page > maxPage ? maxPage : page;
                page = page < 0 ? 0 : page;


                if (pastaVotes.Count() <= 0)
                {
                    string loveString  = (lovedPastas ? e.GetResource("miki_module_pasta_loved") : e.GetResource("miki_module_pasta_hated"));
                    string errorString = e.GetResource("miki_module_pasta_favlist_self_none", loveString);
                    if (e.message.MentionedUserIds.Count() >= 1)
                    {
                        errorString = e.GetResource("miki_module_pasta_favlist_mention_none", loveString);
                    }
                    Utils.ErrorEmbed(e, errorString).ToEmbed().QueueToChannel(e.Channel);
                    return;
                }

                EmbedBuilder     embed        = Utils.Embed;
                List <PastaVote> neededPastas = pastaVotes.Skip((int)totalPerPage * page).Take((int)totalPerPage).ToList();

                string resultString = string.Join(" ", neededPastas.Select(x => $"`{x.Id}`"));

                string useName = string.IsNullOrEmpty(targetUser.Username) ? targetUser.Username : targetUser.Username;
                embed.SetTitle($"{(lovedPastas ? e.GetResource("miki_module_pasta_loved_header") : e.GetResource("miki_module_pasta_hated_header"))} - {useName}");
                embed.SetDescription(resultString);
                embed.SetFooter(e.GetResource("page_index", page + 1, Math.Ceiling(pastaVotes.Count() / totalPerPage)), "");

                embed.ToEmbed().QueueToChannel(e.Channel);
            }
        }
Example #29
0
        public async Task SoftbanAsync(EventContext e)
        {
            if (e.Guild.CurrentUser.HasPermissions(e.Channel, DiscordGuildPermission.BanMembers))
            {
                List <string> arg        = e.arguments.Split(' ').ToList();
                IDiscordUser  bannedUser = null;

                if (e.message.MentionedUserIds.Count > 0)
                {
                    bannedUser = await e.Guild.GetUserAsync(e.message.MentionedUserIds.First());
                }
                else
                {
                    if (arg.Count > 0)
                    {
                        bannedUser = await e.Guild.GetUserAsync(ulong.Parse(arg[0]));
                    }
                }

                if (bannedUser == null)
                {
                    await e.ErrorEmbed(e.GetResource("ban_error_user_null"))
                    .SendToChannel(e.Channel);

                    return;
                }

                if (bannedUser.Hierarchy >= e.Guild.CurrentUser.Hierarchy)
                {
                    await e.ErrorEmbed(e.GetResource("permission_error_low", "softban"))
                    .SendToChannel(e.Channel);

                    return;
                }

                arg.RemoveAt(0);

                string reason = string.Join(" ", arg);

                IDiscordEmbed embed = Utils.Embed;
                embed.Title       = "โš  SOFTBAN";
                embed.Description = $"You've been banned from **{e.Guild.Name}**!";

                if (!string.IsNullOrWhiteSpace(reason))
                {
                    embed.AddInlineField("๐Ÿ’ฌ Reason", reason);
                }

                embed.AddInlineField("๐Ÿ’ Banned by", e.Author.Username + "#" + e.Author.Discriminator);

                await bannedUser.SendMessage(embed);

                await bannedUser.Ban(e.Guild, 1, reason);

                await bannedUser.Unban(e.Guild);
            }
            else
            {
                await e.ErrorEmbed(e.GetResource("permission_needed_error", $"`{e.GetResource("permission_ban_members")}`"))
                .SendToChannel(e.Channel);
            }
        }
Example #30
0
 public async Task LunchAsync(EventContext e)
 {
     await e.Channel.SendMessage(e.GetResource("lunch_line") + "\n" + lunchposts[Global.random.Next(0, lunchposts.Length)]);
 }