Exemplo n.º 1
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);
            }
        }
Exemplo n.º 2
0
        public async Task ShipAsync(ICommandContext e)
        {
            var cache   = e.GetService <IExtendedCacheClient>();
            var context = e.GetService <MikiDbContext>();

            e.Arguments.Take(out string shipPartner);

            IDiscordGuildUser user = await DiscordExtensions.GetUserAsync(shipPartner, e.Guild);

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

            if (await cache.HashExistsAsync("avtr:sync", e.Author.Id.ToString()))
            {
                await Utils.SyncAvatarAsync(e.Author, cache, context);
            }

            if (await cache.HashExistsAsync("avtr:sync", user.Id.ToString()))
            {
                await Utils.SyncAvatarAsync(user, cache, context);
            }

            Random r = new Random((int)((e.Author.Id + user.Id + (ulong)DateTime.Now.DayOfYear) % int.MaxValue));

            int value = r.Next(0, 100);

            Stream s = await imageClient.GetStreamAsync($"/api/ship?me={e.Author.Id}&other={user.Id}&value={value}");

            await(e.Channel as IDiscordTextChannel).SendFileAsync(s, "meme.png");
        }
Exemplo n.º 3
0
        public async Task GuildInfoAsync(EventContext e)
        {
            IDiscordGuildUser owner = await e.Guild.GetOwnerAsync();

            //var emojiNames = e.Guild.Emotes.Select(x => x.ToString());
            string emojiOutput = "none (yet!)";

            //if(emojiNames.Count() > 0)
            //{
            //	emojiOutput = string.Join(",", emojiNames);
            //}

            string prefix = await e.commandHandler.GetPrefixAsync(e.Guild.Id);

            new EmbedBuilder()
            {
                Author = new EmbedAuthor()
                {
                    Name    = e.Guild.Name,
                    IconUrl = e.Guild.IconUrl,
                    Url     = e.Guild.IconUrl
                },
            }.AddInlineField("👑 " + e.Locale.GetString("miki_module_general_guildinfo_owned_by"), $"{owner.Username}#{owner.Discriminator}")
            .AddInlineField("👉 " + e.Locale.GetString("miki_label_prefix"), prefix)
            .AddInlineField("📺 " + e.Locale.GetString("miki_module_general_guildinfo_channels"), (await e.Guild.GetChannelsAsync()).Count.ToString())
            .AddInlineField("🔊 " + e.Locale.GetString("miki_module_general_guildinfo_voicechannels"), (await e.Guild.GetVoiceChannelsAsync()).Count.ToString())
            .AddInlineField("🙎 " + e.Locale.GetString("miki_module_general_guildinfo_users"), (await e.Guild.GetUsersAsync()).Count.ToString())
            //.AddInlineField("🤖 " +  e.GetResource("term_shard"), Bot.Instance.Client.GetShardFor(e.Guild).ShardId)
            .AddInlineField("#⃣ " + e.Locale.GetString("miki_module_general_guildinfo_roles_count"), (await e.Guild.GetRolesAsync()).Count.ToString())
            .AddField("📜 " + e.Locale.GetString("miki_module_general_guildinfo_roles"),
                      string.Join(",", (await e.Guild.GetRolesAsync()).Select(x => $"`{x.Name}`")))
            .AddField("😃 " + e.Locale.GetString("term_emoji"), emojiOutput)
            .ToEmbed().QueueToChannel(e.Channel);
        }
Exemplo n.º 4
0
        public async Task AvatarAsync(CommandContext e)
        {
            string avatarUrl      = e.Author.GetAvatarUrl();
            string avatarResource = e.Author.Username;

            if (e.Arguments.Take(out string arg))
            {
                if (arg == "-s")
                {
                    avatarUrl      = e.Guild.IconUrl;
                    avatarResource = e.Guild.Name;
                    return;
                }

                IDiscordGuildUser user = await DiscordExtensions.GetUserAsync(arg, e.Guild);

                if (user != null)
                {
                    avatarUrl      = user.GetAvatarUrl();
                    avatarResource = user.Username;
                }
            }

            await new EmbedBuilder()
            .SetTitle($"🖼 Avatar for {avatarResource}")
            .SetThumbnail(avatarUrl)
            .SetColor(215, 158, 132)
            .AddInlineField("Full image", $"[click here]({avatarUrl})")
            .ToEmbed()
            .QueueToChannelAsync(e.Channel);
        }
