Ejemplo n.º 1
0
    public static async Task <Channel> MatchChannel(this Context ctx)
    {
        if (!MentionUtils.TryParseChannel(ctx.PeekArgument(), out var id))
        {
            return(null);
        }

        var channel = await ctx.Cache.TryGetChannel(id);

        if (channel == null)
        {
            channel = await ctx.Rest.GetChannelOrNull(id);
        }
        if (channel == null)
        {
            return(null);
        }

        if (!DiscordUtils.IsValidGuildChannel(channel))
        {
            return(null);
        }

        ctx.PopArgument();
        return(channel);
    }
Ejemplo n.º 2
0
        public override ValueTask <TypeParserResult <SocketTextChannel> > ParseAsync(string value, VolteContext ctx)
        {
            SocketTextChannel channel = default;

            if (ulong.TryParse(value, out var id) || MentionUtils.TryParseChannel(value, out id))
            {
                channel = ctx.Client.GetChannel(id).Cast <SocketTextChannel>();
            }

            if (channel is null)
            {
                var match = ctx.Guild.TextChannels.Where(x => x.Name.EqualsIgnoreCase(value))
                            .ToList();
                if (match.Count > 1)
                {
                    return(Failure(
                               "Multiple channels found. Try mentioning the channel or using its ID."));
                }
                channel = match.First();
            }

            return(channel is null
                ? Failure("Channel not found.")
                : Success(channel));
        }
Ejemplo n.º 3
0
        public override Task <TypeParserResult <T> > ParseAsync(Parameter parameter, string value, ICommandContext context, IServiceProvider provider)
        {
            var _context = context as GuildContext;
            var results  = new Dictionary <ulong, GenericParseResult <T> >();
            var channels = _context.Guild.Channels;

            //By Mention (1.0)
            if (MentionUtils.TryParseChannel(value, out ulong id))
            {
                AddResult(results, _context.Guild.GetChannel(id) as T, 1.00f);
            }

            //By Id (0.9)
            if (ulong.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out id))
            {
                AddResult(results, _context.Guild.GetChannel(id) as T, 0.90f);
            }

            //By Name (0.7-0.8)
            foreach (var channel in channels.Where(x => string.Equals(value, x.Name, StringComparison.OrdinalIgnoreCase)))
            {
                AddResult(results, channel as T, channel.Name == value ? 0.80f : 0.70f);
            }

            if (results.Count > 0)
            {
                return(Task.FromResult(new TypeParserResult <T>(results.Values.OrderBy(a => a.Score).FirstOrDefault()?.Value)));
            }

            return(Task.FromResult(new TypeParserResult <T>("Channel not found.")));
        }
Ejemplo n.º 4
0
        private async void SetLoggingChannelInformation(string value)
        {
            if (!MentionUtils.TryParseChannel(value, out ulong parserId))
            {
                await ReplyAsync("Please pass in a valid channel!");

                return;
            }

            var parsedChannel = Context.Guild.GetTextChannel(parserId);

            if (parsedChannel == null)
            {
                await ReplyAsync("Please pass in a valid channel!");

                return;
            }

            await _servers.ModifyLoggingChannel(Context.Guild.Id, parserId);

            await ReplyAsync($"Successfully modified the logging channel to {parsedChannel.Mention}");

            var perms = Context.Guild.CurrentUser.GetPermissions(parsedChannel);

            if (!perms.SendMessages)
            {
                await ReplyAsync("`Warning` the bot does not have permisson to send messages to the logging channel!");
            }

            _logger.LogInformation("{user} set the logging channel to {value} for {server}",
                                   Context.User.Username, value, Context.Guild.Name);
        }
Ejemplo n.º 5
0
        public async Task AddLimit(string value = null)
        {
            await Context.Channel.TriggerTypingAsync();

            if (value != null)
            {
                if (!MentionUtils.TryParseChannel(value, out ulong parsedId))
                {
                    await Context.Channel.SendErrorAsync("Channel Limits", "Please pass in a valid channel!");

                    return;
                }
                var parsedChannel = Context.Guild.GetTextChannel(parsedId);
                if (parsedChannel == null)
                {
                    await Context.Channel.SendErrorAsync("Channel Limits", "Please pass in a valid channel!");

                    return;
                }
                await _limits.AddLimitAsync(Context.Guild.Id, parsedId);

                await _serverHelper.SendLogAsync(Context.Guild, "Situation Log", $"{Context.User.Mention} added {parsedChannel.Mention} to the list of limited channels!");

                await Context.Channel.SendSuccessAsync("Channel Limits", $"Successfully limited the bot to {parsedChannel.Mention}.");
            }
        }
