コード例 #1
0
        public async Task SetCommandAsync(EventContext e)
        {
            Locale locale = new Locale(e.Channel.Id);

            string[] arguments = e.arguments.Split(' ');
            IEvent   command   = e.EventSystem.CommandHandler.GetCommandEvent(arguments[0]);

            if (command == null)
            {
                e.ErrorEmbed($"{arguments[0]} is not a valid command")
                .QueueToChannel(e.Channel);
                return;
            }

            bool setValue = arguments[1].ToBool();

            if (!command.CanBeDisabled)
            {
                e.ErrorEmbed(locale.GetString("miki_admin_cannot_disable", $"`{arguments[0]}`"))
                .QueueToChannel(e.Channel);
                return;
            }

            if (arguments.Length > 2)
            {
                if (arguments.Contains("-s"))
                {
                }
            }
            await command.SetEnabled(e.Channel.Id, setValue);

            Utils.SuccessEmbed(locale, ((setValue) ? locale.GetString("miki_generic_enabled") : locale.GetString("miki_generic_disabled")) + $" {command.Name}")
            .QueueToChannel(e.Channel);
        }
コード例 #2
0
        public async Task IAmNotAsync(EventContext e)
        {
            IDiscordRole role = GetRoleByName(e.Guild, e.arguments);

            if (role == null)
            {
                await e.ErrorEmbed(e.Channel.GetLocale().GetString("error_role_null"))
                .SendToChannel(e.Channel);

                return;
            }

            if (!e.Author.RoleIds.Contains(role.Id))
            {
                await e.ErrorEmbed(e.Channel.GetLocale().GetString("error_role_forbidden"))
                .SendToChannel(e.Channel);

                return;
            }

            using (var context = new MikiContext())
            {
                LevelRole newRole = await context.LevelRoles.FindAsync(e.Guild.Id.ToDbLong(), role.Id.ToDbLong());

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

                await e.Author.RemoveRoleAsync(newRole.Role);

                Utils.Embed.SetTitle("I AM NOT")
                .SetColor(255, 128, 128)
                .SetDescription($"You're no longer a(n) {role.Name}!")
                .QueueToChannel(e.Channel);
            }
        }
コード例 #3
0
ファイル: PastaModule.cs プロジェクト: SnipeFrost/Miki
        public async Task GetPasta(EventContext e)
        {
            Locale locale = new Locale(e.Channel.Id);

            if (string.IsNullOrWhiteSpace(e.arguments))
            {
                e.ErrorEmbed(e.GetResource("pasta_error_no_arg")).QueueToChannel(e.Channel);
                return;
            }

            List <string> arguments = e.arguments.Split(' ').ToList();

            using (var context = new MikiContext())
            {
                GlobalPasta pasta = await context.Pastas.FindAsync(arguments[0]);

                if (pasta == null)
                {
                    e.ErrorEmbed(e.GetResource("miki_module_pasta_search_error_no_results", e.arguments)).QueueToChannel(e.Channel);
                    return;
                }
                pasta.TimesUsed++;
                e.Channel.QueueMessageAsync(pasta.Text);
                await context.SaveChangesAsync();
            }
        }
コード例 #4
0
        public async Task GetPasta(EventContext e)
        {
            if (string.IsNullOrWhiteSpace(e.Arguments.ToString()))
            {
                await e.ErrorEmbed(e.Locale.GetString("pasta_error_no_arg")).ToEmbed().QueueToChannelAsync(e.Channel);

                return;
            }

            using (var context = new MikiContext())
            {
                GlobalPasta pasta = await context.Pastas.FindAsync(e.Arguments.ToString());

                if (pasta == null)
                {
                    await e.ErrorEmbed(e.Locale.GetString("miki_module_pasta_search_error_no_results", e.Arguments.ToString()))
                    .ToEmbed().QueueToChannelAsync(e.Channel);

                    return;
                }
                pasta.TimesUsed++;

                var sanitizedText = Utils.EscapeEveryone(pasta.Text);
                e.Channel.QueueMessage(sanitizedText);
                await context.SaveChangesAsync();
            }
        }
コード例 #5
0
        public async Task IAmNotAsync(EventContext e)
        {
            string roleName = e.Arguments.ToString();

            using (var context = new MikiContext())
            {
                List <IDiscordRole> roles = await GetRolesByName(e.Guild, roleName);

                IDiscordRole role = null;

                if (roles.Count > 1)
                {
                    List <LevelRole> levelRoles = await context.LevelRoles.Where(x => x.GuildId == (long)e.Guild.Id).ToListAsync();

                    if (levelRoles.Where(x => x.Role.Name.ToLower() == roleName.ToLower()).Count() > 1)
                    {
                        e.ErrorEmbed("two roles configured have the same name.")
                        .ToEmbed().QueueToChannel(e.Channel);
                        return;
                    }
                    else
                    {
                        role = levelRoles.Where(x => x.Role.Name.ToLower() == roleName.ToLower()).FirstOrDefault().Role;
                    }
                }
                else
                {
                    role = roles.FirstOrDefault();
                }

                if (role == null)
                {
                    await e.ErrorEmbed(e.GetResource("error_role_null"))
                    .ToEmbed().SendToChannel(e.Channel);

                    return;
                }

                IDiscordGuildUser author = await e.Guild.GetUserAsync(e.Author.Id);

                if (!author.RoleIds.Contains(role.Id))
                {
                    await e.ErrorEmbed(e.GetResource("error_role_forbidden"))
                    .ToEmbed().SendToChannel(e.Channel);

                    return;
                }

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

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

                await author.RemoveRoleAsync(newRole.Role);

                Utils.Embed.SetTitle("I AM NOT")
                .SetColor(255, 128, 128)
                .SetDescription($"You're no longer a(n) {role.Name}!")
                .ToEmbed().QueueToChannel(e.Channel);
            }
        }
