Example #1
0
        public async Task <DiscordCommandResult> GetRepoAsync([Name("Repository")] string repoName)
        {
            var details = repoName.Split("/");

            if (details.Length < 2)
            {
                return(Response("It seems like you haven't provided a suitable repo name."));
            }

            try
            {
                var result = await _lexGithubClient.Repository.Get(details[0], details[1]);

                var eb = new LexEmbed()
                         .WithTitle(result.Name)
                         .WithDescription(result.Description)
                         .AddField("Language", result.Language)
                         .AddField("Source", Markdown.Link("Github", result.HtmlUrl));

                return(Response(eb));
            }
            catch (NotFoundException)
            {
                return(NotFoundResponse("repository"));
            }
        }
Example #2
0
        public async Task <DiscordCommandResult> GetIssueAsync(
            [Name("Repo Id"), Description("The Id of the repository where the issue is")] long repoId,
            [Name("Issue Number"), Description("The issue number")] int issueNumber)
        {
            try
            {
                var result = await _lexGithubClient.Issue.Get(repoId, issueNumber);

                var resultText = result.Body.CutIfLong();
                var userText   = result.User.Name ?? result.User.Login;

                var eb = new LexEmbed()
                         .WithTitle(result.Title)
                         .WithUrl(result.HtmlUrl)
                         .WithDescription(resultText)
                         .AddField("Created By", userText)
                         .AddField(result.Repository.Name, Markdown.Link("GitHub", result.Repository.HtmlUrl));

                return(Response(eb));
            }
            catch (NotFoundException)
            {
                return(NotFoundResponse("issue"));
            }
        }
Example #3
0
        public async Task <DiscordCommandResult> GetIssueAsync(
            [Name("Owner Name"), Description("The owner of the repository where the issue is")] string ownerName,
            [Description("The name of the repository")] string name,
            [Description("The issue number")] int issueNumber)
        {
            try
            {
                var result = await _lexGithubClient.Issue.Get(ownerName, name, issueNumber);

                var resultText = result.Body.CutIfLong();
                var userText   = result.User.Name ?? result.User.Login;

                var eb = new LexEmbed()
                         .WithTitle(result.Title)
                         .WithUrl(result.HtmlUrl)
                         .WithDescription(resultText)
                         .AddField("Created By", userText);

                return(Response(eb));
            }
            catch (NotFoundException)
            {
                return(NotFoundResponse("issue"));
            }
        }
Example #4
0
        public async Task <DiscordCommandResult> GetRandomWordAsync()
        {
            var result = await _searchService.GetRandomWordResponseAsync();

            var le = new LexEmbed()
                     .WithTitle(result.Word)
                     .WithDescription(result.Definition)
                     .AddField("Pronunciation", result.Pronunciation);

            return(Response(le));
        }
Example #5
0
        public DiscordCommandResult AvatarAsync([Description("The member for whom you wish to receive a portrait")] IMember member = null)
        {
            member ??= Context.Author;
            var avatarUrl = member.GetAvatarUrl(CdnAssetFormat.Automatic, 2048);

            var eb = new LexEmbed()
                     .WithTitle($"A portrait of {member}")
                     .WithUrl(avatarUrl)
                     .WithImageUrl(avatarUrl);

            return(Response(eb));
        }
Example #6
0
        public async Task <DiscordCommandResult> QuoteMessageAsync(string quoteUrl)
        {
            var regex = Discord.MessageJumpLinkRegex;

            if (!regex.IsMatch(quoteUrl))
            {
                return(Response("It seems you have not given me a valid jump URL"));
            }

            var res       = regex.Match(quoteUrl);
            var channelId = Convert.ToUInt64(res.Groups["channel_id"].Value);
            var messageId = Convert.ToUInt64(res.Groups["message_id"].Value);

            IChannel channel;

            try
            {
                channel = await Context.Bot.FetchChannelAsync(channelId);
            }
            catch (RestApiException e) when(e.StatusCode == HttpResponseStatusCode.Forbidden)
            {
                return(Response("It seems I am unable to access that channel"));
            }

            if (channel is not IGuildChannel guildChannel)
            {
                return(Response("I cannot read messages from a DM"));
            }

            if (!Context.CurrentMember.GetChannelPermissions(guildChannel).ReadMessageHistory)
            {
                return(Response("I don't have the necessary permissions to view this channel"));
            }

            if (!Context.Author.GetChannelPermissions(guildChannel).ReadMessageHistory)
            {
                return(Response("You don't have the necessary permissions to view this channel"));
            }

            var message = await Context.Bot.FetchMessageAsync(channelId, messageId);

            var eb = new LexEmbed()
                     .WithAuthor(message.Author.ToString(), message.Author.GetAvatarUrl())
                     .WithDescription(message.Content)
                     .WithFooter($"Id: {messageId}")
                     .WithTimestamp(message.CreatedAt());

            return(Response(eb));
        }