Ejemplo n.º 6
0
        public override ValueTask <TypeParserResult <SocketTextChannel> > ParseAsync(
            Parameter param,
            string value,
            CommandContext context)
        {
            var ctx = context.Cast <VolteContext>();
            SocketTextChannel channel = default;

            if (ulong.TryParse(value, out var id) || MentionUtils.TryParseChannel(value, out id))
            {
                channel = ctx.Client.GetChannel(id).Cast <SocketTextChannel>();
            }

            if (channel is null)
            {
                var match = ctx.Guild.TextChannels.Where(x => x.Name.EqualsIgnoreCase(value))
                            .ToList();
                if (match.Count > 1)
                {
                    return(TypeParserResult <SocketTextChannel> .Failed(
                               "Multiple channels found. Try mentioning the channel or using its ID."));
                }
            }

            return(channel is null
                ? TypeParserResult <SocketTextChannel> .Failed("Channel not found.")
                : TypeParserResult <SocketTextChannel> .Successful(channel));
        }
Ejemplo n.º 7
0
        public override async ValueTask <TypeReaderResponse> Read(IMessageContext context, string input)
        {
            if (context.Guild != null)
            {
                var results  = new Dictionary <ulong, TypeReaderValue>();
                var channels = await context.Guild.GetChannelsAsync();

                ulong id;

                //By Mention (1.0)
                if (MentionUtils.TryParseChannel(input, out id))
                {
                    AddResult(results, channels.Where(c => c.Id == id).FirstOrDefault() as T, 1.0f);
                }

                //By Id (0.9)
                if (ulong.TryParse(input, NumberStyles.None, CultureInfo.InvariantCulture, out id))
                {
                    AddResult(results, channels.Where(c => c.Id == id).FirstOrDefault() as T, 0.90f);
                }

                //By Name (0.7-0.8)
                foreach (var channel in channels.Where(x => string.Equals(input, x.Name, StringComparison.OrdinalIgnoreCase)))
                {
                    AddResult(results, channel as T, channel.Name == input ? 0.80f : 0.70f);
                }

                if (results.Count > 0)
                {
                    return(TypeReaderResponse.FromSuccess(results.Values));
                }
            }

            return(TypeReaderResponse.FromError(TYPEREADER_ENTITY_NOTFOUND, input, typeof(T)));
        }
Ejemplo n.º 8
0
        public override async Task <TypeParserResult <TChannel> > ParseAsync(
            Parameter param,
            string value,
            ICommandContext context,
            IServiceProvider provider)
        {
            var      ctx     = (DepressedBotContext)context;
            TChannel channel = null;

            if (ulong.TryParse(value, out var id) || MentionUtils.TryParseChannel(value, out id))
            {
                channel = (await ctx.Guild.GetTextChannelsAsync()).FirstOrDefault(x => x.Id == id) as TChannel;
            }

            if (channel is null)
            {
                var match = (await ctx.Guild.GetTextChannelsAsync()).Where(x => x.Name.EqualsIgnoreCase(value))
                            .ToList();
                if (match.Count > 1)
                {
                    return(TypeParserResult <TChannel> .Unsuccessful(
                               "Multiple channels found. Try mentioning the channel or using its ID."));
                }
            }

            return(channel is null
                ? TypeParserResult <TChannel> .Unsuccessful("Channel not found.")
                : TypeParserResult <TChannel> .Successful(channel));
        }
Ejemplo n.º 9
0
        public async Task <DiscordChannel> MatchChannel()
        {
            if (!MentionUtils.TryParseChannel(PeekArgument(), out var channel))
            {
                return(null);
            }

            try
            {
                var discordChannel = await _shard.GetChannelAsync(channel);

                if (discordChannel.Type != ChannelType.Text)
                {
                    return(null);
                }

                PopArgument();
                return(discordChannel);
            }
            catch (NotFoundException)
            {
                return(null);
            }
            catch (UnauthorizedException)
            {
                return(null);
            }
        }