コード例 #6
0
        public async Task EditPasta(EventContext e)
        {
            if (e.Arguments.Pack.Length < 2)
            {
                await e.ErrorEmbed(e.Locale.GetString("miki_module_pasta_error_specify", e.Locale.GetString("miki_module_pasta_error_specify_edit")))
                .ToEmbed().QueueToChannelAsync(e.Channel);

                return;
            }

            using (var context = new MikiContext())
            {
                e.Arguments.Take(out string tag);

                GlobalPasta p = await context.Pastas.FindAsync(tag);

                if (p.CreatorId == e.Author.Id.ToDbLong())
                {
                    p.Text = e.Arguments.Pack.TakeAll();
                    await context.SaveChangesAsync();

                    await e.SuccessEmbed($"Edited `{tag}`!")
                    .QueueToChannelAsync(e.Channel);
                }
                else
                {
                    await e.ErrorEmbed($"You cannot edit pastas you did not create. Baka!")
                    .ToEmbed().QueueToChannelAsync(e.Channel);
                }
            }
        }
コード例 #7
0
        public async Task ShowMekosAsync(EventContext e)
        {
            ulong targetId = e.message.MentionedUserIds.Count > 0 ? e.message.MentionedUserIds.First() : 0;

            if (e.message.MentionedUserIds.Count > 0)
            {
                if (targetId == 0)
                {
                    await e.ErrorEmbed(e.GetResource("miki_module_accounts_mekos_no_user")).SendToChannel(e.Channel);

                    return;
                }
                IDiscordUser userCheck = await e.Guild.GetUserAsync(targetId);

                if (userCheck.IsBot)
                {
                    await e.ErrorEmbed(e.GetResource("miki_module_accounts_mekos_bot")).SendToChannel(e.Channel);

                    return;
                }
            }

            using (var context = new MikiContext())
            {
                User user = await context.Users.FindAsync(targetId != 0?(long)targetId : e.Author.Id.ToDbLong());

                IDiscordEmbed embed = new RuntimeEmbed(new EmbedBuilder());
                embed.Title       = "🔸 Mekos";
                embed.Description = e.GetResource("miki_user_mekos", user.Name, user.Currency);
                embed.Color       = new IA.SDK.Color(1f, 0.5f, 0.7f);

                await embed.SendToChannel(e.Channel);
            }
        }
コード例 #8
0
        public async Task SetModuleAsync(EventContext e)
        {
            var cache = (ICacheClient)e.Services.GetService(typeof(ICacheClient));

            if (e.Arguments.Take(out string moduleName))
            {
                return;
            }

            Module m = e.EventSystem.GetCommandHandler <SimpleCommandHandler>().Modules.FirstOrDefault(x => x.Name == moduleName);

            if (m == null)
            {
                await e.ErrorEmbed($"{moduleName} is not a valid module.")
                .ToEmbed().QueueToChannelAsync(e.Channel);

                return;
            }

            if (e.Arguments.Take(out bool setValue))
            {
                if (!m.CanBeDisabled && !setValue)
                {
                    await e.ErrorEmbed(e.Locale.GetString("miki_admin_cannot_disable", $"`{moduleName}`"))
                    .ToEmbed().QueueToChannelAsync(e.Channel);

                    return;
                }
            }

            await m.SetEnabled(cache, e.Guild.Id, setValue);

            await e.SuccessEmbed((setValue ? e.Locale.GetString("miki_generic_enabled") : e.Locale.GetString("miki_generic_disabled")) + $" {m.Name}")
            .QueueToChannelAsync(e.Channel);
        }
