コード例 #1
0
        public override ValueTask <TypeParserResult <DiscordRole> > ParseAsync(Parameter parameter, string value, RiasCommandContext context)
        {
            var localization = context.Services.GetRequiredService <Localization>();

            if (context.Guild is null)
            {
                return(TypeParserResult <DiscordRole> .Failed(localization.GetText(context.Guild?.Id, Localization.TypeParserRoleNotGuild)));
            }

            DiscordRole?role;

            if (RiasUtilities.TryParseRoleMention(value, out var roleId) || ulong.TryParse(value, out roleId))
            {
                role = context.Guild.GetRole(roleId);
                if (role != null)
                {
                    return(TypeParserResult <DiscordRole> .Successful(role));
                }

                return(TypeParserResult <DiscordRole> .Failed(localization.GetText(context.Guild?.Id, Localization.AdministrationRoleNotFound)));
            }

            role = context.Guild.Roles.FirstOrDefault(x => string.Equals(x.Value.Name, value, StringComparison.OrdinalIgnoreCase)).Value;
            if (role != null)
            {
                return(TypeParserResult <DiscordRole> .Successful(role));
            }

            return(TypeParserResult <DiscordRole> .Failed(localization.GetText(context.Guild?.Id, Localization.AdministrationRoleNotFound)));
        }
コード例 #2
0
        private async Task WebSocketClosed()
        {
            Log.Warning("Patreon WebSocket was closed. Retrying in 10 seconds...");
            await Task.Delay(10000);

            RiasUtilities.RunTask(() => ConnectWebSocket(true));
        }
コード例 #3
0
            public async Task DatabaseAsync([Remainder] IUser user)
            {
                var userDb = await DbContext.Users.FirstOrDefaultAsync(x => x.UserId == user.Id);

                if (userDb is null)
                {
                    await ReplyErrorAsync(Localization.BotUserNotInDatabase);

                    return;
                }

                var mutualGuilds = user is CachedUser cachedUser ? cachedUser.MutualGuilds.Count : 0;

                var embed = new LocalEmbedBuilder()
                            .WithColor(RiasUtilities.ConfirmColor)
                            .WithAuthor(user)
                            .AddField(GetText(Localization.CommonId), user.Id, true)
                            .AddField(GetText(Localization.GamblingCurrency), $"{userDb.Currency} {Credentials.Currency}", true)
                            .AddField(GetText(Localization.XpGlobalLevel), RiasUtilities.XpToLevel(userDb.Xp, 30), true)
                            .AddField(GetText(Localization.XpGlobalXp), userDb.Xp, true)
                            .AddField(GetText(Localization.BotIsBlacklisted), userDb.IsBlacklisted, true)
                            .AddField(GetText(Localization.BotIsBanned), userDb.IsBanned, true)
                            .AddField(GetText(Localization.BotMutualGuilds), mutualGuilds, true)
                            .WithImageUrl(user.GetAvatarUrl());

                await ReplyAsync(embed);
            }
コード例 #4
0
        public override ValueTask <TypeParserResult <DiscordColor> > ParseAsync(Parameter parameter, string value, RiasCommandContext context)
        {
            var hex = RiasUtilities.HexToInt(value);

            if (hex.HasValue)
            {
                return(TypeParserResult <DiscordColor> .Successful(new DiscordColor(hex.Value)));
            }

            var color = default(System.Drawing.Color);

            if (Enum.TryParse <System.Drawing.KnownColor>(value.Replace(" ", string.Empty), true, out var knownColor))
            {
                color = System.Drawing.Color.FromKnownColor(knownColor);
            }

            if (!color.IsEmpty)
            {
                return(TypeParserResult <DiscordColor> .Successful(new DiscordColor(color.R, color.G, color.B)));
            }

            var localization = context.Services.GetRequiredService <Localization>();

            return(TypeParserResult <DiscordColor> .Failed(localization.GetText(context.Guild?.Id, Localization.TypeParserInvalidColor)));
        }
コード例 #5
0
            public async Task DatabaseAsync([Remainder] DiscordUser user)
            {
                var userDb = await DbContext.Users.FirstOrDefaultAsync(x => x.UserId == user.Id);

                if (userDb is null)
                {
                    await ReplyErrorAsync(Localization.BotUserNotInDatabase, user.FullName());

                    return;
                }

                var mutualGuilds = user is DiscordMember cachedUser?cachedUser.GetMutualGuilds(RiasBot).Count() : 0;

#if RELEASE
                var currency = GetText(Localization.GamblingCurrency);
#else
                var currency = GetText(Localization.GamblingHearts);
#endif

                var embed = new DiscordEmbedBuilder()
                            .WithColor(RiasUtilities.ConfirmColor)
                            .WithAuthor(user.FullName(), user.GetAvatarUrl(ImageFormat.Auto))
                            .AddField(GetText(Localization.CommonId), user.Id.ToString(), true)
                            .AddField(currency, $"{userDb.Currency} {Configuration.Currency}", true)
                            .AddField(GetText(Localization.XpGlobalLevel), RiasUtilities.XpToLevel(userDb.Xp, 30).ToString(), true)
                            .AddField(GetText(Localization.XpGlobalXp), userDb.Xp.ToString(), true)
                            .AddField(GetText(Localization.BotIsBanned), userDb.IsBanned.ToString(), true)
                            .AddField(GetText(Localization.BotMutualGuilds), mutualGuilds.ToString(), true)
                            .WithImageUrl(user.GetAvatarUrl(ImageFormat.Auto));

                await ReplyAsync(embed);
            }