Ejemplo n.º 10
0
        public override ValueTask <TypeParserResult <ITextChannel> > ParseAsync(Parameter param, string value, ScrapContext context)
        {
            var          channels = context.Guild.Channels.OfType <ITextChannel>().ToList();
            ITextChannel channel  = null;

            if (ulong.TryParse(value, out ulong id) || MentionUtils.TryParseChannel(value, out id))
            {
                channel = context.Client.GetChannel(id) as ITextChannel;
            }

            if (channel is null)
            {
                var match = channels.Where(x =>
                                           x.Name.EqualsIgnoreCase(value));
                if (match.Count() > 1)
                {
                    return(TypeParserResult <ITextChannel> .Unsuccessful(
                               "Multiple channels found, try mentioning the channel or using its ID."));
                }

                channel = match.FirstOrDefault();
            }
            return(channel is null
                ? TypeParserResult <ITextChannel> .Unsuccessful("User not found.")
                : TypeParserResult <ITextChannel> .Successful(channel));
        }
Ejemplo n.º 11
0
        public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
        {
            if (context.Guild != null)
            {
                var results  = new Dictionary <ulong, TypeReaderValue>();
                var channels = await context.Guild.GetChannelsAsync(CacheMode.CacheOnly).ConfigureAwait(false);

                ulong id;

                //By Mention (1.0)
                if (MentionUtils.TryParseChannel(input, out id))
                {
                    AddResult(results, await context.Guild.GetChannelAsync(id, CacheMode.CacheOnly).ConfigureAwait(false) as T, 1.00f);
                }

                //By Id (0.9)
                if (ulong.TryParse(input, NumberStyles.None, CultureInfo.InvariantCulture, out id))
                {
                    AddResult(results, await context.Guild.GetChannelAsync(id, CacheMode.CacheOnly).ConfigureAwait(false) as T, 0.90f);
                }

                //By Name (0.7-0.8)
                foreach (var channel in channels.Where(x => string.Equals(input, x.Name, StringComparison.OrdinalIgnoreCase)))
                {
                    AddResult(results, channel as T, channel.Name == input ? 0.80f : 0.70f);
                }

                if (results.Count > 0)
                {
                    return(TypeReaderResult.FromSuccess(results.Values.ToReadOnlyCollection()));
                }
            }

            return(TypeReaderResult.FromError(CommandError.ObjectNotFound, "Channel not found."));
        }
Ejemplo n.º 12
0
        public override Task <TypeParserResult <TChannel> > ParseAsync(Parameter parameter, string value, ICommandContext ctx, IServiceProvider provider)
        {
            var context = (AdminCommandContext)ctx;

            if (context.IsPrivate)
            {
                return(Task.FromResult(TypeParserResult <TChannel> .Unsuccessful("requirecontext_guild")));
            }

            TChannel channel = null;
            IEnumerable <TChannel> channels;

            if (typeof(SocketVoiceChannel).IsAssignableFrom(typeof(TChannel)))
            {
                channels = context.Guild.VoiceChannels.OfType <TChannel>().ToList();
            }
            else if (typeof(SocketCategoryChannel).IsAssignableFrom(typeof(TChannel)))
            {
                channels = context.Guild.CategoryChannels.OfType <TChannel>().ToList();
            }
            else if (typeof(SocketTextChannel).IsAssignableFrom(typeof(TChannel)))
            {
                channels = context.Guild.TextChannels.OfType <TChannel>().ToList();
            }
            else
            {
                channels = context.Guild.Channels.OfType <TChannel>().ToList();
            }

            // Parse by channel ID (or text channel mention)
            if (ulong.TryParse(value, out var id) || MentionUtils.TryParseChannel(value, out id))
            {
                channel = channels.FirstOrDefault(x => x.Id == id);
            }

            // Parse by channel name
            if (channel is null)
            {
                var matchingChannels = channels
                                       .Where(x => x.Name.Equals(value, StringComparison.OrdinalIgnoreCase))
                                       .ToList();

                if (matchingChannels.Count > 1)
                {
                    return(Task.FromResult(
                               TypeParserResult <TChannel> .Unsuccessful(context.Localize("channelparser_multiple"))));
                }

                channel = matchingChannels.FirstOrDefault();
            }

            return(Task.FromResult(!(channel is null)
                ? TypeParserResult <TChannel> .Successful(channel)
                : TypeParserResult <TChannel> .Unsuccessful(context.Localize("channelparser_notfound"))));
        }