Example #7
0
        public DiscordCommandResult QuoteMessageAsync()
        {
            var messageRef = Context.Message.ReferencedMessage.GetValueOrDefault();

            if (messageRef is null)
            {
                return(Response("I require a Jump URL or a reference to a message to quote"));
            }

            var eb = new LexEmbed()
                     .WithAuthor(messageRef.Author.ToString(), messageRef.Author.GetAvatarUrl())
                     .WithDescription(messageRef.Content)
                     .WithFooter($"Id: {messageRef.Id}")
                     .WithTimestamp(messageRef.CreatedAt());

            return(Response(eb));
        }
Example #8
0
        public async Task <DiscordCommandResult> GetNoteAsync([Description("The Id of the note")] int id)
        {
            var note = await NoteService.RetrieveNoteAsync(id);

            if (note is null)
            {
                return(NoteNotFoundResponse());
            }

            var owner = await Context.Bot.FetchUserAsync(note.OwnerId);

            var eb = new LexEmbed()
                     .WithTitle($"Note {note.Id}")
                     .WithDescription(note.ToString())
                     .WithAuthor(owner);

            return(Response(eb));
        }
Example #9
0
        public async Task <DiscordCommandResult> SearchWordDefinitionAsync([Remainder] string word)
        {
            var result = await _searchService.GetDefinitionAsync(word);

            switch (result.Entries.Count)
            {
            case 0:
                return(NoResultsFoundResponse());

            case <= 5:
            {
                var i  = 0;
                var le = new LexEmbed()
                         .WithTitle(result.SearchText);

                foreach (var entry in result.Entries)
                {
                    foreach (var def in entry.ShortDefs)
                    {
                        le.AddField($"{++i}", def);
                    }
                }

                return(Response(le));
            }

            default:
            {
                var fieldBuilders = new List <LocalEmbedField>(result.Entries.Count);
                var i             = 0;

                foreach (var entry in result.Entries)
                {
                    foreach (var def in entry.ShortDefs)
                    {
                        fieldBuilders.Add(new LocalEmbedField().WithName($"{i++}").WithValue(def));
                    }
                }

                var config = FieldBasedPageProviderConfiguration.Default.WithContent($"I found {result.Entries.Count} definitions");
                return(Pages(new FieldBasedPageProvider(fieldBuilders, config)));
            }
            }
        }
Example #10
0
        public async Task <DiscordCommandResult> GitSearchUsersAsync([Name("Search Query"), Remainder] string searchQuery)
        {
            var request = new SearchUsersRequest(searchQuery);

            var result = await _lexGithubClient.Search.SearchUsers(request);

            switch (result.Items.Count)
            {
            case 0:
                return(NoResultsFoundResponse());

            case <= 5:
            {
                var eb = new LexEmbed()
                         .WithTitle("Search Results");

                foreach (var item in result.Items)
                {
                    eb.AddField(item.Name ?? item.Login, $"{GetUserSearchResultBio(item)} ({Markdown.Link("GitHub page", item.HtmlUrl)})");
                }


                return(Response(eb));
            }

            default:
            {
                var fieldBuilders = new List <LocalEmbedField>(result.Items.Count);

                foreach (var item in result.Items)
                {
                    fieldBuilders.Add(new LocalEmbedField().WithName(item.Name ?? item.Login)
                                      .WithValue($"{item.Name ?? item.Login} {GetUserSearchResultBio(item)} ({Markdown.Link("GitHub page", item.HtmlUrl)})"));
                }

                var config =
                    FieldBasedPageProviderConfiguration.Default.WithContent(
                        $"I have found {result.Items.Count} results");

                return(Pages(new FieldBasedPageProvider(fieldBuilders, config)));
            }
            }
        }