Exemplo n.º 5
0
        public async Task OnClientOnGuildMemberDeleteAsync(IDiscordGuildUser user)
        {
            using var scope = app.Services.CreateScope();
            var context = scope.ServiceProvider.GetService <DbContext>();

            try
            {
                var guild = await user.GetGuildAsync();

                var data = await GetMessageAsync(context, guild, EventMessageType.LEAVESERVER, user);

                if (data == null)
                {
                    return;
                }

                data.ForEach(x => x.DestinationChannel.SendMessageAsync(x.Message));
            }
            catch (Exception e)
            {
                var @event = e.ToSentryEvent();
                @event.SetTag("user.id", user?.Id.ToString() ?? "null");
                @event.SetTag("guild.id", user?.GuildId.ToString() ?? "null");
                sentryClient.CaptureEvent(e.ToSentryEvent());
            }
        }
Exemplo n.º 6
0
        public async Task WarnAsync(
            IDiscordGuild guild,
            MessageContext context,
            IDiscordGuildUser user,
            [Optional, Remaining] string reason)
        {
            var @event = await _eventManager.CallAsync(new UserWarnEvent(user, context.User, reason));

            if (@event.IsCancelled)
            {
                return;
            }

            var warning = new UserWarning
            {
                GuildId     = guild.Id,
                UserId      = user.Id,
                ModeratorId = context.User.Id,
                Reason      = reason,
                Created     = DateTime.UtcNow
            };

            await _warningRepository.AddAsync(warning);

            await _consoleService.UpdateWarningMessageAsync(context, warning, user, context.User);
        }
Exemplo n.º 7
0
        public async Task ShipAsync(EventContext e)
        {
            ArgObject o = e.Arguments.First().TakeUntilEnd();

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

            // TODO: implement UserNullException
            if (user == null)
            {
                return;
            }

            if (!await Global.RedisClient.ExistsAsync($"user:{e.Author.Id}:avatar:synced"))
            {
                await Utils.SyncAvatarAsync(e.Author);
            }

            if (!await Global.RedisClient.ExistsAsync($"user:{user.Id}:avatar:synced"))
            {
                await Utils.SyncAvatarAsync(user);
            }

            Random r = new Random((int)((e.Author.Id + user.Id + (ulong)DateTime.Now.DayOfYear) % int.MaxValue));

            int value = r.Next(0, 100);

            Stream s = await imageClient.GetStreamAsync($"/api/ship?me={e.Author.Id}&other={user.Id}&value={value}");

            await e.Channel.SendFileAsync(s, "meme.png");
        }
Exemplo n.º 8
0
        public async Task WarningsAsync(IDiscordGuild guild, MessageContext context, IDiscordGuildUser user)
        {
            var warnings = await _warningRepository.GetWarningsForUserAsync(guild.Id, user.Id);

            string GetLine(UserWarning w)
            {
                var title = w.ConsoleChannelId.HasValue && w.ConsoleMessageId.HasValue
                    ? $"[#{w.Id}](https://discordapp.com/channels/{guild.Id}/{w.ConsoleChannelId}/{w.ConsoleMessageId})"
                    : $"#{w.Id}";

                return($"[{title} | {w.Created:d}] {w.Reason.MaxLength(50, "...")}");
            }

            var lastYear  = DateTime.UtcNow.Subtract(TimeSpan.FromDays(365));
            var lastMonth = DateTime.UtcNow.Subtract(TimeSpan.FromDays(31));
            var lastWeek  = DateTime.UtcNow.Subtract(TimeSpan.FromDays(7));

            var stats = _localizer["Moderation.Warnings.Stats"]
                        .WithToken("total", warnings.Count)
                        .WithToken("year", warnings.Count(w => w.Created >= lastYear))
                        .WithToken("month", warnings.Count(w => w.Created >= lastMonth))
                        .WithToken("week", warnings.Count(w => w.Created >= lastWeek));

            context.Response.AddEmbed()
            .SetEmbedAuthor(_localizer["Moderation.Warnings.Title"].WithToken("user", user), user.GetAvatarUrl(size: ImageSize.x32))
            .AddEmbedField(_localizer["Moderation.Warnings.Stats.Header"], stats)
            .AddEmbedField(_localizer["Moderation.Warnings.Warnings.Header"], string.Join("\n", warnings.Select(GetLine)));
        }