Ejemplo n.º 13
0
        public async Task DelLimit(string value = null)
        {
            await Context.Channel.TriggerTypingAsync();

            var limits = await _limits.GetLimitsAsync(Context.Guild.Id);

            var hasLimit = await _servers.GetHasLimitAsync(Context.Guild.Id);

            try
            {
                if (hasLimit == true)
                {
                    await ReplyAsync("You can't delete limit channel while limit mode is active!");

                    return;
                }

                if (value != null)
                {
                    if (!MentionUtils.TryParseChannel(value, out ulong parsedId))
                    {
                        await Context.Channel.SendErrorAsync("Channel Limits", "Please pass in a valid channel!");

                        return;
                    }
                    var parsedChannel = Context.Guild.GetTextChannel(parsedId);
                    if (parsedChannel == null)
                    {
                        await Context.Channel.SendErrorAsync("Channel Limits", "Please pass in a valid channel!");

                        return;
                    }
                    if (limits.All(x => x.ChannelId != parsedChannel.Id))
                    {
                        await Context.Channel.TriggerTypingAsync();

                        await Context.Channel.SendErrorAsync("Channel Limits", "That channel is not a limited channel!");

                        return;
                    }

                    await _limits.RemoveLimitAsync(Context.Guild.Id, parsedId);

                    await _serverHelper.SendLogAsync(Context.Guild, "Situation Log", $"{Context.User.Mention} removed {parsedChannel.Mention} from the limited channel list!");

                    await Context.Channel.SendSuccessAsync("Channel Limits", $"Successfully removed {parsedChannel.Mention} from the limited channels.");
                }
            }
            catch (Exception e)
            {
                await Context.Channel.SendErrorAsync("Error", $"Something went wrong: ```{e.ToString()}```");
            }
        }
        public static async Task <DiscordChannel> MatchChannel(this Context ctx)
        {
            if (!MentionUtils.TryParseChannel(ctx.PeekArgument(), out var id))
            {
                return(null);
            }

            var channel = await ctx.Shard.GetChannel(id);

            if (channel == null || channel.Type != ChannelType.Text)
            {
                return(null);
            }

            ctx.PopArgument();
            return(channel);
        }
Ejemplo n.º 15
0
        public async Task AutoClear(string channelName)
        {
            guild     = Context.Guild;
            guildName = guild.Name;
            ulong channelID;

            if (MentionUtils.TryParseChannel(channelName, out channelID))
            {
                SocketTextChannel channel = guild.GetTextChannel(channelID);

                await ToggleChannel(channel);
            }
            else
            {
                await ReplyAsync(string.Format(ResponseManager.GetLine("ClearedChannelsNotExist"), guildName, channelName));
            }
        }
Ejemplo n.º 16
0
        public static IEnumerable <SocketUser> ParseUsers(DiscordSocketClient discord, string text, SocketGuild guild)
        {
            if (guild != null)
            {
                ulong roleId;
                if (MentionUtils.TryParseRole(text, out roleId))
                {
                    return(guild.Users.Where(u => u.Roles.Any(r => r.Id == roleId)));
                }
            }
            ulong channelId;

            if (MentionUtils.TryParseChannel(text, out channelId))
            {
                return(discord.GetChannel(channelId).Users);
            }
            var user = ParseUser(discord, text);

            return(user != null ? new[] { user } : null);
        }
Ejemplo n.º 17
0
        public static async Task <Channel> MatchChannel(this Context ctx)
        {
            if (!MentionUtils.TryParseChannel(ctx.PeekArgument(), out var id))
            {
                return(null);
            }

            if (!ctx.Cache.TryGetChannel(id, out var channel))
            {
                return(null);
            }

            if (!(channel.Type == Channel.ChannelType.GuildText || channel.Type == Channel.ChannelType.GuildText))
            {
                return(null);
            }

            ctx.PopArgument();
            return(channel);
        }
Ejemplo n.º 18
0
        public static Task <Channel> MatchChannel(this Context ctx)
        {
            if (!MentionUtils.TryParseChannel(ctx.PeekArgument(), out var id))
            {
                return(Task.FromResult <Channel>(null));
            }

            if (!ctx.Cache.TryGetChannel(id, out var channel))
            {
                return(Task.FromResult <Channel>(null));
            }

            if (!DiscordUtils.IsValidGuildChannel(channel))
            {
                return(Task.FromResult <Channel>(null));
            }

            ctx.PopArgument();
            return(Task.FromResult(channel));
        }