Example #11
0
        public async Task <DiscordCommandResult> ServerInfoAsync()
        {
            var owner = await Context.Guild.FetchMemberAsync(Context.Guild.OwnerId);

            var botMemberCount = Context.Guild.Members.Values.Count(x => x.IsBot);

            var features = Context.Guild.GetGuildFeatures();

            var eb = new LexEmbed()
                     .WithTitle(Context.Guild.Name)
                     .WithDescription($"**ID:** {Context.Guild.Id}\n**Owner:** {owner}")
                     .WithThumbnailUrl(Context.Guild.GetIconUrl())
                     .WithFooter("Created")
                     .WithTimestamp(Context.Guild.CreatedAt())
                     .AddField("Member count", $"{Context.Guild.MemberCount} ({botMemberCount} bots)")
                     .AddField("Channels", Context.Guild.GetChannels().Count)
                     .AddField("Roles", Context.Guild.Roles.Count)
                     .AddField("Features", features);

            return(Response(eb));
        }
Example #12
0
        public async Task <DiscordCommandResult> GetRepoAsync(
            [Name("Username"), Description("The owner of the repository")] string username,
            [Name("Repository Name"), Description("The name of the repository")] string repoName)
        {
            try
            {
                var result = await _lexGithubClient.Repository.Get(username, repoName);

                var eb = new LexEmbed()
                         .WithTitle(result.Name)
                         .WithDescription(result.Description)
                         .AddField("Language", result.Language)
                         .AddField("Source", Markdown.Link("Github", result.HtmlUrl));

                return(Response(eb));
            }
            catch (NotFoundException)
            {
                return(NotFoundResponse("repository"));
            }
        }
Example #13
0
        public async Task <DiscordCommandResult> ListNotesAsync()
        {
            var notes = await NoteService.RetrieveNotesAsync(Context.Author.Id);

            switch (notes.Count)
            {
            case 0:
                return(Response("It seems you do not have any notes"));

            case <= 5:
            {
                var eb = new LexEmbed();

                foreach (var note in notes)
                {
                    eb.AddField($"Note {note.Id}", note.ToString());
                }

                var content = $"I have retrieved {notes.Count} {(notes.Count == 1 ? "note" : "notes")}";
                return(Response(content, eb));
            }

            default:
            {
                var fieldBuilders = new List <LocalEmbedField>(notes.Count);

                foreach (var note in notes)
                {
                    fieldBuilders.Add(new LocalEmbedField().WithName($"Note {note.Id}").WithValue(note.ToString()));
                }

                var config = FieldBasedPageProviderConfiguration.Default.WithContent($"You have {notes.Count} notes");
                return(Pages(new FieldBasedPageProvider(fieldBuilders, config)));
            }
            }
        }
Example #14
0
        public async Task <DiscordCommandResult> GetUserAsync([Description("The username of the user")] string username)
        {
            try
            {
                var result = await _lexGithubClient.User.Get(username);

                var eb = new LexEmbed()
                         .WithTitle(result.Name ?? result.Login)
                         .WithUrl(result.HtmlUrl)
                         .WithThumbnailUrl(result.AvatarUrl)
                         .WithDescription(result.Bio ?? "No Bio")
                         .AddField("Followers", result.Followers, true)
                         .AddField("Following", result.Following, true)
                         .AddField("Repositories", result.PublicRepos, true)
                         .AddField("Location", result.Location ?? "No Location")
                         .AddField("Account created at", result.CreatedAt.ToString());

                return(Response(eb));
            }
            catch (NotFoundException)
            {
                return(NotFoundResponse("user"));
            }
        }