Exemplo n.º 9
0
        /// <inheritdoc />
        public async Task <GuildPermission> GetPermissionsAsync(IDiscordGuildUser user)
        {
            if (user.Id == OwnerId)
            {
                return(GuildPermission.All);
            }

            GuildPermission permissions = Permissions;

            if (permissions.HasFlag(GuildPermission.Administrator))
            {
                return(GuildPermission.All);
            }

            IDiscordRole everyoneRole = await GetRoleAsync(Id);

            permissions = everyoneRole.Permissions;

            if (user.RoleIds != null)
            {
                var roles = await GetRolesAsync();

                foreach (IDiscordRole role in roles.Where(x => user.RoleIds.Contains(x.Id)))
                {
                    permissions |= role.Permissions;
                }
            }

            if (permissions.HasFlag(GuildPermission.Administrator))
            {
                return(GuildPermission.All);
            }
            return(permissions);
        }
Exemplo n.º 10
0
        public async Task <List <EventMessageObject> > GetMessage(IDiscordGuild guild, EventMessageType type, IDiscordUser user)
        {
            var channels = await guild.GetChannelsAsync();

            var channelIds = channels.Select(x => x.Id.ToDbLong());

            IDiscordGuildUser owner = await guild.GetOwnerAsync();

            var ownerMention = owner.Mention;
            var ownerName    = owner.Username;

            List <EventMessageObject> output = new List <EventMessageObject>();

            using (var context = new MikiContext())
            {
                var messageObjects = await context.EventMessages
                                     .Where(x => channelIds.Contains(x.ChannelId) && (short)type == x.EventType)
                                     .ToListAsync();

                var allUsers = await guild.GetMembersAsync();

                foreach (var c in messageObjects)
                {
                    if (c == null)
                    {
                        continue;
                    }

                    if (string.IsNullOrEmpty(c.Message))
                    {
                        continue;
                    }

                    string modifiedMessage = c.Message;

                    modifiedMessage = modifiedMessage.Replace("-um", user.Mention);
                    modifiedMessage = modifiedMessage.Replace("-uc", guild.MemberCount.ToString());
                    modifiedMessage = modifiedMessage.Replace("-u", user.Username);

                    modifiedMessage = modifiedMessage.Replace("-ru", allUsers.ElementAt(MikiRandom.Next(0, allUsers.Count())).Username);

                    modifiedMessage = modifiedMessage.Replace("-now", DateTime.Now.ToShortDateString());
                    modifiedMessage = modifiedMessage.Replace("-s", guild.Name);

                    modifiedMessage = modifiedMessage.Replace("-om", ownerMention);
                    modifiedMessage = modifiedMessage.Replace("-o", ownerName);

                    modifiedMessage = modifiedMessage.Replace("-cc", channels.Count.ToString());
                    modifiedMessage = modifiedMessage.Replace("-vc", channels.Count.ToString());

                    output.Add(new EventMessageObject()
                    {
                        message            = modifiedMessage,
                        destinationChannel = channels.FirstOrDefault(x => x.Id.ToDbLong() == c.ChannelId)
                    });
                }
                return(output);
            }
        }
Exemplo n.º 11
0
 private string GetWhoIsUsername(IDiscordGuildUser user)
 {
     if (string.IsNullOrEmpty(user.Nickname))
     {
         return(user.Username);
     }
     return(user.Username + $" ({user.Nickname})");
 }
Exemplo n.º 12
0
        private async Task OnBlackjackHold(EventContext e, BlackjackManager bm, IDiscordMessage instanceMessage,
                                           int bet, bool charlie = false)
        {
            bm.dealer.Hand.ForEach(x => x.isPublic = true);

            if (!charlie)
            {
                IDiscordGuildUser me = await e.Guild.GetSelfAsync();

                //if (me.GetPermissions(e.Channel as IDiscordGuildUser).Has(ChannelPermission.ManageMessages))
                //{
                //	await e.message.DeleteAsync();
                //}
            }

            while (true)
            {
                if (bm.Worth(bm.dealer) >= Math.Max(bm.Worth(bm.player), 17))
                {
                    if (charlie)
                    {
                        if (bm.dealer.Hand.Count == 5)
                        {
                            if (bm.Worth(bm.dealer) == bm.Worth(bm.player))
                            {
                                await OnBlackjackDraw(e, bm, instanceMessage, bet);

                                return;
                            }
                            await OnBlackjackDead(e, bm, instanceMessage, bet);

                            return;
                        }
                    }
                    else
                    {
                        if (bm.Worth(bm.dealer) == bm.Worth(bm.player))
                        {
                            await OnBlackjackDraw(e, bm, instanceMessage, bet);

                            return;
                        }
                        await OnBlackjackDead(e, bm, instanceMessage, bet);

                        return;
                    }
                }

                bm.dealer.AddToHand(bm.deck.DrawRandom());

                if (bm.Worth(bm.dealer) > 21)
                {
                    await OnBlackjackWin(e, bm, instanceMessage, bet);

                    return;
                }
            }
        }