Ejemplo n.º 19
0
        public override ValueTask <TypeParserResult <SocketTextChannel> > ParseAsync(Parameter parameter, string value,
                                                                                     SocketCommandContext context, IServiceProvider provider)
        {
            if (MentionUtils.TryParseChannel(value, out var id))
            {
                return(context.Guild.GetChannel(id) is SocketTextChannel txCh
                    ? TypeParserResult <SocketTextChannel> .Successful(txCh)
                    : TypeParserResult <SocketTextChannel> .Unsuccessful("Couldn't parse text channel"));
            }

            if (ulong.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out id))
            {
                return(context.Guild.GetTextChannel(id) is SocketTextChannel txCh
                    ? TypeParserResult <SocketTextChannel> .Successful(txCh)
                    : TypeParserResult <SocketTextChannel> .Unsuccessful("Couldn't parse text channel"));
            }

            return(context.Guild.TextChannels.FirstOrDefault(x => x.Name == value) is SocketTextChannel txChCheck
                ? TypeParserResult <SocketTextChannel> .Successful(txChCheck)
                : TypeParserResult <SocketTextChannel> .Unsuccessful("Couldn't parse text channel"));
        }
        /// <summary>
        ///     Tries to parses a given string as a channel.
        /// </summary>
        /// <remarks>
        ///     See flow chart by Still#2876:
        ///     https://cdn.discordapp.com/attachments/381889909113225237/409209957683036160/ChannelTypeReader.png
        /// </remarks>
        /// <param name="guild">The guild in which to search for the channel.</param>
        /// <param name="input">A string representing a channel by mention, id, or name.</param>
        /// <returns>The results of the parse.</returns>
        public static async Task <TypeReaderResult> ReadAsync(IGuild guild, string input)
        {
            if (guild != null)
            {
                var results  = new Dictionary <ulong, TypeReaderValue>();
                var channels = await guild.GetChannelsAsync(CacheMode.CacheOnly).ConfigureAwait(false);

                ulong id;

                // By Mention (1.0)
                if (MentionUtils.TryParseChannel(input, out id))
                {
                    AddResult(results, await guild.GetChannelAsync(id, CacheMode.CacheOnly).ConfigureAwait(false) as T,
                              1.00f);
                }

                // By Id (0.9)
                if (ulong.TryParse(input, NumberStyles.None, CultureInfo.InvariantCulture, out id))
                {
                    AddResult(results, await guild.GetChannelAsync(id, CacheMode.CacheOnly).ConfigureAwait(false) as T,
                              0.90f);
                }

                // By Name (0.7-0.8)
                // Acounts for name being null because GetChannelsAsync returns categories in 1.0.
                foreach (var channel in channels.Where(c =>
                                                       c.Name?.Equals(input, StringComparison.OrdinalIgnoreCase) ?? false))
                {
                    AddResult(results, channel as T, channel.Name == input ? 0.80f : 0.70f);
                }

                if (results.Count > 0)
                {
                    return(TypeReaderResult.FromSuccess(results.Values));
                }
            }

            return(TypeReaderResult.FromError(CommandError.ObjectNotFound, "Channel not found."));
        }