コード例 #6
0
            public async Task EmojiAsync([Remainder] string emoji)
            {
                if (!RiasUtilities.TryParseEmoji(emoji, out var emojiId))
                {
                    await ReplyErrorAsync(Localization.AdministrationEmojiNotValid);

                    return;
                }

                var httpClient = HttpClient;
                var emojiUrl   = string.Format(EmojiCdn, $"{emojiId}.gif");
                var result     = await httpClient.GetAsync(emojiUrl);

                if (result.StatusCode == HttpStatusCode.UnsupportedMediaType)
                {
                    emojiUrl = string.Format(EmojiCdn, $"{emojiId}.png");
                    result   = await httpClient.GetAsync(emojiUrl);

                    if (!result.IsSuccessStatusCode)
                    {
                        await ReplyErrorAsync(Localization.AdministrationEmojiNotValid);

                        return;
                    }
                }

                var embed = new DiscordEmbedBuilder
                {
                    Color  = RiasUtilities.ConfirmColor,
                    Author = new DiscordEmbedBuilder.EmbedAuthor
                    {
                        Name = emoji[(emoji.IndexOf(":", StringComparison.Ordinal) + 1)..emoji.LastIndexOf(":", StringComparison.Ordinal)],
コード例 #7
0
        public async Task SendAsync(string id, [Remainder] string message)
        {
            var isEmbed = RiasUtilities.TryParseEmbed(message, out var embed);

            if (id.StartsWith("c:", StringComparison.InvariantCultureIgnoreCase))
            {
                CachedChannel channel;
                if (Snowflake.TryParse(id[2..], out var channelId))
コード例 #8
0
        public async Task XpLeaderboardAsync(int page = 1)
        {
            page--;
            if (page < 0)
            {
                page = 0;
            }

            var membersXp = (await DbContext.GetOrderedListAsync <MembersEntity, int>(x => x.GuildId == Context.Guild !.Id, y => y.Xp, true))
                            .Where(x => Context.Guild !.Members.ContainsKey(x.MemberId))
                            .ToList();

            var xpLeaderboard = membersXp.Skip(page * 15)
                                .Take(15)
                                .ToList();

            if (xpLeaderboard.Count == 0)
            {
                await ReplyErrorAsync(Localization.XpGuildLeaderboardEmpty);

                return;
            }

            var description = new StringBuilder();
            var index       = page * 15;

            foreach (var userDb in xpLeaderboard)
            {
                try
                {
                    var member = await Context.Guild !.GetMemberAsync(userDb.MemberId);
                    description.Append($"{++index}. **{member.FullName()}**: " +
                                       $"`{GetText(Localization.XpLevelX, RiasUtilities.XpToLevel(userDb.Xp, XpService.XpThreshold))} " +
                                       $"({userDb.Xp} {GetText(Localization.XpXp).ToLowerInvariant()})`\n");
                }
                catch
                {
                    // ignored
                }
            }

            var embed = new DiscordEmbedBuilder
            {
                Color       = RiasUtilities.ConfirmColor,
                Title       = GetText(Localization.XpGuildLeaderboard),
                Description = description.ToString(),
                Footer      = new DiscordEmbedBuilder.EmbedFooter
                {
                    IconUrl = Context.User.GetAvatarUrl(ImageFormat.Auto),
                    Text    = $"{Context.User.FullName()} • #{membersXp.FindIndex(x => x.MemberId == Context.User.Id) + 1}"
                }
            };

            await ReplyAsync(embed);
        }
コード例 #9
0
        public override ValueTask <TypeParserResult <TimeSpan> > ParseAsync(Parameter parameter, string value, RiasCommandContext context)
        {
            var timespan = RiasUtilities.ConvertToTimeSpan(value);

            if (timespan.HasValue)
            {
                return(TypeParserResult <TimeSpan> .Successful(timespan.Value));
            }

            var localization = context.Services.GetRequiredService <Localization>();

            return(TypeParserResult <TimeSpan> .Failed(localization.GetText(context.Guild?.Id, Localization.TypeParserTimeSpanUnsuccessful)));
        }
コード例 #10
0
        public VotesService(IServiceProvider serviceProvider)
            : base(serviceProvider)
        {
            if (Configuration.VotesConfiguration == null)
            {
                return;
            }

            _webSocket = new WebSocketClient(Configuration.VotesConfiguration);
            RiasUtilities.RunTask(() => ConnectWebSocket());
            _webSocket.DataReceived += VoteReceivedAsync;
            _webSocket.Closed       += WebSocketClosed;

            RiasUtilities.RunTask(CheckVotesAsync);
        }
コード例 #11
0
        private async Task AddBackgroundAsync(MagickImage image, ProfileInfo profileInfo)
        {
            if (string.IsNullOrEmpty(profileInfo.BackgroundUrl))
            {
                AddBackground(null, image, profileInfo);
                return;
            }

            try
            {
                using var response = await _httpClient.GetAsync(profileInfo.BackgroundUrl);

                if (!response.IsSuccessStatusCode)
                {
                    AddBackground(null, image, profileInfo);
                    return;
                }

                await using var backgroundStream = await response.Content.ReadAsStreamAsync();

                if (!(RiasUtilities.IsPng(backgroundStream) || RiasUtilities.IsJpg(backgroundStream)))
                {
                    AddBackground(null, image, profileInfo);
                    return;
                }

                backgroundStream.Position     = 0;
                using var tempBackgroundImage = new MagickImage(backgroundStream);

                tempBackgroundImage.Resize(new MagickGeometry
                {
                    Width             = 500,
                    Height            = 250,
                    IgnoreAspectRatio = false,
                    FillArea          = true
                });

                using var backgroundImageLayer = new MagickImage(MagickColors.Black, 500, 250);
                backgroundImageLayer.Draw(new DrawableComposite(0, 0, CompositeOperator.Over, tempBackgroundImage));
                AddBackground(backgroundImageLayer, image, profileInfo);
            }
            catch
            {
                AddBackground(null, image, profileInfo);
            }
        }
コード例 #12
0
            public async Task SetAvatarAsync(string url)
            {
                if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
                {
                    await ReplyErrorAsync(Localization.UtilityUrlNotValid);

                    return;
                }

                using var response = await _httpClient.GetAsync(uri);

                if (!response.IsSuccessStatusCode)
                {
                    await ReplyErrorAsync(Localization.UtilityUrlNotValid);

                    return;
                }

                await using var stream = await response.Content.ReadAsStreamAsync();

                await using var avatarStream = new MemoryStream();
                await stream.CopyToAsync(avatarStream);

                avatarStream.Position = 0;

                if (!(RiasUtilities.IsPng(stream) || RiasUtilities.IsJpg(stream)))
                {
                    await ReplyErrorAsync(Localization.UtilityUrlNotPngJpg);

                    return;
                }

                avatarStream.Position = 0;

                try
                {
                    await RiasBot.CurrentUser.ModifyAsync(x => x.Avatar = avatarStream);
                    await ReplyConfirmationAsync(Localization.BotAvatarSet);
                }
                catch
                {
                    await ReplyErrorAsync(Localization.BotSetAvatarError);
                }
            }
コード例 #13
0
        public PatreonService(IServiceProvider serviceProvider)
            : base(serviceProvider)
        {
            if (Configuration.PatreonConfiguration is null)
            {
                return;
            }

            _webSocket = new WebSocketClient(Configuration.PatreonConfiguration);
            RiasUtilities.RunTask(() => ConnectWebSocket());
            _webSocket.DataReceived += PledgeReceivedAsync;
            _webSocket.Closed       += WebSocketClosed;

            RiasUtilities.RunTask(CheckPatronsAsync);

            _httpClient         = serviceProvider.GetRequiredService <IHttpClientFactory>().CreateClient();
            _httpClient.Timeout = TimeSpan.FromMinutes(1);
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(Configuration.PatreonConfiguration.Authorization !);
            _sendPatronsTimer = new Timer(_ => RiasUtilities.RunTask(SendPatronsAsync), null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
        }
コード例 #14
0
        private async Task MessageReceivedAsync(MessageReceivedEventArgs args)
        {
            if (!(args.Message is CachedUserMessage userMessage))
            {
                return;
            }
            if (userMessage.Author.IsBot)
            {
                return;
            }

            var guildChannel = userMessage.Channel as CachedTextChannel;

            if (guildChannel != null)
            {
                await RunTaskAsync(_botService.AddAssignableRoleAsync((CachedMember)userMessage.Author));
                await RunTaskAsync(_xpService.AddUserXpAsync(userMessage.Author));
                await RunTaskAsync(_xpService.AddGuildUserXpAsync((CachedMember)userMessage.Author, userMessage.Channel));
            }

            var prefix = await GetGuildPrefixAsync(guildChannel?.Guild);

            if (CommandUtilities.HasPrefix(userMessage.Content, prefix, out var output) ||
                RiasUtilities.HasMentionPrefix(userMessage, out output))
            {
                await RunTaskAsync(ExecuteCommandAsync(userMessage, userMessage.Channel, prefix, output));

                return;
            }

            if (userMessage.Client.CurrentUser is null)
            {
                return;
            }

            if (CommandUtilities.HasPrefix(userMessage.Content, userMessage.Client.CurrentUser.Name, StringComparison.InvariantCultureIgnoreCase, out output))
            {
                await RunTaskAsync(ExecuteCommandAsync(userMessage, userMessage.Channel, prefix, output));
            }
        }
コード例 #15
0
        public async Task SendAsync([TextChannel] DiscordChannel channel, [Remainder] string message)
        {
            var permissions = channel.Guild.CurrentMember.PermissionsIn(channel);

            if (!permissions.HasPermission(Permissions.AccessChannels))
            {
                await ReplyErrorAsync(Localization.AdministrationTextChannelNoViewPermission);

                return;
            }

            if (!permissions.HasPermission(Permissions.SendMessages))
            {
                await ReplyErrorAsync(Localization.BotTextChannelNoSendMessagesPermission);

                return;
            }

            switch (RiasUtilities.TryParseMessage(message, out var customMessage))
            {
            case true when string.IsNullOrEmpty(customMessage.Content) && customMessage.Embed is null:
                await ReplyErrorAsync(Localization.AdministrationNullCustomMessage);

                return;

            case true:
                await channel.SendMessageAsync(customMessage.Content, customMessage.Embed);

                break;

            default:
                await channel.SendMessageAsync(message);

                break;
            }

            await ReplyConfirmationAsync(Localization.BotMessageSent);
        }
コード例 #16
0
ファイル: XpModule.cs プロジェクト: DiogenesTheGamer/RiasBot
        public async Task XpLeaderboardAsync(int page = 1)
        {
            page--;
            if (page < 0)
            {
                page = 0;
            }

            var xpLeaderboard = (await DbContext.GetOrderedListAsync <GuildUsersEntity, int>(x => x.GuildId == Context.Guild !.Id, y => y.Xp, true))
                                .Where(x => Context.Guild !.GetMember(x.UserId) != null)
                                .Skip(page * 15)
                                .Take(15)
                                .ToList();

            if (xpLeaderboard.Count == 0)
            {
                await ReplyErrorAsync(Localization.XpGuildLeaderboardEmpty);

                return;
            }

            var embed = new LocalEmbedBuilder
            {
                Color = RiasUtilities.ConfirmColor,
                Title = GetText(Localization.XpGuildLeaderboard)
            };

            var index = page * 15;

            foreach (var userDb in xpLeaderboard)
            {
                embed.AddField($"{++index}. {Context.Guild!.GetMember(userDb.UserId)}",
                               $"{GetText(Localization.XpLevelX, RiasUtilities.XpToLevel(userDb.Xp, XpService.XpThreshold))} | {GetText(Localization.XpXp)} {userDb.Xp}",
                               true);
            }

            await ReplyAsync(embed);
        }
コード例 #17
0
        private async Task ConnectWebSocket(bool recheckPatrons = false)
        {
            while (true)
            {
                try
                {
                    await _webSocket !.ConnectAsync();
                    Log.Information("Patreon WebSocket connected");

                    if (recheckPatrons)
                    {
                        RiasUtilities.RunTask(CheckPatronsAsync);
                    }

                    break;
                }
                catch
                {
                    Log.Warning("Patreon WebSocket couldn't connect. Retrying in 10 seconds...");
                    await Task.Delay(10000);
                }
            }
        }
コード例 #18
0
ファイル: XpModule.cs プロジェクト: DiogenesTheGamer/RiasBot
        public async Task GlobalXpLeaderboardAsync(int page = 1)
        {
            page--;
            if (page < 0)
            {
                page = 0;
            }

            var xpLeaderboard = await DbContext.GetOrderedListAsync <UsersEntity, int>(x => x.Xp, true, (page * 15)..((page + 1) * 15));

            if (xpLeaderboard.Count == 0)
            {
                await ReplyErrorAsync(Localization.XpLeaderboardEmpty);

                return;
            }

            var embed = new LocalEmbedBuilder
            {
                Color = RiasUtilities.ConfirmColor,
                Title = GetText(Localization.XpLeaderboard)
            };

            var index = page * 15;

            foreach (var userDb in xpLeaderboard)
            {
                var user = (IUser)RiasBot.GetUser(userDb.UserId) ?? await RiasBot.GetUserAsync(userDb.UserId);

                embed.AddField($"{++index}. {user}",
                               $"{GetText(Localization.XpLevelX, RiasUtilities.XpToLevel(userDb.Xp, XpService.XpThreshold))} | {GetText(Localization.XpXp)} {userDb.Xp}",
                               true);
            }

            await ReplyAsync(embed);
        }
コード例 #19
0
        public async Task BackgroundAsync(string url)
        {
            var userDb = await DbContext.GetOrAddAsync(x => x.UserId == Context.User.Id, () => new UsersEntity { UserId = Context.User.Id });

            if (userDb.Currency < 1000)
            {
                await ReplyErrorAsync(Localization.GamblingCurrencyNotEnough, Credentials.Currency);

                return;
            }

            if (!Uri.TryCreate(url, UriKind.Absolute, out var backgroundUri))
            {
                await ReplyErrorAsync(Localization.UtilityUrlNotValid);

                Context.Command.ResetCooldowns();
                return;
            }

            if (backgroundUri.Scheme != Uri.UriSchemeHttps)
            {
                await ReplyErrorAsync(Localization.UtilityUrlNotHttps);

                Context.Command.ResetCooldowns();
                return;
            }

            using var _ = Context.Channel.Typing();

            using var result = await _httpClient.GetAsync(backgroundUri);

            if (!result.IsSuccessStatusCode)
            {
                await ReplyErrorAsync(Localization.UtilityImageOrUrlNotGood);

                Context.Command.ResetCooldowns();
                return;
            }

            await using var backgroundStream = await result.Content.ReadAsStreamAsync();

            if (!(RiasUtilities.IsPng(backgroundStream) || RiasUtilities.IsJpg(backgroundStream)))
            {
                await ReplyErrorAsync(Localization.UtilityUrlNotPngJpg);

                return;
            }

            var currentMember = Context.Guild !.CurrentMember;

            if (!currentMember.Permissions.AttachFiles)
            {
                await ReplyErrorAsync(Localization.ProfileBackgroundNoAttachFilesPermission);

                return;
            }

            if (!currentMember.GetPermissionsFor((CachedTextChannel)Context.Channel).AttachFiles)
            {
                await ReplyErrorAsync(Localization.ProfileBackgroundNoAttachFilesChannelPermission);

                return;
            }

            backgroundStream.Position      = 0;
            await using var profilePreview = await Service.GenerateProfileBackgroundAsync(Context.User, backgroundStream);

            await Context.Channel.SendMessageAsync(new[] { new LocalAttachment(profilePreview, $"{Context.User.Id}_profile_preview.png") }, GetText(Localization.ProfileBackgroundPreview));

            var messageReceived = await NextMessageAsync();

            if (!string.Equals(messageReceived?.Message.Content, GetText(Localization.CommonYes), StringComparison.InvariantCultureIgnoreCase))
            {
                await ReplyErrorAsync(Localization.ProfileBackgroundCanceled);

                return;
            }

            userDb.Currency -= 1000;

            var profileDb = await DbContext.GetOrAddAsync(x => x.UserId == Context.User.Id, () => new ProfileEntity { UserId = Context.User.Id, BackgroundDim = 50 });

            profileDb.BackgroundUrl = url;

            await DbContext.SaveChangesAsync();

            await ReplyConfirmationAsync(Localization.ProfileBackgroundSet);
        }
コード例 #20
0
            public async Task AddEmojiAsync(string url, [Remainder] string name)
            {
                if (!Uri.TryCreate(url, UriKind.Absolute, out var emojiUri))
                {
                    await ReplyErrorAsync(Localization.UtilityUrlNotValid);

                    return;
                }

                if (emojiUri.Scheme != Uri.UriSchemeHttps)
                {
                    await ReplyErrorAsync(Localization.UtilityUrlNotHttps);

                    return;
                }

                using var result = await _httpClient.GetAsync(emojiUri);

                if (!result.IsSuccessStatusCode)
                {
                    await ReplyErrorAsync(Localization.UtilityImageOrUrlNotGood);

                    return;
                }

                await using var stream = await result.Content.ReadAsStreamAsync();

                await using var emojiStream = new MemoryStream();
                await stream.CopyToAsync(emojiStream);

                emojiStream.Position = 0;

                bool?isAnimated = null;

                if (RiasUtilities.IsPng(emojiStream) || RiasUtilities.IsJpg(emojiStream))
                {
                    isAnimated = false;
                }

                if (!isAnimated.HasValue && RiasUtilities.IsGif(emojiStream))
                {
                    isAnimated = true;
                }

                if (!isAnimated.HasValue)
                {
                    await ReplyErrorAsync(Localization.UtilityUrlNotPngJpgGif);

                    return;
                }

                var emojis      = Context.Guild !.Emojis.Values;
                var emojisSlots = Context.Guild !.GetGuildEmotesSlots();

                if (isAnimated.Value)
                {
                    if (emojis.Count(x => x.IsAnimated) >= emojisSlots)
                    {
                        await ReplyErrorAsync(Localization.AdministrationAnimatedEmojisLimit, emojisSlots);

                        return;
                    }
                }
                else
                {
                    if (emojis.Count(x => !x.IsAnimated) >= emojisSlots)
                    {
                        await ReplyErrorAsync(Localization.AdministrationStaticEmojisLimit, emojisSlots);

                        return;
                    }
                }

                if (emojiStream.Length / 1024 > 256) //in KB
                {
                    await ReplyErrorAsync(Localization.AdministrationEmojiSizeLimit);

                    return;
                }

                name = name.Replace(" ", "_");
                emojiStream.Position = 0;
                await Context.Guild.CreateEmojiAsync(emojiStream, name);

                await ReplyConfirmationAsync(Localization.AdministrationEmojiCreated, name);
            }
コード例 #21
0
            public async Task SendAsync(string id, [Remainder] string message)
            {
                if (!id.StartsWith("u:", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (!ulong.TryParse(id, out var channelId))
                    {
                        await ReplyErrorAsync(Localization.AdministrationTextChannelNotFound);

                        return;
                    }

                    var channel = RiasBot.Client.ShardClients
                                  .SelectMany(x => x.Value.Guilds)
                                  .SelectMany(x => x.Value.Channels)
                                  .FirstOrDefault(x => x.Key == channelId).Value;

                    if (channel is null)
                    {
                        await ReplyErrorAsync(Localization.AdministrationTextChannelNotFound);

                        return;
                    }

                    if (channel.Type != ChannelType.Text && channel.Type != ChannelType.News && channel.Type != ChannelType.Store)
                    {
                        await ReplyErrorAsync(Localization.BotChannelNotTextChannel);

                        return;
                    }

                    var permissions = channel.Guild.CurrentMember.PermissionsIn(channel);
                    if (!permissions.HasPermission(Permissions.AccessChannels))
                    {
                        await ReplyErrorAsync(Localization.AdministrationTextChannelNoViewPermission);

                        return;
                    }

                    if (!permissions.HasPermission(Permissions.SendMessages))
                    {
                        await ReplyErrorAsync(Localization.BotTextChannelNoSendMessagesPermission);

                        return;
                    }

                    switch (RiasUtilities.TryParseMessage(message, out var customMessage))
                    {
                    case true when string.IsNullOrEmpty(customMessage.Content) && customMessage.Embed is null:
                        await ReplyErrorAsync(Localization.AdministrationNullCustomMessage);

                        return;

                    case true:
                        await channel.SendMessageAsync(customMessage.Content, customMessage.Embed);

                        break;

                    default:
                        await channel.SendMessageAsync(message);

                        break;
                    }

                    await ReplyConfirmationAsync(Localization.BotMessageSent);
                }
                else
                {
                    DiscordMember member;
                    if (ulong.TryParse(id[2..], out var userId) && RiasBot.Members.TryGetValue(userId, out var m))
コード例 #22
0
            public async Task AnimeAsync([Remainder] string title)
            {
                var(type, method) = int.TryParse(title, out _) ? ("Int", "id") : ("String", "search");
                var query = AnimeService.AnimeQuery.Replace("[type]", type)
                            .Replace("[var]", method);

                var anime = await Service.GetAniListInfoAsync <AnimeMangaContent>(query, new { anime = title }, "Media");

                if (anime is null)
                {
                    await ReplyErrorAsync(Localization.SearchesAnimeNotFound);

                    return;
                }

                var description = new StringBuilder(anime.Description);

                if (!string.IsNullOrEmpty(anime.Description))
                {
                    description.Replace("<br>", "");
                    description.Replace("<i>", "");
                    description.Replace("</i>", "");
                }

                if (description.Length == 0)
                {
                    description.Append('-');
                }

                var episodeDuration = anime.Duration.HasValue
                    ? TimeSpan.FromMinutes(anime.Duration.Value).Humanize(2, new CultureInfo(Localization.GetGuildLocale(Context.Guild?.Id)))
                    : "-";

                var startDate = "-";

                if (anime.StartDate.Year.HasValue && anime.StartDate.Month.HasValue && anime.StartDate.Day.HasValue)
                {
                    startDate = new DateTime(anime.StartDate.Year.Value, anime.StartDate.Month.Value, anime.StartDate.Day.Value)
                                .ToString("MMM dd, yyyy", CultureInfo.InvariantCulture);
                }

                var endDate = "-";

                if (anime.EndDate.Year.HasValue && anime.EndDate.Month.HasValue && anime.EndDate.Day.HasValue)
                {
                    endDate = new DateTime(anime.EndDate.Year.Value, anime.EndDate.Month.Value, anime.EndDate.Day.Value)
                              .ToString("MMM dd, yyyy", CultureInfo.InvariantCulture);
                }

                var genres = anime.Genres != null
                    ? anime.Genres.Length != 0
                        ? string.Join("\n", anime.Genres)
                        : "-"
                    : "-";

                var embed = new DiscordEmbedBuilder
                {
                    Color       = RiasUtilities.HexToInt(anime.CoverImage.Color) ?? RiasUtilities.ConfirmColor,
                    Url         = anime.SiteUrl,
                    Title       = $"{(string.IsNullOrEmpty(anime.Title.Romaji) ? anime.Title.English : anime.Title.Romaji)} (AniList)",
                    Description = $"{description.ToString().Truncate(1900)} [{GetText(Localization.CommonMore).ToLowerInvariant()}]({anime.SiteUrl})"
                }.AddField(GetText(Localization.SearchesTitleRomaji), !string.IsNullOrEmpty(anime.Title.Romaji) ? anime.Title.Romaji : "-", true)
                .AddField(GetText(Localization.SearchesTitleEnglish), !string.IsNullOrEmpty(anime.Title.English) ? anime.Title.English : "-", true)
                .AddField(GetText(Localization.SearchesTitleNative), !string.IsNullOrEmpty(anime.Title.Native) ? anime.Title.Native : "-", true)
                .AddField(GetText(Localization.CommonId), anime.Id.ToString(), true)
                .AddField(GetText(Localization.SearchesFormat), !string.IsNullOrEmpty(anime.Format) ? anime.Format : "-", true)
                .AddField(GetText(Localization.SearchesEpisodes), anime.Episodes.HasValue ? anime.Episodes.Value.ToString() : "-", true)
                .AddField(GetText(Localization.SearchesEpisodeDuration), episodeDuration, true)
                .AddField(GetText(Localization.UtilityStatus), !string.IsNullOrEmpty(anime.Status) ? anime.Status : "-", true)
                .AddField(GetText(Localization.SearchesStartDate), startDate, true)
                .AddField(GetText(Localization.SearchesEndDate), endDate, true)
                .AddField(GetText(Localization.SearchesSeason), !string.IsNullOrEmpty(anime.Season) ? anime.Season : "-", true)
                .AddField(GetText(Localization.SearchesAverageScore), anime.AverageScore.HasValue ? anime.AverageScore.Value.ToString() : "-", true)
                .AddField(GetText(Localization.SearchesMeanScore), anime.MeanScore.HasValue ? anime.MeanScore.Value.ToString() : "-", true)
                .AddField(GetText(Localization.SearchesPopularity), anime.Popularity.HasValue ? anime.Popularity.Value.ToString() : "-", true)
                .AddField(GetText(Localization.SearchesFavourites), anime.Favourites.HasValue ? anime.Favourites.Value.ToString() : "-", true)
                .AddField(GetText(Localization.SearchesSource), !string.IsNullOrEmpty(anime.Source) ? anime.Source : "-", true)
                .AddField(GetText(Localization.SearchesGenres), genres, true)
                .AddField(GetText(Localization.SearchesIsAdult), anime.IsAdult ? GetText(Localization.CommonYes) : GetText(Localization.CommonNo), true);

                switch (anime.IsAdult)
                {
                case true when Context.Channel.IsNSFW:
                case false:
                    embed.WithImageUrl(anime.CoverImage.ExtraLarge);
                    break;
                }

                await ReplyAsync(embed);
            }
コード例 #23
0
            public async Task MangaAsync([Remainder] string title)
            {
                var(type, method) = int.TryParse(title, out _) ? ("Int", "id") : ("String", "search");
                var query = AnimeService.MangaQuery.Replace("[type]", type)
                            .Replace("[var]", method);

                var manga = await Service.GetAniListInfoAsync <AnimeMangaContent>(query, new { manga = title }, "Media");

                if (manga is null)
                {
                    await ReplyErrorAsync(Localization.SearchesMangaNotFound);

                    return;
                }

                var description = new StringBuilder(manga.Description);

                if (!string.IsNullOrEmpty(manga.Description))
                {
                    description.Replace("<br>", "");
                    description.Replace("<i>", "");
                    description.Replace("</i>", "");
                }

                if (description.Length == 0)
                {
                    description.Append('-');
                }

                var startDate = "-";

                if (manga.StartDate.Year.HasValue && manga.StartDate.Month.HasValue && manga.StartDate.Day.HasValue)
                {
                    startDate = new DateTime(manga.StartDate.Year.Value, manga.StartDate.Month.Value, manga.StartDate.Day.Value)
                                .ToString("MMM dd, yyyy", CultureInfo.InvariantCulture);
                }

                var endDate = "-";

                if (manga.EndDate.Year.HasValue && manga.EndDate.Month.HasValue && manga.EndDate.Day.HasValue)
                {
                    endDate = new DateTime(manga.EndDate.Year.Value, manga.EndDate.Month.Value, manga.EndDate.Day.Value)
                              .ToString("MMM dd, yyyy", CultureInfo.InvariantCulture);
                }

                var synonyms = manga.Synonyms != null
                    ? manga.Synonyms.Length != 0
                        ? string.Join("\n", manga.Synonyms)
                        : "-"
                    : "-";

                var genres = manga.Genres != null
                    ? manga.Genres.Length != 0
                        ? string.Join("\n", manga.Genres)
                        : "-"
                    : "-";

                var embed = new DiscordEmbedBuilder
                {
                    Color       = RiasUtilities.HexToInt(manga.CoverImage.Color) ?? RiasUtilities.ConfirmColor,
                    Url         = manga.SiteUrl,
                    Title       = $"{(string.IsNullOrEmpty(manga.Title.Romaji) ? manga.Title.English : manga.Title.Romaji)} (AniList)",
                    Description = $"{description.ToString().Truncate(1900)} [{GetText(Localization.CommonMore).ToLowerInvariant()}]({manga.SiteUrl})"
                }.AddField(GetText(Localization.SearchesTitleRomaji), !string.IsNullOrEmpty(manga.Title.Romaji) ? manga.Title.Romaji : "-", true)
                .AddField(GetText(Localization.SearchesTitleEnglish), !string.IsNullOrEmpty(manga.Title.English) ? manga.Title.English : "-", true)
                .AddField(GetText(Localization.SearchesTitleNative), !string.IsNullOrEmpty(manga.Title.Native) ? manga.Title.Native : "-", true)
                .AddField(GetText(Localization.CommonId), manga.Id.ToString(), true)
                .AddField(GetText(Localization.SearchesFormat), !string.IsNullOrEmpty(manga.Format) ? manga.Format : "-", true)
                .AddField(GetText(Localization.SearchesChapters), manga.Chapters.HasValue ? manga.Chapters.Value.ToString() : "-", true)
                .AddField(GetText(Localization.SearchesVolumes), manga.Volumes.HasValue ? manga.Volumes.Value.ToString() : "-", true)
                .AddField(GetText(Localization.UtilityStatus), !string.IsNullOrEmpty(manga.Status) ? manga.Status : "-", true)
                .AddField(GetText(Localization.SearchesStartDate), startDate, true)
                .AddField(GetText(Localization.SearchesEndDate), endDate, true)
                .AddField(GetText(Localization.SearchesAverageScore), manga.AverageScore.HasValue ? manga.AverageScore.Value.ToString() : "-", true)
                .AddField(GetText(Localization.SearchesMeanScore), manga.MeanScore.HasValue ? manga.MeanScore.Value.ToString() : "-", true)
                .AddField(GetText(Localization.SearchesPopularity), manga.Popularity.HasValue ? manga.Popularity.Value.ToString() : "-", true)
                .AddField(GetText(Localization.SearchesFavourites), manga.Favourites.HasValue ? manga.Favourites.Value.ToString() : "-", true)
                .AddField(GetText(Localization.SearchesSource), !string.IsNullOrEmpty(manga.Source) ? manga.Source : "-", true)
                .AddField(GetText(Localization.SearchesGenres), genres, true)
                .AddField(GetText(Localization.SearchesSynonyms), synonyms, true)
                .AddField(GetText(Localization.SearchesIsAdult), manga.IsAdult.ToString(), true);

                switch (manga.IsAdult)
                {
                case true when Context.Channel.IsNSFW:
                case false:
                    embed.WithImageUrl(manga.CoverImage.ExtraLarge);
                    break;
                }

                await ReplyAsync(embed);
            }
コード例 #24
0
        public void LoadCredentials()
        {
            var config = new ConfigurationBuilder().AddJsonFile(_configurationPath).Build();

            Prefix = config.GetValue <string>(nameof(Prefix));
            Token  = config.GetValue <string>(nameof(Token));

            MasterId = config.GetValue <ulong>(nameof(MasterId));
            Currency = config.GetValue <string>(nameof(Currency));

            Invite            = config.GetValue <string>(nameof(Invite));
            OwnerServerInvite = config.GetValue <string>(nameof(OwnerServerInvite));
            OwnerServerId     = config.GetValue <ulong>(nameof(OwnerServerId));

            var confirmColor = RiasUtilities.HexToInt(config.GetValue <string>(nameof(RiasUtilities.ConfirmColor)));

            if (confirmColor.HasValue)
            {
                RiasUtilities.ConfirmColor = new DiscordColor(confirmColor.Value);
            }

            var errorColor = RiasUtilities.HexToInt(config.GetValue <string>(nameof(RiasUtilities.ErrorColor)));

            if (errorColor.HasValue)
            {
                RiasUtilities.ErrorColor = new DiscordColor(errorColor.Value);
            }

            Patreon        = config.GetValue <string>(nameof(Patreon));
            Website        = config.GetValue <string>(nameof(Website));
            DiscordBotList = config.GetValue <string>(nameof(DiscordBotList));

            UrbanDictionaryApiKey = config.GetValue <string>(nameof(UrbanDictionaryApiKey));
            ExchangeRateAccessKey = config.GetValue <string>(nameof(ExchangeRateAccessKey));
            DiscordBotListToken   = config.GetValue <string>(nameof(DiscordBotListToken));
            DiscordBotsToken      = config.GetValue <string>(nameof(DiscordBotsToken));
            WeebServicesToken     = config.GetValue <string>(nameof(WeebServicesToken));

            var databaseConfiguration = config.GetSection(nameof(DatabaseConfiguration));

            DatabaseConfiguration = !databaseConfiguration.Exists() ? null : new DatabaseConfiguration
            {
                Host            = databaseConfiguration.GetValue <string>(nameof(DatabaseConfiguration.Host)),
                Port            = databaseConfiguration.GetValue <ushort>(nameof(DatabaseConfiguration.Port)),
                Database        = databaseConfiguration.GetValue <string>(nameof(DatabaseConfiguration.Database)),
                Username        = databaseConfiguration.GetValue <string>(nameof(DatabaseConfiguration.Username)),
                Password        = databaseConfiguration.GetValue <string>(nameof(DatabaseConfiguration.Password)),
                ApplicationName = databaseConfiguration.GetValue <string>(nameof(DatabaseConfiguration.ApplicationName))
            };

            var votesConfiguration = config.GetSection(nameof(VotesConfiguration));

            VotesConfiguration = !votesConfiguration.Exists() ? null : new VotesConfiguration
            {
                WebSocketHost      = votesConfiguration.GetValue <string>(nameof(VotesConfiguration.WebSocketHost)),
                WebSocketPort      = votesConfiguration.GetValue <ushort>(nameof(VotesConfiguration.WebSocketPort)),
                IsSecureConnection = votesConfiguration.GetValue <bool>(nameof(VotesConfiguration.IsSecureConnection)),
                UrlParameters      = votesConfiguration.GetValue <string>(nameof(VotesConfiguration.UrlParameters)),
                Authorization      = votesConfiguration.GetValue <string>(nameof(VotesConfiguration.Authorization))
            };

            var patreonConfiguration = config.GetSection(nameof(PatreonConfiguration));

            PatreonConfiguration = !patreonConfiguration.Exists() ? null : new PatreonConfiguration
            {
                WebSocketHost      = patreonConfiguration.GetValue <string>(nameof(PatreonConfiguration.WebSocketHost)),
                WebSocketPort      = patreonConfiguration.GetValue <ushort>(nameof(PatreonConfiguration.WebSocketPort)),
                IsSecureConnection = patreonConfiguration.GetValue <bool>(nameof(PatreonConfiguration.IsSecureConnection)),
                UrlParameters      = patreonConfiguration.GetValue <string>(nameof(PatreonConfiguration.UrlParameters)),
                Authorization      = patreonConfiguration.GetValue <string>(nameof(PatreonConfiguration.Authorization))
            };
        }
コード例 #25
0
        private void AddInfo(MagickImage image, CachedMember member, ProfileInfo profileInfo)
        {
            var settings = new MagickReadSettings
            {
                BackgroundColor = MagickColors.Transparent,
                FillColor       = profileInfo.Color,
                Font            = _arialFontPath,
                FontPointsize   = 20,
                Width           = 125,
                TextGravity     = Gravity.Center
            };

            var segmentLength = 500 / 6;

            using var currencyImage = new MagickImage($"caption:{profileInfo.Currency}", settings);
            image.Draw(new DrawableComposite(segmentLength - (double)currencyImage.Width / 2, 280, CompositeOperator.Over, currencyImage));

            var waifusCount = profileInfo.Waifus !.Count;

            if (profileInfo.SpecialWaifu != null)
            {
                waifusCount++;
            }

            using var waifusImage = new MagickImage($"caption:{waifusCount}", settings);
            image.Draw(new DrawableComposite(segmentLength * 2 - (double)waifusImage.Width / 2, 280, CompositeOperator.Over, waifusImage));

            using var levelImage = new MagickImage($"caption:{profileInfo.Level}", settings);
            image.Draw(new DrawableComposite(segmentLength * 3 - (double)levelImage.Width / 2, 280, CompositeOperator.Over, levelImage));

            using var totalXpImage = new MagickImage($"caption:{profileInfo.Xp}", settings);
            image.Draw(new DrawableComposite(segmentLength * 4 - (double)totalXpImage.Width / 2, 280, CompositeOperator.Over, totalXpImage));

            using var rankImage = new MagickImage($"caption:{profileInfo.Rank}", settings);
            image.Draw(new DrawableComposite(segmentLength * 5 - (double)rankImage.Width / 2, 280, CompositeOperator.Over, rankImage));

            settings.FillColor     = MagickColors.White;
            settings.FontPointsize = 15;

            var guildId = member.Guild.Id;

            using var currencyTextImage = new MagickImage($"caption:{GetText(guildId, CurrencyLocalization)}", settings);
            image.Draw(new DrawableComposite(segmentLength - (double)currencyTextImage.Width / 2, 315, CompositeOperator.Over, currencyTextImage));

            using var waifusTextImage = new MagickImage($"caption:{GetText(guildId, Localization.WaifuWaifus)}", settings);
            image.Draw(new DrawableComposite(segmentLength * 2 - (double)waifusTextImage.Width / 2, 315, CompositeOperator.Over, waifusTextImage));

            using var levelTextImage = new MagickImage($"caption:{GetText(guildId, Localization.XpLevel)}", settings);
            image.Draw(new DrawableComposite(segmentLength * 3 - (double)levelTextImage.Width / 2, 315, CompositeOperator.Over, levelTextImage));

            using var totalXpTextImage = new MagickImage($"caption:{GetText(guildId, Localization.XpTotalXp)}", settings);
            image.Draw(new DrawableComposite(segmentLength * 4 - (double)totalXpTextImage.Width / 2, 315, CompositeOperator.Over, totalXpTextImage));

            using var rankTextImage = new MagickImage($"caption:{GetText(guildId, Localization.CommonRank)}", settings);
            image.Draw(new DrawableComposite(segmentLength * 5 - (double)rankTextImage.Width / 2, 315, CompositeOperator.Over, rankTextImage));

            image.Draw(new Drawables()
                       .RoundRectangle(50, 360, 450, 370, 5, 5)
                       .FillColor(_darker));

            var currentXp   = RiasUtilities.LevelXp(profileInfo.Level, profileInfo.Xp, XpService.XpThreshold);
            var nextLevelXp = (profileInfo.Level + 1) * 30;

            var xpBarLength = (double)currentXp / nextLevelXp * 400;

            image.Draw(new Drawables()
                       .RoundRectangle(50, 360, 50 + xpBarLength, 370, 5, 5)
                       .FillColor(profileInfo.Color));

            settings.Width    = 0;
            using var xpImage = new MagickImage($"caption:{currentXp}", settings);
            image.Draw(new DrawableComposite(50, 380, CompositeOperator.Over, xpImage));

            using var nextLevelXpImage = new MagickImage($"caption:{nextLevelXp}", settings);
            image.Draw(new DrawableComposite(450 - nextLevelXpImage.Width, 380, CompositeOperator.Over, nextLevelXpImage));

            image.Draw(new Drawables()
                       .RoundRectangle(25, 415, 475, 495, 10, 10)
                       .FillColor(_darker));

            settings.Font          = _meiryoFontPath;
            settings.FontPointsize = 12;
            settings.TextGravity   = Gravity.West;
            settings.Width         = 440;

            using var bioImage = new MagickImage($"caption:{profileInfo.Biography}", settings);
            image.Draw(new DrawableComposite(30, 420, CompositeOperator.Over, bioImage));
        }
コード例 #26
0
        private async Task SendGreetMessageAsync(GuildsEntity guildDb, CachedMember member)
        {
            if (guildDb is null)
            {
                return;
            }
            if (!guildDb.GreetNotification)
            {
                return;
            }
            if (string.IsNullOrEmpty(guildDb.GreetMessage))
            {
                return;
            }
            if (guildDb.GreetWebhookId == 0)
            {
                return;
            }

            var guild         = member.Guild;
            var currentMember = guild.CurrentMember;

            if (!currentMember.Permissions.ManageWebhooks)
            {
                return;
            }

            var guildWebhook = await guild.GetWebhookAsync(guildDb.GreetWebhookId);

            if (_webhooks.TryGetValue(guildDb.GreetWebhookId, out var webhook))
            {
                if (guildWebhook is null)
                {
                    _webhooks.TryRemove(guildDb.GreetWebhookId, out _);
                    webhook.Dispose();
                    await DisableGreetAsync(guild);

                    return;
                }
            }
            else
            {
                if (guildWebhook != null)
                {
                    webhook = new RestWebhookClient(guildWebhook);
                    _webhooks.TryAdd(guildWebhook.Id, webhook);
                }
                else
                {
                    await DisableGreetAsync(guild);

                    return;
                }
            }

            if (webhook is null)
            {
                return;
            }

            var greetMsg = ReplacePlaceholders(member, guildDb.GreetMessage);

            if (RiasUtilities.TryParseEmbed(greetMsg, out var embed))
            {
                await webhook.ExecuteAsync(embeds : new[] { embed.Build() });
            }
            else
            {
                await webhook.ExecuteAsync(greetMsg);
            }
        }
コード例 #27
0
        public async Task EditAsync([TextChannel] DiscordChannel channel, ulong messageId, [Remainder] string message)
        {
            var permissions = channel.Guild.CurrentMember.PermissionsIn(channel);

            if (!permissions.HasPermission(Permissions.AccessChannels))
            {
                await ReplyErrorAsync(Localization.AdministrationTextChannelNoViewPermission);

                return;
            }

            if (!permissions.HasPermission(Permissions.SendMessages))
            {
                await ReplyErrorAsync(Localization.BotTextChannelNoSendMessagesPermission);

                return;
            }

            var discordMessage = await channel.GetMessageAsync(messageId);

            if (discordMessage is null)
            {
                await ReplyErrorAsync(Localization.BotMessageNotFound);

                return;
            }

            if (discordMessage.MessageType != MessageType.Default)
            {
                await ReplyErrorAsync(Localization.BotMessageNotUserMessage);

                return;
            }

            if (discordMessage.Author.Id != channel.Guild.CurrentMember.Id)
            {
                await ReplyErrorAsync(Localization.BotMessageNotSelf);

                return;
            }

            switch (RiasUtilities.TryParseMessage(message, out var customMessage))
            {
            case true when string.IsNullOrEmpty(customMessage.Content) && customMessage.Embed is null:
                await ReplyErrorAsync(Localization.AdministrationNullCustomMessage);

                return;

            case true:
                await discordMessage.ModifyAsync(customMessage.Content, customMessage.Embed?.Build() ?? (Optional <DiscordEmbed>) default);

                break;

            default:
                await discordMessage.ModifyAsync(message);

                break;
            }

            await ReplyConfirmationAsync(Localization.BotMessageEdited);
        }
コード例 #28
0
            public async Task AddEmojiAsync(string emoji, [Remainder] string name)
            {
                var httpClient = HttpClient;

                await using var emojiStream = new MemoryStream();
                bool?isAnimated = null;

                if (RiasUtilities.TryParseEmoji(emoji, out var emojiId))
                {
                    var emojiUrl = string.Format(EmojiCdn, $"{emojiId}.gif");
                    var result   = await httpClient.GetAsync(emojiUrl);

                    isAnimated = true;

                    if (result.StatusCode == HttpStatusCode.UnsupportedMediaType)
                    {
                        emojiUrl = string.Format(EmojiCdn, $"{emojiId}.png");
                        result   = await httpClient.GetAsync(emojiUrl);

                        isAnimated = false;

                        if (!result.IsSuccessStatusCode)
                        {
                            return;
                        }
                    }

                    await using var stream = await result.Content.ReadAsStreamAsync();

                    await stream.CopyToAsync(emojiStream);

                    emojiStream.Position = 0;
                }

                if (!isAnimated.HasValue)
                {
                    if (!Uri.TryCreate(emoji, UriKind.Absolute, out var emojiUri))
                    {
                        await ReplyErrorAsync(Localization.UtilityUrlNotValid);

                        return;
                    }

                    if (emojiUri.Scheme != Uri.UriSchemeHttps)
                    {
                        await ReplyErrorAsync(Localization.UtilityUrlNotHttps);

                        return;
                    }

                    using var result = await httpClient.GetAsync(emojiUri);

                    if (!result.IsSuccessStatusCode)
                    {
                        await ReplyErrorAsync(Localization.UtilityImageOrUrlNotGood);

                        return;
                    }

                    await using var stream = await result.Content.ReadAsStreamAsync();

                    await stream.CopyToAsync(emojiStream);

                    emojiStream.Position = 0;

                    if (RiasUtilities.IsPng(emojiStream) || RiasUtilities.IsJpg(emojiStream))
                    {
                        isAnimated = false;
                    }

                    if (!isAnimated.HasValue && RiasUtilities.IsGif(emojiStream))
                    {
                        isAnimated = true;
                    }

                    if (!isAnimated.HasValue)
                    {
                        await ReplyErrorAsync(Localization.UtilityUrlNotPngJpgGif);

                        return;
                    }
                }

                var emojis      = Context.Guild !.Emojis.Values;
                var emojisSlots = Context.Guild !.GetGuildEmotesSlots();

                if (isAnimated.Value)
                {
                    if (emojis.Count(x => x.IsAnimated) >= emojisSlots)
                    {
                        await ReplyErrorAsync(Localization.AdministrationAnimatedEmojisLimit, emojisSlots);

                        return;
                    }
                }
                else
                {
                    if (emojis.Count(x => !x.IsAnimated) >= emojisSlots)
                    {
                        await ReplyErrorAsync(Localization.AdministrationStaticEmojisLimit, emojisSlots);

                        return;
                    }
                }

                // Check if length is bigger than 256 KB
                if (emojiStream.Length / 1024 > 256)
                {
                    await ReplyErrorAsync(Localization.AdministrationEmojiSizeLimit);

                    return;
                }

                name = name.Replace(" ", "_");
                emojiStream.Position = 0;
                await Context.Guild.CreateEmojiAsync(name, emojiStream);

                await ReplyConfirmationAsync(Localization.AdministrationEmojiCreated, name);
            }
コード例 #29
0
        public async Task BackgroundAsync(string url)
        {
            var userDb = await DbContext.GetOrAddAsync(x => x.UserId == Context.User.Id, () => new UserEntity { UserId = Context.User.Id });

            if (userDb.Currency < 1000)
            {
                await ReplyErrorAsync(Localization.GamblingCurrencyNotEnough, Configuration.Currency);

                return;
            }

            if (!Uri.TryCreate(url, UriKind.Absolute, out var backgroundUri))
            {
                await ReplyErrorAsync(Localization.UtilityUrlNotValid);

                Context.Command.ResetCooldowns();
                return;
            }

            if (backgroundUri.Scheme != Uri.UriSchemeHttps)
            {
                await ReplyErrorAsync(Localization.UtilityUrlNotHttps);

                Context.Command.ResetCooldowns();
                return;
            }

            await Context.Channel.TriggerTypingAsync();

            using var result = await HttpClient.GetAsync(backgroundUri);

            if (!result.IsSuccessStatusCode)
            {
                await ReplyErrorAsync(Localization.UtilityImageOrUrlNotGood);

                Context.Command.ResetCooldowns();
                return;
            }

            await using var backgroundStream = await result.Content.ReadAsStreamAsync();

            if (!(RiasUtilities.IsPng(backgroundStream) || RiasUtilities.IsJpg(backgroundStream)))
            {
                await ReplyErrorAsync(Localization.UtilityUrlNotPngJpg);

                return;
            }

            var serverAttachFilesPerm  = Context.Guild !.CurrentMember.GetPermissions().HasPermission(Permissions.AttachFiles);
            var channelAttachFilesPerm = Context.Guild !.CurrentMember.PermissionsIn(Context.Channel).HasPermission(Permissions.AttachFiles);

            if (!serverAttachFilesPerm && !channelAttachFilesPerm)
            {
                await ReplyErrorAsync(Localization.ProfileBackgroundNoAttachFilesPermission);

                return;
            }

            if (serverAttachFilesPerm && !channelAttachFilesPerm)
            {
                await ReplyErrorAsync(Localization.ProfileBackgroundNoAttachFilesChannelPermission);

                return;
            }

            backgroundStream.Position      = 0;
            await using var profilePreview = await Service.GenerateProfileBackgroundAsync(Context.User, backgroundStream);

            var componentInteractionArgs = await SendConfirmationButtonsAsync(new DiscordMessageBuilder()
                                                                              .WithEmbed(new DiscordEmbedBuilder
            {
                Color = RiasUtilities.Yellow,
                Description = GetText(Localization.ProfileBackgroundPreview),
                ImageUrl = $"attachment://{Context.User.Id}_profile_preview.png"
            })
                                                                              .WithFile($"{Context.User.Id}_profile_preview.png", profilePreview));

            if (componentInteractionArgs is null)
            {
                return;
            }

            userDb.Currency -= 1000;

            var profileDb = await DbContext.GetOrAddAsync(x => x.UserId == Context.User.Id, () => new ProfileEntity { UserId = Context.User.Id, BackgroundDim = 50 });

            profileDb.BackgroundUrl = url;

            await DbContext.SaveChangesAsync();

            await ButtonsActionModifyDescriptionAsync(componentInteractionArgs.Value.Result.Message, Localization.ProfileBackgroundSet);
        }
コード例 #30
0
        public override ValueTask <TypeParserResult <DiscordChannel> > ParseAsync(Parameter parameter, string value, RiasCommandContext context)
        {
            var localization = context.Services.GetRequiredService <Localization>();

            if (context.Guild is null)
            {
                return(TypeParserResult <DiscordChannel> .Failed(localization.GetText(context.Guild?.Id, Localization.TypeParserChannelNotGuild)));
            }

            var channelType = ChannelType.Unknown;
            HashSet <ChannelType>?ignoreChannelTypes = null;

            foreach (var attribute in parameter.Attributes)
            {
                switch (attribute)
                {
                case CategoryChannelAttribute:
                    channelType = ChannelType.Category;
                    break;

                case TextChannelAttribute:
                    channelType = ChannelType.Text;
                    break;

                case VoiceChannelAttribute:
                    channelType = ChannelType.Voice;
                    break;

                case IgnoreChannelTypesAttribute ignoreChannelTypeAttribute:
                    ignoreChannelTypes = ignoreChannelTypeAttribute.ChannelTypes;
                    break;
                }
            }

            if (channelType is not ChannelType.Unknown && ignoreChannelTypes is not null && ignoreChannelTypes.Contains(channelType))
            {
                throw new ArgumentException("The required channel type and the ignored channel type cannot be the same");
            }

            DiscordChannel?channel;

            if (RiasUtilities.TryParseChannelMention(value, out var channelId) || ulong.TryParse(value, out channelId))
            {
                channel = context.Guild.GetChannel(channelId);
                if (channel is not null)
                {
                    var allowChannel = channelType switch
                    {
                        ChannelType.Text => channel.Type is ChannelType.Text or ChannelType.News or ChannelType.Store,
                        ChannelType.Voice => channel.Type is ChannelType.Voice or ChannelType.Stage,
                        _ => channel.Type == channelType || channelType is ChannelType.Unknown
                    };

                    if (allowChannel)
                    {
                        return(ignoreChannelTypes is not null && ignoreChannelTypes.Contains(channel.Type)
                            ? TypeParserResult <DiscordChannel> .Failed(localization.GetText(context.Guild.Id, Localization.TypeParserChannelNotAllowed(channel.Type.ToString().ToLower())))
                            : TypeParserResult <DiscordChannel> .Successful(channel));
                    }
                }
            }
            else
            {
                channel = channelType switch
                {
                    ChannelType.Category => context.Guild.GetCategoryChannel(value),
                    ChannelType.Text => context.Guild.GetTextChannel(value),
                    ChannelType.Voice => context.Guild.GetVoiceChannel(value),
                    ChannelType.Unknown => ignoreChannelTypes is null
                        ? context.Guild.Channels
                    .OrderBy(c => c.Value.Position)
                    .FirstOrDefault(x => string.Equals(x.Value.Name, value, StringComparison.OrdinalIgnoreCase))
                    .Value
                        : context.Guild.Channels
                    .Where(c => !ignoreChannelTypes.Contains(c.Value.Type))
                    .OrderBy(c => c.Value.Position)
                    .FirstOrDefault(x => string.Equals(x.Value.Name, value, StringComparison.OrdinalIgnoreCase))
                    .Value
                };

                if (channel != null)
                {
                    return(TypeParserResult <DiscordChannel> .Successful(channel));
                }
            }

            return(channelType switch
            {
                ChannelType.Category => TypeParserResult <DiscordChannel> .Failed(localization.GetText(context.Guild.Id, Localization.AdministrationCategoryChannelNotFound)),
                ChannelType.Text => TypeParserResult <DiscordChannel> .Failed(localization.GetText(context.Guild.Id, Localization.AdministrationTextChannelNotFound)),
                ChannelType.Voice => TypeParserResult <DiscordChannel> .Failed(localization.GetText(context.Guild.Id, Localization.AdministrationVoiceChannelNotFound)),
                ChannelType.Unknown => TypeParserResult <DiscordChannel> .Failed(localization.GetText(context.Guild.Id, Localization.AdministrationChannelNotFound))
            });