Exemplo n.º 13
0
        public async Task WhoIsAsync(EventContext e)
        {
            ArgObject arg = e.Arguments.Join();

            if (arg == null)
            {
                throw new ArgumentNullException();
            }

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

            //if (user == null)
            //{
            //	user = e.Author as IGuildUser;
            //}

            var embed = e.CreateEmbedBuilder();

            embed.WithTitle("whois_title", user.Username);
            embed.EmbedBuilder.SetColor(0.5f, 0f, 1.0f);

            embed.EmbedBuilder.ImageUrl = user.GetAvatarUrl();

            var roles = (await e.Guild.GetRolesAsync()).Where(x => user.RoleIds.Contains(x.Id) && x.Color.Value != 0).OrderByDescending(x => x.Position);

            Color c = roles.FirstOrDefault()?.Color ?? new Color(0);

            StringBuilder builder = new StringBuilder();

            builder.AppendLine($"User Id      : **{user.Id}**");
            builder.AppendLine(
                $"Username: **{user.Username}#{user.Discriminator} {(string.IsNullOrEmpty((user as IDiscordGuildUser).Nickname) ? "" : $"({(user as IDiscordGuildUser).Nickname})")}**");
            //builder.AppendLine($"Created at: **{user.CreatedAt.ToString()}**");
            builder.AppendLine($"Joined at   : **{user.JoinedAt.ToString()}**");
            builder.AppendLine($"Color Hex : **#{c.ToHexString()}**");

            embed.AddField(
                e.CreateResource("miki_module_whois_tag_personal"),
                new StringResource(builder.ToString())
                );

            string r = string.Join(" ", roles.Select(x => x.Name));

            if (string.IsNullOrEmpty(r))
            {
                r = "none (yet!)";
            }

            if (r.Length <= 1000)
            {
                embed.AddField(
                    e.CreateResource("miki_module_general_guildinfo_roles"),
                    new StringResource(r)
                    );
            }

            embed.Build().QueueToChannel(e.Channel);
        }
Exemplo n.º 14
0
        /// <inheritdoc />
        public async Task RemoveBanAsync(IDiscordGuildUser user)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            await client.ApiClient.RemoveGuildBanAsync(Id, user.Id);
        }
Exemplo n.º 15
0
        public async Task <List <EventMessageObject> > GetMessageAsync(
            DbContext db, IDiscordGuild guild, EventMessageType type, IDiscordUser user)
        {
            var channels   = (await guild.GetChannelsAsync()).ToList();
            var channelIds = channels.Select(x => (long)x.Id);

            IDiscordGuildUser owner = await guild.GetOwnerAsync();

            var ownerMention = owner.Mention;
            var ownerName    = owner.Username;

            List <EventMessageObject> output = new List <EventMessageObject>();
            short t = (short)type;

            var messageObjects = await db.Set <EventMessage>()
                                 .Where(x => channelIds.Contains(x.ChannelId) && t == x.EventType)
                                 .ToListAsync();

            foreach (var c in messageObjects)
            {
                if (c == null)
                {
                    continue;
                }

                if (string.IsNullOrEmpty(c.Message))
                {
                    continue;
                }

                string modifiedMessage = c.Message;

                modifiedMessage = modifiedMessage.Replace("-um", user.Mention);
                modifiedMessage = modifiedMessage.Replace("-uc", guild.MemberCount.ToString());
                modifiedMessage = modifiedMessage.Replace("-u", user.Username);

                modifiedMessage = modifiedMessage.Replace("-now", DateTime.Now.ToShortDateString());
                modifiedMessage = modifiedMessage.Replace("-s", guild.Name);

                modifiedMessage = modifiedMessage.Replace("-om", ownerMention);
                modifiedMessage = modifiedMessage.Replace("-o", ownerName);

                modifiedMessage = modifiedMessage.Replace("-cc", channels.Count().ToString());
                modifiedMessage = modifiedMessage.Replace("-vc", channels.Count().ToString());

                output.Add(new EventMessageObject
                {
                    Message            = modifiedMessage,
                    DestinationChannel = channels.FirstOrDefault(
                        x => (long)x.Id == c.ChannelId) as IDiscordTextChannel
                });
            }

            return(output);
        }