Ejemplo n.º 21
0
        public async Task Welcome(string option = null, string value = null)
        {
            await Context.Channel.TriggerTypingAsync();

            if (option == null && value == null)
            {
                var fetchedChannelId = await _servers.GetWelcomeAsync(Context.Guild.Id);

                if (fetchedChannelId == 0)
                {
                    await Context.Channel.SendErrorAsync("Welcome module", "There has not been set a welcome channel yet!");

                    return;
                }

                var fetchedChannel = Context.Guild.GetTextChannel(fetchedChannelId);
                if (fetchedChannel == null)
                {
                    await Context.Channel.SendErrorAsync("Welcome module", "There has not been set a welcome channel yet!");

                    await _servers.ClearWelcomeAsync(Context.Guild.Id);

                    return;
                }

                var fetchedBackground = await _servers.GetBackgroundAsync(Context.Guild.Id);

                if (fetchedBackground != null)
                {
                    await Context.Channel.SendSuccessAsync("Welcome module", $"The channel used for the welcome module is {fetchedChannel.Mention}.\nThe background is set to {fetchedBackground}.");
                }
                else
                {
                    await Context.Channel.SendSuccessAsync("Welcome module", $"The channel used for the welcome module is {fetchedChannel.Mention}.");
                }

                return;
            }

            if (option == "channel" && value != null)
            {
                if (!MentionUtils.TryParseChannel(value, out ulong parsedId))
                {
                    await Context.Channel.SendErrorAsync("Welcome module", "Please pass in a valid channel!");

                    return;
                }

                var parsedChannel = Context.Guild.GetTextChannel(parsedId);
                if (parsedChannel == null)
                {
                    await Context.Channel.SendErrorAsync("Welcome module", "Please pass in a valid channel!");

                    return;
                }

                await _servers.ModifyWelcomeAsync(Context.Guild.Id, parsedId);

                await Context.Channel.SendSuccessAsync("Welcome module", $"Successfully modified the welcome channel to {parsedChannel.Mention}.");

                await _serverHelper.SendLogAsync(Context.Guild, "Situation Log", $"{Context.User.Mention} modified the welcome channel to {parsedChannel.Mention}!");

                return;
            }

            if (option == "background" && value != null)
            {
                if (value == "clear")
                {
                    await _servers.ClearBackgroundAsync(Context.Guild.Id);

                    await Context.Channel.SendSuccessAsync("Welcome module", "Successfully cleared the background for this server.");

                    await _serverHelper.SendLogAsync(Context.Guild, "Situation Log", $"{Context.User.Mention} cleared the welcome channel!");

                    return;
                }

                await _servers.ModifyBackgroundAsync(Context.Guild.Id, value);

                await Context.Channel.SendSuccessAsync("Welcome module", $"Successfully modified the background to {value}.");

                return;
            }

            if (option == "clear" && value == null)
            {
                await _servers.ClearWelcomeAsync(Context.Guild.Id);

                await Context.Channel.SendSuccessAsync("Welcome module", "Successfully cleared the welcome channel.");

                return;
            }
            await Context.Channel.SendErrorAsync("Welcome module", "You did not use this command properly!");
        }