Example #15
0
        public DiscordCommandResult Help(params string[] path)
        {
            var service                      = Context.Bot.Commands;
            var topLevelModules              = service.TopLevelModules.ToArray();
            IReadOnlyList <Module>  modules  = topLevelModules.Where(x => x.Aliases.Count != 0).ToArray();
            IReadOnlyList <Command> commands = topLevelModules.Except(modules).SelectMany(x => x.Commands).ToArray();

            if (path.Length == 0)
            {
                var builder = new LexEmbed();

                if (modules.Count != 0)
                {
                    var aliases = modules.Select(x => x.Aliases[0])
                                  .OrderBy(x => x)
                                  .Select(x => Markdown.Code(x));
                    builder.AddField("Modules", string.Join(", ", aliases));
                }

                if (commands.Count != 0)
                {
                    var aliases = commands.Select(x => x.Aliases[0])
                                  .OrderBy(x => x)
                                  .Select(x => Markdown.Code(x));
                    builder.AddField("Commands", string.Join(", ", aliases));
                }

                return(builder.Fields.Count == 0 ? Reply("Nothing to display.") : Reply(builder));
            }

            var     comparison   = service.StringComparison;
            Module  foundModule  = null;
            Command foundCommand = null;

            foreach (var t in path)
            {
                if (foundModule != null)
                {
                    modules     = foundModule.Submodules;
                    commands    = foundModule.Commands;
                    foundModule = null;
                }

                var currentAlias = t.Trim();
                foreach (var module in modules)
                {
                    foreach (var alias in module.Aliases)
                    {
                        if (!currentAlias.Equals(alias, comparison))
                        {
                            continue;
                        }
                        foundModule = module;
                        break;
                    }
                }

                if (foundModule != null)
                {
                    continue;
                }
                foreach (var command in commands)
                {
                    foreach (var alias in command.Aliases)
                    {
                        if (currentAlias.Equals(alias, comparison))
                        {
                            foundCommand = command;
                            break;
                        }
                    }
                }

                if (foundCommand != null)
                {
                    break;
                }
            }

            if (foundModule == null && foundCommand == null)
            {
                return(Reply("No module or command found matching the input."));
            }
            if (foundCommand != null)
            {
                var eb = new LexEmbed()
                         .WithTitle(foundCommand.Name)
                         .WithDescription(foundCommand.Description ?? "No Description")
                         .AddField("Module", foundCommand.Module is null ? "Top level command" : foundCommand.Module.Name)
                         .AddField("Aliases", foundCommand.Aliases is null
                        ? "No aliases"
                        : string.Join(", ", foundCommand.Aliases.Select(Markdown.Code)))
                         .AddField("Parameters", foundCommand.Parameters.Count == 0
                        ? "No parameters"
                        : string.Join(' ', foundCommand.Parameters.Select(FormatParameter)));

                if (foundCommand.Parameters.Count != 0)
                {
                    eb.AddField("Parameter Descriptions", string.Join('\n',
                                                                      foundCommand.Parameters.Select(x => $"{x.Name}: {x.Description ?? "No description"}")));
                }

                return(Reply(eb));
            }
            else
            {
                var eb = new LexEmbed()
                         .WithTitle(foundModule.Name)
                         .WithDescription(foundModule.Description ?? "No Description")
                         .AddField("Submodules",
                                   foundModule.Submodules.Count == 0
                            ? "No submodules"
                            : string.Join('\n', foundModule.Submodules.Select(x => Markdown.Code(x.Name))))
                         .AddField("Commands", string.Join('\n', foundModule.Commands.Where(x => !string.IsNullOrEmpty(x.Name))
                                                           .Select(x => Markdown.Code(x.Name))));

                return(Reply(eb));
            }
        }
Example #16
0
        public LocalEmbed EvalLuaCode(string codeBlock)
        {
            try
            {
                var script = new Script(CoreModules.Preset_SoftSandbox);
                var res    = script.DoString(codeBlock);

                object resString = res.Type switch
                {
                    DataType.String => res.String,
                    DataType.Number => res.Number,
                    DataType.Boolean => res.Boolean,
                    DataType.Function => res.Function,
                    DataType.Nil => "null",
                    DataType.Void => "void",
                    DataType.Table => res.Table,
                    DataType.Tuple => res.Tuple,
                    DataType.UserData => "no return type",
                    DataType.Thread => "no return type",
                    DataType.ClrFunction => res.Callback.Name,
                    DataType.TailCallRequest => res.UserData.Descriptor.Name,
                    DataType.YieldRequest => "no return type",
                    _ => "no return type"
                };

                var codeReturn = Markdown.CodeBlock("lua", resString.ToString());

                var resEmbed = new LexEmbed()
                               .WithTitle("Evaluation Success")
                               .WithDescription(codeReturn)
                               .OverrideColor(new Color(161, 11, 11));

                return(resEmbed);
            }
            catch (ScriptRuntimeException scriptRuntimeException)
            {
                var errCodeBlock = Markdown.CodeBlock("lua", scriptRuntimeException.DecoratedMessage);

                var errEmbed = new LexEmbed()
                               .WithTitle("An error occured, Runtime Exception")
                               .WithDescription(errCodeBlock)
                               .OverrideColor(new Color(161, 11, 11));

                Logger.LogError("Unsuccessfully evaluated Lua code, Runtime Exception");

                return(errEmbed);
            }
            catch (SyntaxErrorException syntaxErrorException)
            {
                var errCodeBlock = Markdown.CodeBlock("lua", syntaxErrorException.DecoratedMessage);

                var errEmbed = new LexEmbed()
                               .WithTitle("An error occured, Syntax Exception")
                               .WithDescription(errCodeBlock)
                               .OverrideColor(new Color(161, 11, 11));

                Logger.LogError("Unsuccessfully evaluated Lua code, Syntax exception");

                return(errEmbed);
            }
        }