Exemplo n.º 16
0
        public async Task <GuildPermission> GetPermissionsAsync(IDiscordGuildUser user = null)
        {
            IDiscordGuild guild = await GetGuildAsync();

            if (user == null)
            {
                user = await guild.GetSelfAsync();
            }
            GuildPermission permissions = await guild.GetPermissionsAsync(user);

            return(DiscordChannelHelper.GetOverwritePermissions(user, this, permissions));
        }
Exemplo n.º 17
0
        public static GuildPermission GetOverwritePermissions(
            IDiscordGuildUser user, IDiscordGuildChannel channel, GuildPermission basePermissions)
        {
            var permissions = basePermissions;

            if (permissions.HasFlag(GuildPermission.Administrator))
            {
                return(GuildPermission.All);
            }

            if (channel.PermissionOverwrites != null)
            {
                PermissionOverwrite overwriteEveryone = channel.PermissionOverwrites
                                                        .FirstOrDefault(x => x.Id == channel.GuildId);

                if (overwriteEveryone != null)
                {
                    permissions &= ~overwriteEveryone.DeniedPermissions;
                    permissions |= overwriteEveryone.AllowedPermissions;
                }

                PermissionOverwrite overwrites = new PermissionOverwrite();

                if (user.RoleIds != null)
                {
                    foreach (ulong roleId in user.RoleIds)
                    {
                        PermissionOverwrite roleOverwrites = channel.PermissionOverwrites
                                                             .FirstOrDefault(x => x.Id == roleId);

                        if (roleOverwrites != null)
                        {
                            overwrites.AllowedPermissions |= roleOverwrites.AllowedPermissions;
                            overwrites.DeniedPermissions  &= roleOverwrites.DeniedPermissions;
                        }
                    }
                }

                permissions &= ~overwrites.DeniedPermissions;
                permissions |= overwrites.AllowedPermissions;

                PermissionOverwrite userOverwrite = channel.PermissionOverwrites
                                                    .FirstOrDefault(x => x.Id == user.Id);

                if (userOverwrite != null)
                {
                    permissions &= ~userOverwrite.DeniedPermissions;
                    permissions |= userOverwrite.AllowedPermissions;
                }
            }

            return(permissions);
        }
Exemplo n.º 18
0
        public async ValueTask <GuildPermission> GetPermissionsAsync(IDiscordGuildUser user)
        {
            IDiscordGuild guild = await GetGuildAsync();

            GuildPermission permissions = await guild.GetPermissionsAsync(user);

            if (permissions.HasFlag(GuildPermission.Administrator))
            {
                return(GuildPermission.All);
            }

            if (_packet.PermissionOverwrites != null)
            {
                PermissionOverwrite overwriteEveryone = _packet.PermissionOverwrites
                                                        .FirstOrDefault(x => x.Id == GuildId) ?? null;

                if (overwriteEveryone != null)
                {
                    permissions &= ~overwriteEveryone.DeniedPermissions;
                    permissions |= overwriteEveryone.AllowedPermissions;
                }

                PermissionOverwrite overwrites = new PermissionOverwrite();

                if (user.RoleIds != null)
                {
                    foreach (ulong roleId in user.RoleIds)
                    {
                        PermissionOverwrite roleOverwrites = _packet.PermissionOverwrites.FirstOrDefault(x => x.Id == roleId);

                        if (roleOverwrites != null)
                        {
                            overwrites.AllowedPermissions |= roleOverwrites.AllowedPermissions;
                            overwrites.DeniedPermissions  &= roleOverwrites.DeniedPermissions;
                        }
                    }
                }

                permissions &= ~overwrites.DeniedPermissions;
                permissions |= overwrites.AllowedPermissions;

                PermissionOverwrite userOverwrite = _packet.PermissionOverwrites.FirstOrDefault(x => x.Id == user.Id);

                if (userOverwrite != null)
                {
                    permissions &= ~userOverwrite.DeniedPermissions;
                    permissions |= userOverwrite.AllowedPermissions;
                }
            }

            return(permissions);
        }