コード例 #9
0
ファイル: AccountsModule.cs プロジェクト: MrDurank/Miki
        public async Task GetDailyAsync(EventContext e)
        {
            using (var context = new MikiContext())
            {
                Locale locale = new Locale(e.Channel.Id);

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

                if (u == null)
                {
                    e.ErrorEmbed(e.GetResource("user_error_no_account"))
                    .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.GetLocale())}` before using it again.").QueueToChannel(e.Channel);
                    return;
                }

                int    streak   = 1;
                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;


                Utils.Embed.SetTitle("💰 Daily")
                .SetDescription($"Received **{amount}** Mekos! You now have `{u.Currency}` Mekos")
                .SetColor(253, 216, 136)
                .AddInlineField("Streak!", $"You're on a {streak} day daily streak!")
                .QueueToChannel(e.Channel);

                await Global.redisClient.AddAsync(redisKey, streak, new TimeSpan(48, 0, 0));

                await context.SaveChangesAsync();
            }
        }
コード例 #10
0
ファイル: AdminModule.cs プロジェクト: mugSans/Miki
        public async Task KickAsync(EventContext e)
        {
            IGuildUser currentUser = await e.Guild.GetCurrentUserAsync();

            ArgObject arg = e.Arguments.FirstOrDefault();

            if (currentUser.GuildPermissions.Has(GuildPermission.KickMembers))
            {
                IGuildUser bannedUser = null;
                bannedUser = await arg?.GetUserAsync(e.Guild) ?? null;

                if (bannedUser == null)
                {
                    e.ErrorEmbed(e.GetResource("ban_error_user_null"))
                    .Build().QueueToChannel(e.Channel);
                    return;
                }

                if ((bannedUser as SocketGuildUser).Hierarchy >= (e.Author as SocketGuildUser).Hierarchy)
                {
                    e.ErrorEmbed(e.GetResource("permission_error_low", "kick")).Build()
                    .QueueToChannel(e.Channel);
                    return;
                }

                if ((bannedUser as SocketGuildUser).Hierarchy >= (currentUser as SocketGuildUser).Hierarchy)
                {
                    e.ErrorEmbed(e.GetResource("permission_error_low", "kick")).Build()
                    .QueueToChannel(e.Channel);
                    return;
                }

                arg = arg.Next();

                string reason = arg.TakeUntilEnd().Argument;

                EmbedBuilder embed = new EmbedBuilder();
                embed.Title       = e.GetResource("miki_module_admin_kick_header");
                embed.Description = e.GetResource("miki_module_admin_kick_description", new object[] { 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);

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

                await embed.Build().SendToUser(bannedUser);

                await bannedUser.KickAsync(reason);
            }
            else
            {
                e.ErrorEmbed(e.GetResource("permission_needed_error", $"`{e.GetResource("permission_kick_members")}`"))
                .Build().QueueToChannel(e.Channel);
            }
        }
コード例 #11
0
        public async Task MyPasta(EventContext e)
        {
            if (e.Arguments.Take(out int page))
            {
                page--;
            }

            long   userId;
            string userName;

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

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

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

                if (page * 25 > totalCount)
                {
                    await e.ErrorEmbed(e.Locale.GetString("pasta_error_out_of_index"))
                    .ToEmbed().QueueToChannelAsync(e.Channel);

                    return;
                }

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

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

                    await new EmbedBuilder()
                    .SetTitle(e.Locale.GetString("mypasta_title", userName))
                    .SetDescription(resultString)
                    .SetFooter(e.Locale.GetString("page_index", page + 1, (Math.Ceiling((double)totalCount / 25)).ToString()), null)
                    .ToEmbed().QueueToChannelAsync(e.Channel);
                    return;
                }

                await e.ErrorEmbed(e.Locale.GetString("mypasta_error_no_pastas"))
                .ToEmbed().QueueToChannelAsync(e.Channel);
            }
        }
コード例 #12
0
        //[Command(Name = "lottery")]
        //public async Task LotteryAsync(EventContext e)
        //{
        //	ArgObject arg = e.Arguments.FirstOrDefault();

        //	if (arg == null)
        //	{
        //		long totalTickets = await (Global.RedisClient as StackExchangeCacheClient).Client.GetDatabase(0).ListLengthAsync(lotteryKey);
        //		long yourTickets = 0;

        //		string latestWinner = (Global.RedisClient as StackExchangeCacheClient).Client.GetDatabase(0).StringGet("lottery:winner");

        //		if (await lotteryDict.ContainsAsync(e.Author.Id))
        //		{
        //			yourTickets = long.Parse(await lotteryDict.GetAsync(e.Author.Id));
        //		}

        //		string timeLeft = taskScheduler?.GetInstance(0, lotteryId).TimeLeft.ToTimeString(e.Locale, true) ?? "1h?m?s - will be fixed soon!";

        //		new EmbedBuilder()
        //		{
        //			Title = "🍀 Lottery",
        //			Description = "Make the biggest gamble, and get paid off massively if legit.",
        //			Color = new Color(119, 178, 85)
        //		}.AddInlineField("Tickets Owned", yourTickets.ToString())
        //		.AddInlineField("Drawing In", timeLeft)
        //		.AddInlineField("Total Tickets", totalTickets.ToString())
        //		.AddInlineField("Ticket price", $"{100} mekos")
        //		.AddInlineField("Latest Winner", latestWinner ?? "no name")
        //		.AddInlineField("How to buy?", ">lottery buy [amount]")
        //		.ToEmbed().QueueToChannelAsync(e.Channel);
        //		return;
        //	}

        //	switch (arg.Argument.ToLower())
        //	{
        //		case "buy":
        //		{
        //			arg = arg.Next();
        //			int amount = arg?.AsInt() ?? 1;

        //			if (amount < 1)
        //				amount = 1;

        //			using (var context = new MikiContext())
        //			{
        //				User u = await DatabaseHelpers.GetUserAsync(context, e.Author);

        //				if (amount * 100 > u.Currency)
        //				{
        //					e.ErrorEmbedResource("miki_mekos_insufficient")
        //						.ToEmbed().QueueToChannelAsync(e.Channel);
        //					return;
        //				}

        //				await u.AddCurrencyAsync(-amount * 100, e.Channel);

        //				RedisValue[] tickets = new RedisValue[amount];

        //				for (int i = 0; i < amount; i++)
        //				{
        //					tickets[i] = e.Author.Id.ToString();
        //				}

        //				await (Global.RedisClient as StackExchangeCacheClient).Client.GetDatabase(0).ListRightPushAsync(lotteryKey, tickets);

        //				int totalTickets = 0;

        //				if (await lotteryDict.ContainsAsync(e.Author.Id.ToString()))
        //				{
        //					totalTickets = int.Parse(await lotteryDict.GetAsync(e.Author.Id.ToString()));
        //				}

        //				await lotteryDict.AddAsync(e.Author.Id, amount + totalTickets);

        //				await context.SaveChangesAsync();

        //				e.SuccessEmbed($"Successfully bought {amount} tickets!")
        //					.QueueToChannelAsync(e.Channel);
        //			}
        //		}
        //		break;
        //	}
        //}

        public async Task <int?> ValidateBetAsync(EventContext e, int maxBet = 1000000)
        {
            if (e.Arguments.Take(out string arg))
            {
                using (MikiContext context = new MikiContext())
                {
                    User user = await context.Users.FindAsync(e.Author.Id.ToDbLong());

                    if (user == null)
                    {
                        throw new UserNullException();
                    }

                    if (int.TryParse(arg, out int bet))
                    {
                    }
                    else if (arg.ToLower() == "all" || arg == "*")
                    {
                        bet = Math.Min(user.Currency, maxBet);
                    }
                    else
                    {
                        await e.ErrorEmbed(e.Locale.GetString("miki_error_gambling_parse_error"))
                        .ToEmbed().QueueToChannelAsync(e.Channel);

                        return(null);
                    }

                    if (bet < 1)
                    {
                        throw new ArgumentLessThanZeroException();
                    }

                    if (bet > user.Currency)
                    {
                        throw new InsufficientCurrencyException(user.Currency, bet);
                    }

                    if (bet > maxBet)
                    {
                        await e.ErrorEmbed($"you cannot bet more than {maxBet:n0} mekos!")
                        .ToEmbed().QueueToChannelAsync(e.Channel);

                        return(null);
                    }

                    return(bet);
                }
            }
            else
            {
                await e.ErrorEmbed(e.Locale.GetString("miki_error_gambling_no_arg"))
                .ToEmbed().QueueToChannelAsync(e.Channel);

                return(null);
            }
        }
コード例 #13
0
        public async Task GuildNewRival(EventContext e)
        {
            using (MikiContext context = new MikiContext())
            {
                GuildUser thisGuild = await context.GuildUsers.FindAsync(e.Guild.Id.ToDbLong());

                if (thisGuild == null)
                {
                    await e.ErrorEmbed(e.Locale.GetString("guild_error_null"))
                    .ToEmbed().QueueToChannelAsync(e.Channel);

                    return;
                }

                if (thisGuild.UserCount == 0)
                {
                    thisGuild.UserCount = e.Guild.MemberCount;
                }

                if (thisGuild.LastRivalRenewed.AddDays(1) > DateTime.Now)
                {
                    await new EmbedBuilder()
                    .SetTitle(e.Locale.GetString("miki_terms_rival"))
                    .SetDescription(e.Locale.GetString("guildnewrival_error_timer_running"))
                    .ToEmbed().QueueToChannelAsync(e.Channel);
                    return;
                }

                List <GuildUser> rivalGuilds = await context.GuildUsers
                                               .Where((g) => Math.Abs(g.UserCount - e.Guild.MemberCount) < (g.UserCount * 0.25) && g.RivalId == 0 && g.Id != thisGuild.Id)
                                               .ToListAsync();

                if (rivalGuilds.Count == 0)
                {
                    await e.ErrorEmbed(e.Locale.GetString("guildnewrival_error_matchmaking_failed"))
                    .ToEmbed().QueueToChannelAsync(e.Channel);

                    return;
                }

                int random = MikiRandom.Next(0, rivalGuilds.Count);

                GuildUser rivalGuild = await context.GuildUsers.FindAsync(rivalGuilds[random].Id);

                thisGuild.RivalId  = rivalGuild.Id;
                rivalGuild.RivalId = thisGuild.Id;

                thisGuild.LastRivalRenewed = DateTime.Now;

                await context.SaveChangesAsync();

                await new EmbedBuilder()
                .SetTitle(e.Locale.GetString("miki_terms_rival"))
                .SetDescription(e.Locale.GetString("guildnewrival_success", rivalGuild.Name))
                .ToEmbed().QueueToChannelAsync(e.Channel);
            }
        }
コード例 #14
0
ファイル: FunModule.cs プロジェクト: Xetera/Miki.Bot
        private Task PlaceReminderAsync(EventContext e)
        {
            string args = e.Arguments.Join().Argument;

            int inIndex    = args.ToLower().LastIndexOf(" in ");
            int everyIndex = args.ToLower().LastIndexOf(" every ");

            // TODO: still a bit hacky
            bool isIn     = (inIndex > everyIndex);
            bool repeated = false;

            int splitIndex = isIn ? inIndex : everyIndex;

            if (splitIndex == -1)
            {
                e.ErrorEmbed(e.Locale.GetString("error_argument_null", "time"))
                .ToEmbed().QueueToChannel(e.Channel);
                return(Task.CompletedTask);
            }

            if (!isIn)
            {
                repeated = true;
            }

            string reminderText = new string(args
                                             .Take(splitIndex)
                                             .ToArray()
                                             );

            TimeSpan timeUntilReminder = args.GetTimeFromString();

            if (timeUntilReminder > new TimeSpan(0, 10, 0))
            {
                int id = reminders.AddTask(e.Author.Id, (context) =>
                {
                    new EmbedBuilder()
                    .SetTitle("⏰ Reminder")
                    .SetDescription(new MessageBuilder()
                                    .AppendText(context)
                                    .BuildWithBlockCode())
                    .ToEmbed().QueueToChannel(e.Author.GetDMChannelAsync().Result);
                }, reminderText, timeUntilReminder, repeated);

                new EmbedBuilder()
                .SetTitle($"👌 {e.Locale.GetString("term_ok")}")
                .SetDescription($"I'll remind you to **{reminderText}** {(repeated ? "every" : "in")} **{timeUntilReminder.ToTimeString(e.Locale)}**\nYour reminder code is `{id}`")
                .SetColor(255, 220, 93)
                .ToEmbed().QueueToChannel(e.Channel);
            }
            else
            {
                e.ErrorEmbed("Sorry, but I can only remind you something after 10 minutes.")
                .ToEmbed().QueueToChannel(e.Channel);
            }
            return(Task.CompletedTask);
        }
コード例 #15
0
ファイル: PastaModule.cs プロジェクト: SnipeFrost/Miki
        public async Task SearchPasta(EventContext e)
        {
            Locale locale = new Locale(e.Channel.Id);

            if (string.IsNullOrWhiteSpace(e.arguments))
            {
                e.ErrorEmbed(e.GetResource("searchpasta_error_no_arg"))
                .QueueToChannel(e.Channel.Id);
                return;
            }

            List <string> arguments = e.arguments.Split(' ').ToList();
            int           page      = 0;

            if (arguments.Count > 1)
            {
                if (int.TryParse(arguments[arguments.Count - 1], out page))
                {
                    page -= 1;
                }
            }

            string query = arguments[0];

            using (var context = new MikiContext())
            {
                var pastasFound = await context.Pastas.Where(x => x.Id.ToLower().Contains(query.ToLower()))
                                  .OrderByDescending(x => x.Id)
                                  .Skip(25 * page)
                                  .Take(25)
                                  .ToListAsync();


                var totalCount = await context.Pastas.Where(x => x.Id.Contains(query))
                                 .CountAsync();

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

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

                    IDiscordEmbed embed = Utils.Embed;
                    embed.Title       = e.GetResource("miki_module_pasta_search_header");
                    embed.Description = resultString;
                    embed.CreateFooter();
                    embed.Footer.Text = e.GetResource("page_index", page + 1, (Math.Ceiling((double)totalCount / 25)).ToString());

                    embed.QueueToChannel(e.Channel);
                    return;
                }

                e.ErrorEmbed(e.GetResource("miki_module_pasta_search_error_no_results", arguments[0]))
                .QueueToChannel(e.Channel);
            }
        }
コード例 #16
0
ファイル: AdminModule.cs プロジェクト: NobelColt/Miki.Bot
        public async Task SetCommandAsync(EventContext e)
        {
            ArgObject arg = e.Arguments.FirstOrDefault();

            if (arg == null)
            {
                return;
            }

            string commandId = arg.Argument;

            Event command = e.EventSystem.GetCommandHandler <SimpleCommandHandler>().Commands.FirstOrDefault(x => x.Name == commandId);

            if (command == null)
            {
                e.ErrorEmbed($"{commandId} is not a valid command")
                .ToEmbed().QueueToChannel(e.Channel);
                return;
            }

            arg = arg.Next();

            bool?setValue = arg.AsBoolean();

            if (!setValue.HasValue)
            {
                setValue = arg.Argument.ToLower() == "yes" || arg.Argument == "1";
            }

            if (!command.CanBeDisabled)
            {
                e.ErrorEmbed(e.Locale.GetString("miki_admin_cannot_disable", $"`{commandId}`"))
                .ToEmbed().QueueToChannel(e.Channel);
                return;
            }

            arg = arg?.Next();

            if (arg != null)
            {
                if (arg.Argument == "-s")
                {
                    // TODO: serverwide disable/enable
                }
            }

            using (var context = new MikiContext())
            {
                await command.SetEnabled(context, Global.RedisClient, e.Channel.Id, setValue ?? false);
            }
            e.SuccessEmbed(((setValue ?? false) ? e.Locale.GetString("miki_generic_enabled") : e.Locale.GetString("miki_generic_disabled")) + $" {command.Name}")
            .QueueToChannel(e.Channel);
        }
コード例 #17
0
ファイル: GuildAccountsModule.cs プロジェクト: Beaend/Miki
        public async Task GuildNewRival(EventContext context)
        {
            using (MikiContext db = new MikiContext())
            {
                GuildUser thisGuild = await db.GuildUsers.FindAsync(context.Guild.Id.ToDbLong());

                if (thisGuild == null)
                {
                    await context.ErrorEmbed(context.GetResource("guild_error_null"))
                    .SendToChannel(context.Channel);

                    return;
                }

                if (thisGuild.LastRivalRenewed.AddDays(1) > DateTime.Now)
                {
                    await Utils.Embed
                    .SetTitle(context.GetResource("miki_terms_rival"))
                    .SetDescription(context.GetResource("guildnewrival_error_timer_running"))
                    .SendToChannel(context.Channel);

                    return;
                }

                List <GuildUser> rivalGuilds = await db.GuildUsers
                                               .Where((g) => Math.Abs(g.UserCount - thisGuild.UserCount) < (g.UserCount / 4) && g.RivalId == 0 && g.Id != thisGuild.Id)
                                               .ToListAsync();

                if (rivalGuilds.Count == 0)
                {
                    await context.ErrorEmbed(context.GetResource("guildnewrival_error_matchmaking_failed"))
                    .SendToChannel(context.Channel);

                    return;
                }

                int random = MikiRandom.Next(0, rivalGuilds.Count);

                GuildUser rivalGuild = await db.GuildUsers.FindAsync(rivalGuilds[random].Id);

                thisGuild.RivalId  = rivalGuild.Id;
                rivalGuild.RivalId = thisGuild.Id;

                thisGuild.LastRivalRenewed = DateTime.Now;

                await db.SaveChangesAsync();

                await Utils.Embed
                .SetTitle(context.GetResource("miki_terms_rival"))
                .SetDescription(context.GetResource("guildnewrival_success", rivalGuild.Name))
                .SendToChannel(context.Channel);
            }
        }
コード例 #18
0
        public async Task SetModuleAsync(EventContext e)
        {
            ArgObject arg = e.Arguments.FirstOrDefault();

            if (arg == null)
            {
                return;
            }

            string moduleName = arg.Argument;

            Module m = e.EventSystem.GetCommandHandler <SimpleCommandHandler>().Modules.FirstOrDefault(x => x.Name == moduleName);


            if (m == null)
            {
                e.ErrorEmbed($"{arg.Argument} is not a valid module.")
                .ToEmbed().QueueToChannel(e.Channel);
                return;
            }

            arg = arg?.Next();

            bool?setValue = arg.AsBoolean();

            if (!setValue.HasValue)
            {
                setValue = arg.Argument.ToLower() == "yes" || arg.Argument == "1";
            }

            if (!m.CanBeDisabled && !setValue.Value)
            {
                e.ErrorEmbed(e.GetResource("miki_admin_cannot_disable", $"`{moduleName}`"))
                .ToEmbed().QueueToChannel(e.Channel);
                return;
            }

            arg = arg?.Next();

            if (arg != null)
            {
                if (arg.Argument == "-s")
                {
                    // TODO: serverwide disable/enable
                }
            }

            await m.SetEnabled(Global.RedisClient, e.Channel.Id, (setValue ?? false));

            Utils.SuccessEmbed(e.Channel.Id, ((setValue ?? false) ? e.GetResource("miki_generic_enabled") : e.GetResource("miki_generic_disabled")) + $" {m.Name}")
            .QueueToChannel(e.Channel);
        }
コード例 #19
0
ファイル: AnimeModule.cs プロジェクト: Xetera/Miki.Bot
        public async Task FindCharacterAsync(EventContext e)
        {
            ArgObject arg = e.Arguments.FirstOrDefault();

            if (arg == null)
            {
                return;
            }

            int page = 0;

            if (e.Arguments.LastOrDefault()?.TakeInt() != null)
            {
                page = e.Arguments.LastOrDefault().TakeInt().Value;
            }

            arg = arg.TakeUntilEnd((page != 0) ? 1 : 0);
            string searchQuery = arg.Argument;

            arg = arg.Next();

            ISearchResult <ICharacterSearchResult> result = (await anilistClient.SearchCharactersAsync(searchQuery, page));

            if (result.Items.Count == 0)
            {
                if (page > result.PageInfo.TotalPages && page != 0)
                {
                    e.ErrorEmbed($"You've exceeded the total amount of pages available, might want to move back a bit!")
                    .ToEmbed().QueueToChannel(e.Channel);
                }
                else
                {
                    e.ErrorEmbed($"No characters listed containing `{e.Arguments.ToString()}`, try something else!")
                    .ToEmbed().QueueToChannel(e.Channel);
                }
                return;
            }

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < result.Items.Count; i++)
            {
                sb.AppendLine($"`{result.Items[i].Id.ToString().PadRight(5)}:` {result.Items[i].FirstName} {result.Items[i].LastName}");
            }

            new EmbedBuilder()
            .SetAuthor($"Search result for `{searchQuery}`", "https://anilist.co/img/logo_al.png", "")
            .SetDescription(sb.ToString())
            .SetColor(0, 170, 255)
            .SetFooter($"Page {result.PageInfo.CurrentPage} of {result.PageInfo.TotalPages} | Powered by anilist.co", "")
            .ToEmbed().QueueToChannel(e.Channel);
        }
コード例 #20
0
ファイル: AnimeModule.cs プロジェクト: ShanuMaurya/Miki
        public async Task FindMangaAsync(EventContext e)
        {
            ArgObject arg = e.Arguments.FirstOrDefault();

            if (arg == null)
            {
                return;
            }

            int page = 0;

            if (e.Arguments.LastOrDefault()?.AsInt() != null)
            {
                page = e.Arguments.LastOrDefault().AsInt().Value;
            }

            arg = arg.TakeUntilEnd((page != 0) ? 1 : 0);
            string searchQuery = arg.Argument;

            arg = arg.Next();

            ISearchResult <IMediaSearchResult> result = (await anilistClient.SearchMediaAsync(searchQuery, page, (e.Channel as ITextChannel).IsNsfw, MediaFormat.MUSIC, MediaFormat.ONA, MediaFormat.ONE_SHOT, MediaFormat.OVA, MediaFormat.SPECIAL, MediaFormat.TV, MediaFormat.TV_SHORT));

            if (result.Items.Count == 0)
            {
                if (page > result.PageInfo.TotalPages && page != 0)
                {
                    e.ErrorEmbed($"You've exceeded the total amount of pages available, might want to move back a bit!")
                    .Build().QueueToChannel(e.Channel);
                }
                else
                {
                    e.ErrorEmbed($"No characters listed containing `{e.Arguments.ToString()}`, try something else!")
                    .Build().QueueToChannel(e.Channel);
                }
                return;
            }

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < result.Items.Count; i++)
            {
                sb.AppendLine($"`{result.Items[i].Id.ToString().PadRight(5)}:` {result.Items[i].DefaultTitle}");
            }

            Utils.Embed.SetAuthor($"Search result for `{searchQuery}`", "https://anilist.co/img/logo_al.png", "")
            .WithDescription(sb.ToString())
            .WithColor(0, 170, 255)
            .WithFooter($"Page {result.PageInfo.CurrentPage} of {result.PageInfo.TotalPages} | Powered by anilist.co", "")
            .Build().QueueToChannel(e.Channel);
        }
コード例 #21
0
ファイル: PastaModule.cs プロジェクト: mugSans/Miki
        public async Task SearchPasta(EventContext e)
        {
            ArgObject arg = e.Arguments.FirstOrDefault();

            if (arg == null)
            {
                e.ErrorEmbed(e.GetResource("searchpasta_error_no_arg"))
                .Build().QueueToChannel(e.Channel);
                return;
            }

            string query = arg.Argument;

            arg = arg.Next();

            int page = (arg?.AsInt() ?? 0);

            using (var context = new MikiContext())
            {
                var pastasFound = await context.Pastas.Where(x => x.Id.ToLower().Contains(query.ToLower()))
                                  .OrderByDescending(x => x.Id)
                                  .Skip(25 * page)
                                  .Take(25)
                                  .ToListAsync();


                var totalCount = await context.Pastas.Where(x => x.Id.Contains(query))
                                 .CountAsync();

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

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

                    EmbedBuilder embed = Utils.Embed;
                    embed.Title       = e.GetResource("miki_module_pasta_search_header");
                    embed.Description = resultString;

                    embed.WithFooter(e.GetResource("page_index", page + 1, (Math.Ceiling((double)totalCount / 25)).ToString()));

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

                e.ErrorEmbed(e.GetResource("miki_module_pasta_search_error_no_results", query))
                .Build().QueueToChannel(e.Channel);
            }
        }
コード例 #22
0
        private async Task CancelReminderAsync(EventContext e)
        {
            if (e.Arguments.Take(out string arg))
            {
                if (Utils.IsAll(arg))
                {
                    if (reminders.GetAllInstances(e.Author.Id) is List <TaskInstance <string> > instances)
                    {
                        instances.ForEach(i => i.Cancel());
                    }

                    await new EmbedBuilder()
                    .SetTitle($"⏰ {e.Locale.GetString("reminders")}")
                    .SetColor(0.86f, 0.18f, 0.26f)
                    .SetDescription(e.Locale.GetString("reminder_cancelled_all"))
                    .ToEmbed().QueueToChannelAsync(e.Channel);
                    return;
                }
            }
            else if (e.Arguments.Take(out int id))
            {
                if (reminders.CancelReminder(e.Author.Id, id) is TaskInstance <string> i)
                {
                    await new EmbedBuilder()
                    .SetTitle($"⏰ {e.Locale.GetString("reminders")}")
                    .SetColor(0.86f, 0.18f, 0.26f)
                    .SetDescription(e.Locale.GetString("reminder_cancelled", $"`{i.Context}`"))
                    .ToEmbed().QueueToChannelAsync(e.Channel);
                    return;
                }
            }
            await e.ErrorEmbed(e.Locale.GetString("error_reminder_null"))
            .ToEmbed().QueueToChannelAsync(e.Channel);
        }
コード例 #23
0
        public async Task CreatePasta(EventContext e)
        {
            if (e.Arguments.Pack.Length < 2)
            {
                await e.ErrorEmbed(e.Locale.GetString("createpasta_error_no_content"))
                .ToEmbed().QueueToChannelAsync(e.Channel);

                return;
            }

            e.Arguments.Take(out string id);
            string text = e.Arguments.Pack.TakeAll();

            if (Regex.IsMatch(text, "(http[s]://)?((discord.gg)|(discordapp.com/invite))/([A-Za-z0-9]+)", RegexOptions.IgnoreCase))
            {
                throw new PastaInviteException();
            }

            using (var context = new MikiContext())
            {
                await GlobalPasta.AddAsync(context, id, text, (long)e.Author.Id);

                await context.SaveChangesAsync();
            }

            await e.SuccessEmbed(e.Locale.GetString("miki_module_pasta_create_success", id))
            .QueueToChannelAsync(e.Channel);
        }
コード例 #24
0
ファイル: PastaModule.cs プロジェクト: hlinkad/Miki
        public async Task CreatePasta(EventContext e)
        {
            if (e.Arguments.Count < 2)
            {
                e.ErrorEmbed(e.GetResource("createpasta_error_no_content"))
                .ToEmbed().QueueToChannel(e.Channel);
                return;
            }

            ArgObject arg = e.Arguments.FirstOrDefault();

            string id = arg.Argument;

            arg = arg.Next();
            string text = arg.TakeUntilEnd().Argument;

            using (var context = new MikiContext())
            {
                await GlobalPasta.AddAsync(context, id, text, (long)e.Author.Id);

                await context.SaveChangesAsync();
            }

            Utils.SuccessEmbed(e.Channel.Id, e.GetResource("miki_module_pasta_create_success", id))
            .QueueToChannel(e.Channel);
        }
コード例 #25
0
ファイル: PastaModule.cs プロジェクト: mugSans/Miki
        public async Task EditPasta(EventContext e)
        {
            if (e.Arguments.Count < 2)
            {
                e.ErrorEmbed(e.GetResource("miki_module_pasta_error_specify", e.GetResource("miki_module_pasta_error_specify_edit")))
                .Build().QueueToChannel(e.Channel);
                return;
            }

            using (var context = new MikiContext())
            {
                ArgObject arg = e.Arguments.FirstOrDefault();

                string tag = arg.Argument;
                arg = arg.Next();

                GlobalPasta p = await context.Pastas.FindAsync(tag);

                if (p.CreatorId == e.Author.Id.ToDbLong())
                {
                    p.Text = arg.TakeUntilEnd().Argument;
                    await context.SaveChangesAsync();

                    e.Channel.QueueMessageAsync($"Edited `{tag}`!");
                }
                else
                {
                    e.Channel.QueueMessageAsync($@"You cannot edit pastas you did not create. Baka!");
                }
            }
        }
コード例 #26
0
        // TODO: change name of method to fit better to what the method does.
        public async Task ValidateGlitch(EventContext e, Func <EventContext, int, Task> callback, int bet)
        {
            using (var context = new MikiContext())
            {
                User u = await context.Users.FindAsync(e.Author.Id.ToDbLong());

                e.EventSystem.GetCommandHandler <SessionBasedCommandHandler>()
                .RemoveSession(e.Author.Id, e.Channel.Id);

                //if ((await e.Guild.GetSelfAsync()).GetPermissions(e.Channel).ManageMessages)
                //	await e.message.DeleteAsync();


                if (callback != null)
                {
                    if (bet > u.Currency)
                    {
                        e.ErrorEmbed(e.GetResource("miki_mekos_insufficient"))
                        .AddInlineField("Pro tip!", "You can get more daily mekos by voting on us [here!](https://discordbots.org/bot/160105994217586689)")
                        .ToEmbed().QueueToChannel(e.Channel);
                        return;
                    }
                    await callback(e, bet);
                }
            }
        }
コード例 #27
0
ファイル: SettingsModule.cs プロジェクト: parzivail/Miki.Bot
        public async Task PrefixAsync(EventContext e)
        {
            var    cache = (ICacheClient)e.Services.GetService(typeof(ICacheClient));
            string args  = e.Arguments.Pack.TakeAll();

            if (string.IsNullOrEmpty(args))
            {
                await e.ErrorEmbed(e.Locale.GetString("miki_module_general_prefix_error_no_arg")).ToEmbed().QueueToChannelAsync(e.Channel);

                return;
            }

            PrefixInstance defaultInstance = e.commandHandler.GetDefaultPrefix();

            using (var context = new MikiContext())
            {
                await defaultInstance.ChangeForGuildAsync(context, cache, e.Guild.Id, args);
            }

            EmbedBuilder embed = new EmbedBuilder();

            embed.SetTitle(e.Locale.GetString("miki_module_general_prefix_success_header"));
            embed.SetDescription(
                e.Locale.GetString("miki_module_general_prefix_success_message", args
                                   ));

            await embed.ToEmbed().QueueToChannelAsync(e.Channel);
        }
コード例 #28
0
ファイル: GeneralModule.cs プロジェクト: Auxiliatrix/Miki.Bot
        public async Task UrbanAsync(EventContext e)
        {
            if (string.IsNullOrEmpty(e.Arguments.ToString()))
            {
                return;
            }

            UrbanDictionaryApi   api   = new UrbanDictionaryApi(UrbanKey);
            UrbanDictionaryEntry entry = await api.GetEntryAsync(e.Arguments.ToString());

            if (entry != null)
            {
                await new EmbedBuilder()
                {
                    Author = new EmbedAuthor()
                    {
                        Name    = entry.Term,
                        IconUrl = "http://cdn9.staztic.com/app/a/291/291148/urban-dictionary-647813-l-140x140.png",
                        Url     = "http://www.urbandictionary.com/define.php?term=" + e.Arguments.ToString(),
                    },
                    Description = e.Locale.GetString("miki_module_general_urban_author", entry.Author)
                }.AddField(e.Locale.GetString("miki_module_general_urban_definition"), entry.Definition, true)
                .AddField(e.Locale.GetString("miki_module_general_urban_example"), entry.Example, true)
                .AddField(e.Locale.GetString("miki_module_general_urban_rating"), "👍 " + entry.ThumbsUp.ToFormattedString() + "  👎 " + entry.ThumbsDown.ToFormattedString(), true)
                .ToEmbed().QueueToChannelAsync(e.Channel);
            }
            else
            {
                await e.ErrorEmbed(e.Locale.GetString("error_term_invalid"))
                .ToEmbed().QueueToChannelAsync(e.Channel);
            }
        }
コード例 #29
0
        public async Task UrbanAsync(EventContext e)
        {
            if (string.IsNullOrEmpty(e.arguments))
            {
                return;
            }

            Locale               locale = new Locale(e.Channel.Id);
            UrbanDictionaryApi   api    = new UrbanDictionaryApi(Global.Config.UrbanKey);
            UrbanDictionaryEntry entry  = await api.GetEntryAsync(e.arguments);

            if (entry != null)
            {
                IDiscordEmbed embed = Utils.Embed
                                      .SetAuthor(entry.Term,
                                                 "http://cdn9.staztic.com/app/a/291/291148/urban-dictionary-647813-l-140x140.png",
                                                 "http://www.urbandictionary.com/define.php?term=" + e.arguments)
                                      .SetDescription(locale.GetString("miki_module_general_urban_author", entry.Author));

                embed.AddInlineField(locale.GetString("miki_module_general_urban_definition"), entry.Definition);
                embed.AddInlineField(locale.GetString("miki_module_general_urban_example"), entry.Example);
                embed.AddInlineField(locale.GetString("miki_module_general_urban_rating"), "👍 " + entry.ThumbsUp + "  👎 " + entry.ThumbsDown);

                embed.QueueToChannel(e.Channel);
            }
            else
            {
                e.ErrorEmbed(e.GetResource("error_term_invalid"))
                .QueueToChannel(e.Channel.Id);
            }
        }
コード例 #30
0
        public async Task SetLeaveMessage(EventContext e)
        {
            string leaveMsgString = e.Arguments.Pack.TakeAll();

            using (var context = new MikiContext())
            {
                if (string.IsNullOrEmpty(leaveMsgString))
                {
                    EventMessage leaveMessage = context.EventMessages.Find(e.Channel.Id.ToDbLong(), (short)EventMessageType.LEAVESERVER);
                    if (leaveMessage == null)
                    {
                        await e.ErrorEmbed($"No leave message found! To set one use: `>setleavemessage <message>`")
                        .ToEmbed().QueueToChannelAsync(e.Channel);

                        return;
                    }

                    context.EventMessages.Remove(leaveMessage);
                    await e.SuccessEmbed($"Deleted your leave message")
                    .QueueToChannelAsync(e.Channel);
                }
                else
                {
                    await SetMessageAsync(leaveMsgString, EventMessageType.LEAVESERVER, e.Channel.Id);

                    await e.SuccessEmbed($"Your new leave message is set to: ```{leaveMsgString}```")
                    .QueueToChannelAsync(e.Channel);
                }
                await context.SaveChangesAsync();
            }
        }