Ejemplo n.º 22
0
        public static ImmutableArray <ITag> ParseTags(string text, IMessageChannel channel, IGuild guild, IReadOnlyCollection <IUser> userMentions)
        {
            var tags      = ImmutableArray.CreateBuilder <ITag>();
            int index     = 0;
            var codeIndex = 0;

            // checks if the tag being parsed is wrapped in code blocks
            bool CheckWrappedCode()
            {
                // util to check if the index of a tag is within the bounds of the codeblock
                bool EnclosedInBlock(Match m)
                => m.Groups[1].Index < index && index < m.Groups[2].Index;

                // loop through all code blocks that are before the start of the tag
                while (codeIndex < index)
                {
                    var blockMatch = BlockCodeRegex.Match(text, codeIndex);
                    if (blockMatch.Success)
                    {
                        if (EnclosedInBlock(blockMatch))
                        {
                            return(true);
                        }
                        // continue if the end of the current code was before the start of the tag
                        codeIndex += blockMatch.Groups[2].Index + blockMatch.Groups[2].Length;
                        if (codeIndex < index)
                        {
                            continue;
                        }
                        return(false);
                    }
                    var inlineMatch = InlineCodeRegex.Match(text, codeIndex);
                    if (inlineMatch.Success)
                    {
                        if (EnclosedInBlock(inlineMatch))
                        {
                            return(true);
                        }
                        // continue if the end of the current code was before the start of the tag
                        codeIndex += inlineMatch.Groups[2].Index + inlineMatch.Groups[2].Length;
                        if (codeIndex < index)
                        {
                            continue;
                        }
                        return(false);
                    }
                    return(false);
                }
                return(false);
            }

            while (true)
            {
                index = text.IndexOf('<', index);
                if (index == -1)
                {
                    break;
                }
                int endIndex = text.IndexOf('>', index + 1);
                if (endIndex == -1)
                {
                    break;
                }
                if (CheckWrappedCode())
                {
                    break;
                }
                string content = text.Substring(index, endIndex - index + 1);

                if (MentionUtils.TryParseUser(content, out ulong id))
                {
                    IUser mentionedUser = null;
                    foreach (var mention in userMentions)
                    {
                        if (mention.Id == id)
                        {
                            mentionedUser = channel?.GetUserAsync(id, CacheMode.CacheOnly).GetAwaiter().GetResult();
                            if (mentionedUser == null)
                            {
                                mentionedUser = mention;
                            }
                            break;
                        }
                    }
                    tags.Add(new Tag <IUser>(TagType.UserMention, index, content.Length, id, mentionedUser));
                }
                else if (MentionUtils.TryParseChannel(content, out id))
                {
                    IChannel mentionedChannel = null;
                    if (guild != null)
                    {
                        mentionedChannel = guild.GetChannelAsync(id, CacheMode.CacheOnly).GetAwaiter().GetResult();
                    }
                    tags.Add(new Tag <IChannel>(TagType.ChannelMention, index, content.Length, id, mentionedChannel));
                }
                else if (MentionUtils.TryParseRole(content, out id))
                {
                    IRole mentionedRole = null;
                    if (guild != null)
                    {
                        mentionedRole = guild.GetRole(id);
                    }
                    tags.Add(new Tag <IRole>(TagType.RoleMention, index, content.Length, id, mentionedRole));
                }
                else if (Emote.TryParse(content, out var emoji))
                {
                    tags.Add(new Tag <Emote>(TagType.Emoji, index, content.Length, emoji.Id, emoji));
                }
                else //Bad Tag
                {
                    index++;
                    continue;
                }
                index = endIndex + 1;
            }

            index     = 0;
            codeIndex = 0;
            while (true)
            {
                index = text.IndexOf("@everyone", index);
                if (index == -1)
                {
                    break;
                }
                if (CheckWrappedCode())
                {
                    break;
                }
                var tagIndex = FindIndex(tags, index);
                if (tagIndex.HasValue)
                {
                    tags.Insert(tagIndex.Value, new Tag <IRole>(TagType.EveryoneMention, index, "@everyone".Length, 0, guild?.EveryoneRole));
                }
                index++;
            }

            index     = 0;
            codeIndex = 0;
            while (true)
            {
                index = text.IndexOf("@here", index);
                if (index == -1)
                {
                    break;
                }
                if (CheckWrappedCode())
                {
                    break;
                }
                var tagIndex = FindIndex(tags, index);
                if (tagIndex.HasValue)
                {
                    tags.Insert(tagIndex.Value, new Tag <IRole>(TagType.HereMention, index, "@here".Length, 0, guild?.EveryoneRole));
                }
                index++;
            }

            return(tags.ToImmutable());
        }
Ejemplo n.º 23
0
        public async Task Logs(string value = null)
        {
            if (value == null)
            {
                var fetchedChannelId = await _servers.GetLogsAsync(Context.Guild.Id);

                if (fetchedChannelId == 0)
                {
                    await Context.Channel.SendErrorAsync("Error", "There has not been set a logs channel yet!");

                    return;
                }

                var fetchedChannel = Context.Guild.GetTextChannel(fetchedChannelId);
                if (fetchedChannel == null)
                {
                    await Context.Channel.SendErrorAsync("Error", "There has not been set a logs channel yet!");

                    await _servers.ClearLogsAsync(Context.Guild.Id);

                    return;
                }

                await ReplyAsync($"The channel used for the logs is set to {fetchedChannel.Mention}.");

                return;
            }

            if (value != "clear")
            {
                if (!MentionUtils.TryParseChannel(value, out var parsedId))
                {
                    await Context.Channel.SendErrorAsync("Error", "Please pass in a valid channel!");

                    return;
                }

                var parsedChannel = Context.Guild.GetTextChannel(parsedId);
                if (parsedChannel == null)
                {
                    await ReplyAsync("Please pass in a valid channel!");

                    return;
                }

                await _servers.ModifyLogsAsync(Context.Guild.Id, parsedId);

                await Context.Channel.SendSuccessAsync("Success",
                                                       $"Successfully modified the logs channel to {parsedChannel.Mention}.");

                return;
            }

            if (value == "clear")
            {
                await _servers.ClearLogsAsync(Context.Guild.Id);

                await Context.Channel.SendSuccessAsync("Success", "Successfully cleared the logs channel.");

                return;
            }

            await Context.Channel.SendErrorAsync("Error", "You did not use this command properly.");
        }