Exemplo n.º 19
0
        private async Task <LocalExperience> GetOrCreateExperienceProfileAsync(
            DbContext ctx, IDiscordGuildUser user)
        {
            LocalExperience newProfile = await LocalExperience.GetAsync(ctx, user.GuildId, user.Id)
                                         .ConfigureAwait(false);

            if (newProfile == null)
            {
                return(await LocalExperience.CreateAsync(ctx, user.GuildId, user.Id, user.Username)
                       .ConfigureAwait(false));
            }

            return(newProfile);
        }
Exemplo n.º 20
0
        public async Task GuildInfoAsync(IContext e)
        {
            var guild  = e.GetGuild();
            var locale = e.GetLocale();

            IDiscordGuildUser owner = await guild.GetOwnerAsync()
                                      .ConfigureAwait(false);

            var context = e.GetService <IUnitOfWork>();
            var cache   = e.GetService <ICacheClient>();

            if (!(e.GetService <IPrefixService>()
                  .GetDefaultTrigger() is DynamicPrefixTrigger trigger))
            {
                throw new InvalidOperationException("Cannot get default trigger");
            }

            var prefix = await trigger.GetForGuildAsync(context, cache, guild.Id)
                         .ConfigureAwait(false);

            var roles       = (await e.GetGuild().GetRolesAsync().ConfigureAwait(false)).ToList();
            var channels    = (await e.GetGuild().GetChannelsAsync().ConfigureAwait(false)).ToList();
            var rolesString = string.Join(",", roles.Select(x => $"`{x.Name}`"));

            await new EmbedBuilder()
            .SetAuthor(guild.Name, guild.IconUrl, guild.IconUrl)
            .AddInlineField(
                $"👑 {locale.GetString("miki_module_general_guildinfo_owned_by")}",
                $"{owner.Username}#{owner.Discriminator}")
            .AddInlineField(
                $"👉 {locale.GetString("miki_label_prefix")}", prefix)
            .AddInlineField(
                $"📺 {locale.GetString("miki_module_general_guildinfo_channels")}",
                channels.Count(x => x.Type == ChannelType.GuildText).ToString("N0"))
            .AddInlineField(
                $"🔊 {locale.GetString("miki_module_general_guildinfo_voicechannels")}",
                channels.Count(x => x.Type == ChannelType.GuildVoice).ToString("N0"))
            .AddInlineField(
                $"🙎 {locale.GetString("miki_module_general_guildinfo_users")}",
                roles.Count.ToString("N0"))
            .AddInlineField(
                $"#⃣ {locale.GetString("miki_module_general_guildinfo_roles_count")}",
                roles.Count.ToString("N0"))
            .AddField(
                $"📜 {locale.GetString("miki_module_general_guildinfo_roles")}",
                rolesString.SplitStringUntil(",", 1500))
            .ToEmbed()
            .QueueAsync(e, e.GetChannel())
            .ConfigureAwait(false);
        }
Exemplo n.º 21
0
        public async Task ResetAsync(IDiscordGuildUser user, string permission)
        {
            if (!ValidatePermission(permission))
            {
                return;
            }

            if (!await _permissionManager.ResetUserPermissionAsync(_guild.Id, user.Id, permission))
            {
                Response.AddError(GetString("Command.Reset.Failed", "User", permission, user));
            }
            else
            {
                Response.AddSuccess(GetString("Command.Reset.Success", "User", permission, user));
            }
        }
Exemplo n.º 22
0
        public async Task ShipAsync(ICommandContext e)
        {
            var cache   = e.GetService <IExtendedCacheClient>();
            var context = e.GetService <MikiDbContext>();

            e.Arguments.Take(out string shipPartner);

            IDiscordGuildUser user = await DiscordExtensions.GetUserAsync(shipPartner, e.Guild);

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

            using (var client = new RestClient(Global.Config.CdnRegionEndpoint))
            {
                var authorResponse = await client.SendAsync(new HttpRequestMessage()
                {
                    Method     = new HttpMethod("HEAD"),
                    RequestUri = new Uri($"{Global.Config.CdnRegionEndpoint}/avatars/{e.Author.Id}.png")
                });

                if (!authorResponse.Success)
                {
                    await Utils.SyncAvatarAsync(e.Author, cache, context);
                }

                var otherResponse = await client.SendAsync(new HttpRequestMessage()
                {
                    Method     = new HttpMethod("HEAD"),
                    RequestUri = new Uri($"{Global.Config.CdnRegionEndpoint}/avatars/{user.Id}.png")
                });

                if (!authorResponse.Success)
                {
                    await Utils.SyncAvatarAsync(e.Author, cache, context);
                }
            }
            Random r = new Random((int)((e.Author.Id + user.Id + (ulong)DateTime.Now.DayOfYear) % int.MaxValue));

            int value = r.Next(0, 100);

            Stream s = await imageClient.GetStreamAsync($"/api/ship?me={e.Author.Id}&other={user.Id}&value={value}");

            await(e.Channel as IDiscordTextChannel).SendFileAsync(s, "meme.png");
        }
Exemplo n.º 23
0
        private async Task <List <PermissionGroup> > GetPermissionGroups(IDiscordGuildUser user, IDiscordGuild guild)
        {
            var userPermissions = await guild.GetPermissionsAsync(user);

            var groups = GetDefaultPermissions(user);

            if (userPermissions.HasFlag(_options.ModeratorPermission))
            {
                groups.Add(PermissionGroup.Moderator);
            }

            if (userPermissions.HasFlag(_options.AdministratorPermission))
            {
                groups.Add(PermissionGroup.Administrator);
            }

            return(groups);
        }
Exemplo n.º 24
0
        // TODO: rework this
        public async Task <EventAccessibility> GetUserAccessibility(IDiscordMessage e, IDiscordChannel channel)
        {
            if (e.Author.Id == 121919449996460033)
            {
                return(EventAccessibility.DEVELOPERONLY);
            }

            if (channel is IDiscordGuildChannel guildChannel)
            {
                IDiscordGuildUser u = await(await guildChannel.GetGuildAsync()).GetUserAsync(e.Author.Id);
                if ((await guildChannel.GetPermissionsAsync(u)).HasFlag(GuildPermission.ManageRoles))
                {
                    return(EventAccessibility.ADMINONLY);
                }
            }

            return(EventAccessibility.PUBLIC);
        }
Exemplo n.º 25
0
        public async Task ShipAsync(EventContext e)
        {
            e.Arguments.Take(out string shipPartner);

            IDiscordGuildUser user = await DiscordExtensions.GetUserAsync(shipPartner, e.Guild);

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

            Random r = new Random((int)((e.Author.Id + user.Id + (ulong)DateTime.Now.DayOfYear) % int.MaxValue));

            int value = r.Next(0, 100);

            Stream s = await imageClient.GetStreamAsync($"/api/ship?me={e.Author.Id}&other={user.Id}&value={value}");

            await(e.Channel as IDiscordTextChannel).SendFileAsync(s, "meme.png");
        }
Exemplo n.º 26
0
        private async Task OnBlackjackHit(EventContext e, BlackjackManager bm, IDiscordMessage instanceMessage, int bet)
        {
            IDiscordGuildUser me = await e.Guild.GetSelfAsync();

            //if (me.GetPermissions(e.Channel as IDiscordGuildChannel).Has(ChannelPermission.ManageMessages))
            //{
            //	await e.message.DeleteAsync();
            //}

            bm.player.AddToHand(bm.deck.DrawRandom());

            if (bm.Worth(bm.player) > 21)
            {
                await OnBlackjackDead(e, bm, instanceMessage, bet);
            }
            else
            {
                if (bm.player.Hand.Count == 5)
                {
                    await OnBlackjackHold(e, bm, instanceMessage, bet, true);

                    return;
                }
                else if (bm.Worth(bm.player) == 21 && bm.Worth(bm.dealer) != 21)
                {
                    await OnBlackjackWin(e, bm, instanceMessage, bet);

                    return;
                }
                else if (bm.Worth(bm.dealer) == 21 && bm.Worth(bm.player) != 21)
                {
                    await OnBlackjackDead(e, bm, instanceMessage, bet);

                    return;
                }

                await instanceMessage.EditAsync(new EditMessageArgs
                {
                    embed = bm.CreateEmbed(e).ToEmbed()
                });
            }
        }
Exemplo n.º 27
0
        public async Task GuildInfoAsync(EventContext e)
        {
            IDiscordGuildUser owner = await e.Guild.GetOwnerAsync();

            //var emojiNames = e.Guild.R.Select(x => x.ToString());
            string emojiOutput = "none (yet!)";

            //if (emojiNames.Count() > 0)
            //{
            //	emojiOutput = string.Join(",", emojiNames);
            //}

            using (var context = new MikiContext())
            {
                string prefix = await e.commandHandler.GetDefaultPrefixValueAsync(context, e.Guild.Id);

                var roles = await e.Guild.GetRolesAsync();

                var channels = await e.Guild.GetChannelsAsync();

                await new EmbedBuilder()
                {
                    Author = new EmbedAuthor()
                    {
                        Name    = e.Guild.Name,
                        IconUrl = e.Guild.IconUrl,
                        Url     = e.Guild.IconUrl
                    },
                }.AddInlineField("👑 " + e.Locale.GetString("miki_module_general_guildinfo_owned_by"), $"{owner.Username}#{owner.Discriminator}")
                .AddInlineField("👉 " + e.Locale.GetString("miki_label_prefix"), prefix)
                .AddInlineField("📺 " + e.Locale.GetString("miki_module_general_guildinfo_channels"), channels.Count(x => x.Type == ChannelType.GUILDTEXT).ToFormattedString())
                .AddInlineField("🔊 " + e.Locale.GetString("miki_module_general_guildinfo_voicechannels"), channels.Count(x => x.Type == ChannelType.GUILDVOICE).ToFormattedString())
                .AddInlineField("🙎 " + e.Locale.GetString("miki_module_general_guildinfo_users"), roles.Count().ToFormattedString())
                .AddInlineField("#⃣ " + e.Locale.GetString("miki_module_general_guildinfo_roles_count"), roles.Count().ToFormattedString())
                .AddField("📜 " + e.Locale.GetString("miki_module_general_guildinfo_roles"),
                          string.Join(",", roles.Select(x => $"`{x.Name}`")))
                .AddField("😃 " + e.Locale.GetString("term_emoji"), emojiOutput)
                .ToEmbed().QueueToChannelAsync(e.Channel);
            }
        }
Exemplo n.º 28
0
        public async Task <string> Print(int currentValue, IDiscordGuild g, IDiscordGuildChannel c)
        {
            string output = "";

            IDiscordGuildUser u = await g.GetSelfAsync();

            if (!(await c.GetPermissionsAsync(u)).HasFlag(GuildPermission.UseExternalEmojis))
            {
                return("");
            }

            int iteration        = MaxValue / Width;
            int currentIteration = iteration;

            for (int i = 0; i < Width; i++)
            {
                output           += (currentValue >= currentIteration) ? ValueOn.GetAppropriateSection(0, Width - 1, i) : ValueOff.GetAppropriateSection(0, Width - 1, i);
                currentIteration += iteration;
            }

            return(output);
        }
Exemplo n.º 29
0
        public async Task AvatarAsync(EventContext e)
        {
            if (!e.Arguments.Take(out string arg))
            {
                e.Channel.QueueMessage(e.Author.GetAvatarUrl());
            }
            else
            {
                if (arg == "-s")
                {
                    e.Channel.QueueMessage(e.Guild.IconUrl);
                    return;
                }

                IDiscordGuildUser user = await DiscordExtensions.GetUserAsync(arg, e.Guild);

                if (user != null)
                {
                    e.Channel.QueueMessage(user.GetAvatarUrl());
                }
            }
        }
Exemplo n.º 30
0
        private async Task OnClientOnGuildMemberCreateAsync(IDiscordGuildUser user)
        {
            using var scope = app.Services.CreateScope();
            var context = scope.ServiceProvider.GetService <DbContext>();

            try
            {
                var guild = await user.GetGuildAsync();

                var data = await GetMessageAsync(context, guild, EventMessageType.JOINSERVER, user);

                if (data == null)
                {
                    return;
                }

                data.ForEach(x => x.DestinationChannel.SendMessageAsync(x.Message));
            }
            catch (Exception e)
            {
                sentryClient.CaptureEvent(e.ToSentryEvent());
            }
        }