コード例 #1
0
            public async ValueTask <AdminCommandResult> ViewCooldownAsync([Lowercase] string commandName)
            {
                var matches = Commands.GetAllCommands()
                              .Where(x => x.FullAliases.Contains(commandName, StringComparer.OrdinalIgnoreCase)).ToList();

                if (matches.Count == 0)
                {
                    return(CommandErrorLocalized("info_help_notfound"));
                }

                if (!(await Context.Database.Cooldowns.FindAsync(Context.Guild.Id.RawValue, commandName) is { }
                      commandCooldown))
                {
                    return(CommandSuccessLocalized("info_cooldown_default",
                                                   args: new object[]
                    {
                        Markdown.Code(commandName),
                        Markdown.Bold(
                            MinimumCooldownAttribute.MinimumCooldown.HumanizeFormatted(Localization, Context.Language,
                                                                                       TimeUnit.Second))
                    }));
                }

                return(CommandSuccessLocalized("info_cooldown", args: new object[]
                {
                    Markdown.Code(commandName),
                    Markdown.Bold(
                        commandCooldown.Cooldown.HumanizeFormatted(Localization, Context.Language,
                                                                   TimeUnit.Second))
                }));
            }
コード例 #2
0
        public async ValueTask <AdminCommandResult> GetCommandsAsync(Module module)
        {
            var commands = CommandUtilities.EnumerateAllCommands(module);
            var groups   = commands.GroupBy(x => x.FullAliases[0]).ToList();

            var pages = DefaultPaginator.GeneratePages(groups, 1024, group => new StringBuilder()
                                                       .Append(Markdown.Bold(FormatCommands(group)))
                                                       .AppendNewline(Localize($"info_command_{group.Key.Replace(' ', '_')}")).ToString(),
                                                       builderFunc: () => new LocalEmbedBuilder().WithSuccessColor()
                                                       .WithTitle(Localize("info_module_commands", Markdown.Code(module.Name))));

            /*
             * var pages = DefaultPaginator.GeneratePages(groups, 15, group => new EmbedFieldBuilder()
             *  //    .WithName(new StringBuilder(Config.DefaultPrefix)
             *  //        .AppendJoin($"\n{Config.DefaultPrefix}", group.First().FullAliases).Tag)
             *  .WithName(FormatCommands(group))
             *  .WithValue(Localize($"info_command_{group.Key.Replace(' ', '_')}")),
             *  embedFunc: builder => builder.WithSuccessColor()
             *      .WithTitle(Localize("info_module_commands", Format.Code(module.Name))));
             */

            if (pages.Count > 1)
            {
                await Pagination.SendPaginatorAsync(Context.Channel, new DefaultPaginator(pages, 0), pages[0]);

                return(CommandSuccess());
            }

            return(CommandSuccess(embed: pages[0].Embed));
        }
コード例 #3
0
        public async Task <DiscordCommandResult> AddMainAsync(
            [Description("The emoji for the character you wish to add.")]
            IGuildEmoji emoji)
        {
            if (!EmojiToRoleMap.TryGetValue(emoji.Id, out var roleId))
            {
                return(Response("That emoji doesn't belong to a character!"));
            }

            if (Context.Author.RoleIds.Contains(roleId))
            {
                return(Response("You already added that character as a main!"));
            }

            if (await Database.Config.FindAsync("MAXIMUM_MAINS") is not {
            } maximumMains ||
                !int.TryParse(maximumMains.Value, out var maximum))
            {
                return(Response("This command isn't properly configured. Please contact one of the admins."));
            }

            if (EmojiToRoleMap.Values.Count(x => Context.Author.RoleIds.Contains(x)) >= maximum)
            {
                return(Response($"You are not allowed to have more than {maximum} characters you main at once.\n" +
                                $"You'll need to remove some first via \"{Context.Prefix}remove <character>\"."));
            }

            await Context.Author.GrantRoleAsync(roleId);

            return(Response($"You've added {Markdown.Bold(Context.Guild.Roles[roleId].Name)} as a main."));
        }
コード例 #4
0
        public AdminCommandResult GetCommandHelp([Remainder] string commandName)
        {
            var matches = Commands.GetAllCommands()
                          .Where(x => x.FullAliases.Contains(commandName, StringComparer.OrdinalIgnoreCase)).ToList();

            if (matches.Count == 0)
            {
                return(CommandErrorLocalized("info_help_notfound"));
            }

            /*
             * if (matches.Count > 1) // TODO: is this even possible
             *  return CommandErrorLocalized("info_help_multiple");
             */

            var command = matches[0];

            return(CommandSuccess(embed: new LocalEmbedBuilder()
                                  .WithSuccessColor()
                                  .WithDescription(new StringBuilder()
                                                   .Append(Markdown.Bold(FormatCommands(matches)))
                                                   .AppendNewline(Localize($"info_command_{command.FullAliases[0].Replace(' ', '_')}")).AppendNewline()
                                                   .ToString())
                                  .WithFooter(Localize("info_module_reference", command.Module.Name))
                                  .Build()));
        }
コード例 #5
0
ファイル: PPTXFileProcessor.cs プロジェクト: dotBunny/Galileo
        /// <summary>
        /// Process the submissions absolute path
        /// </summary>
        /// <returns>Was the submission able to be loaded?</returns>
        public override bool Process()
        {
            _loaded = false;

            try
            {
                // Open Document
                _document = PresentationDocument.Open(_target.AbsolutePath, false);

                StringBuilder builder = new StringBuilder();

                // Go through slides
                int numberOfSlides = CountSlides(_document);
                for (int i = 0; i < numberOfSlides; i++)
                {
                    string[] lines = GetAllTextInSlide(_document, i);
                    if (lines != null)
                    {
                        foreach (string s in lines)
                        {
                            builder.AppendLine(s);
                        }
                    }
                }

                // Get plain text of content
                _target.Content = builder.ToString();

                // Cache length for later comparison
                _target.ContentLength = _target.Content.Length;
                _target.ContentHash   = Compare.Hash(_target.Content);

                // Collect Meta Data
                _target.MetaCreator        = _document.PackageProperties.Creator;
                _target.MetaLastModifiedBy = _document.PackageProperties.LastModifiedBy;

                if (_document.PackageProperties.LastPrinted != null)
                {
                    _target.MetaDateLastPrinted = (DateTime)_document.PackageProperties.LastPrinted;
                }

                if (_document.PackageProperties.Created != null)
                {
                    _target.MetaDateCreated = (DateTime)_document.PackageProperties.Created;
                }

                if (_document.PackageProperties.Modified != null)
                {
                    _target.MetaDateModified = (DateTime)_document.PackageProperties.Modified;
                }

                _loaded = true;
            }
            catch (Exception e)
            {
                _target.Logging.Add("- " + Markdown.Bold("An exception occured when processing " + _target.AbsolutePath + ", " + e.Message));
            }

            return(_loaded);
        }
コード例 #6
0
        private async Task <string> FormatReminderStringAsync(UserReminder reminder)
        {
            var reminderStringBuilder = new StringBuilder();
            var executesIn            = reminder.TriggerAt - DateTimeOffset.Now;

            // todo this is a really bad and lazy system
            reminderStringBuilder.AppendLine($"{Markdown.Bold("Id")}: {reminder.Id[..4]}");
コード例 #7
0
        /// <summary>
        /// Process the submissions absolute path
        /// </summary>
        /// <returns>Was the submission able to be loaded?</returns>
        public override bool Process()
        {
            _loaded = false;

            try
            {
                WP6Document doc = new WP6Document(_target.AbsolutePath);

                // Build document content
                StringBuilder contentBuilder = new StringBuilder();
                foreach (WPToken t in doc.documentArea.WPStream)
                {
                    Type tokenType = t.GetType();
                    if (tokenType == typeof(Character))
                    {
                        Character character = (Character)t;
                        contentBuilder.Append(character.content);
                    }
                }
                _target.Content       = contentBuilder.ToString();
                _target.ContentLength = _target.Content.Length;
                _target.ContentHash   = Compare.Hash(_target.Content);



                _loaded = true;
            }
            catch (Exception e)
            {
                _target.Logging.Add("- " + Markdown.Bold("An exception occured when processing " + _target.AbsolutePath + ", " + e.Message));
            }

            return(_loaded);
        }
コード例 #8
0
ファイル: Program.cs プロジェクト: QuantumToasted/Shine
        private static void GenerateCommandMarkdown(CommandService commandService)
        {
            var builder = new StringBuilder();

            foreach (var module in commandService.TopLevelModules.OrderBy(x => x.Name))
            {
                builder.AppendNewline($"## {module.Name}")
                .AppendNewline(module.Description)
                .AppendNewline("|Command|Description|")
                .AppendNewline("|---|---|");

                foreach (var command in CommandUtilities.EnumerateAllCommands(module))
                {
                    builder.Append('|')
                    .Append(string.Join("<br>",
                                        command.FullAliases.Select(x => Markdown.Code($"{PREFIX}{x}{command.FormatArguments()}"))))
                    .Append('|')
                    .Append(command.Description.Replace("\n", "<br>"));

                    foreach (var parameter in command.Parameters)
                    {
                        builder.Append("<br>")
                        .Append(Markdown.Code(parameter.Name))
                        .Append(": ")
                        .Append(parameter.Description.Replace("\n", "<br>"))
                        .Append(parameter.IsOptional ? $" {Markdown.Bold("(optional)")}" : string.Empty);
                    }

                    builder.AppendNewline("|");
                }
            }

            Directory.CreateDirectory("docs");
            File.WriteAllText("docs/Command-List.md", builder.ToString());
        }
コード例 #9
0
        public override async ValueTask <CheckResult> CheckAsync(CommandContext ctx)
        {
            var baseCheck = await base.CheckAsync(ctx);

            if (!baseCheck.IsSuccessful)
            {
                return(baseCheck);
            }

            var context = (AdminCommandContext)ctx;
            var user    = (CachedMember)context.User;

            if (_isGuildPermissions)
            {
                return(!user.Permissions.Has(RequiredPermissions)
                    ? CheckResult.Unsuccessful(context.Localize("requireuserpermissions_guild",
                                                                Markdown.Bold(RequiredPermissions.Humanize(LetterCasing.Title))))
                    : CheckResult.Successful);
            }

            return(!user.GetPermissionsFor(context.Channel as IGuildChannel)
                   .Has(RequiredPermissions)
                ? CheckResult.Unsuccessful(context.Localize("requireuserpermissions_channel",
                                                            Markdown.Bold(RequiredPermissions.Humanize(LetterCasing.Title))))
                : CheckResult.Successful);
        }
コード例 #10
0
 public AdminCommandResult GetNickname([Remainder] CachedMember target)
 {
     return(string.IsNullOrWhiteSpace(target.Nick)
         ? CommandSuccessLocalized("user_no_nickname", args: Markdown.Bold(target.Tag.Sanitize()))
         : CommandSuccessLocalized("user_nickname",
                                   args: new object[] { Markdown.Bold(target.Tag.Sanitize()), Markdown.Bold(target.Nick.Sanitize()) }));
 }
コード例 #11
0
            public async ValueTask <AdminCommandResult> GetLanguageAsync()
            {
                var guild = await Context.Database.GetOrCreateGuildAsync(Context.Guild.Id);

                return(CommandSuccessLocalized("guild_language", args:
                                               $"{Markdown.Bold(guild.Language.NativeName)} ({guild.Language.EnglishName}, `{guild.Language.CultureCode}`)"));
            }
コード例 #12
0
 private string FormatUser(CachedMember target)
 {
     return(string.IsNullOrWhiteSpace(target.Nick)
         ? target.Format()
         : Localize("user_search_format", Markdown.Bold(target.Tag.Sanitize()),
                    Markdown.Bold(target.Nick.Sanitize()),
                    Markdown.Code(target.Id.ToString())));
 }
コード例 #13
0
            public async ValueTask <AdminCommandResult> RenameRoleAsync([RequireHierarchy] CachedRole target,
                                                                        [Remainder] string newName)
            {
                await target.ModifyAsync(x => x.Name = newName);

                return(CommandSuccessLocalized("role_rename_success",
                                               args: new object[] { target.Format(), Markdown.Bold(newName) }));
            }
コード例 #14
0
        public override ValueTask <CheckResult> CheckAsync(object argument, CommandContext ctx)
        {
            var guild   = (CachedGuild)argument;
            var context = (AdminCommandContext)ctx;

            return(guild.GetMember(context.User.Id) is null
                ? CheckResult.Unsuccessful(context.Localize("requiremember", Markdown.Bold(guild.Name)))
                : CheckResult.Successful);
        }
コード例 #15
0
ファイル: HTMLFileProcessor.cs プロジェクト: dotBunny/Galileo
        /// <summary>
        /// Process the submissions absolute path
        /// </summary>
        /// <returns>Was the submission able to be loaded?</returns>
        public override bool Process()
        {
            _loaded = false;

            try
            {
                var doc = new HtmlDocument();
                doc.LoadHtml(File.ReadAllText(_target.AbsolutePath));


                HtmlNode creatorNode = doc.DocumentNode.SelectSingleNode("//meta[@name='author']");
                if (creatorNode != null)
                {
                    _target.MetaCreator = creatorNode.Attributes["content"].Value;
                }


                DateTime tempDate;

                var metaModifiedNode = doc.DocumentNode.SelectSingleNode("//meta[@property='article:published_time']");
                if (metaModifiedNode != null)
                {
                    string time = metaModifiedNode.Attributes["content"].Value;
                    if (DateTime.TryParse(time, out tempDate))
                    {
                        _target.MetaDateCreated = tempDate;
                    }
                }

                var mdnode = doc.DocumentNode.SelectSingleNode("//meta[@property='article:modified_time']");
                if (mdnode != null)
                {
                    string time = mdnode.Attributes["content"].Value;
                    if (DateTime.TryParse(time, out tempDate))
                    {
                        _target.MetaDateModified = tempDate;
                    }
                }


                string content = doc.DocumentNode.SelectSingleNode("//body").InnerText;
                content               = content.Replace("\n", string.Empty).Replace("\r", string.Empty).Replace(" ", string.Empty);
                _target.Content       = content;
                _target.ContentLength = _target.Content.Length;
                _target.ContentHash   = Compare.Hash(_target.Content);

                _loaded = true;
            }
            catch (Exception e)
            {
                _target.Logging.Add("- " + Markdown.Bold("An exception occured when processing " + _target.AbsolutePath + ", " + e.Message));
            }

            return(_loaded);
        }
コード例 #16
0
ファイル: PDFFileProcessor.cs プロジェクト: dotBunny/Galileo
        /// <summary>
        /// Process the submissions absolute path
        /// </summary>
        /// <returns>Was the submission able to be loaded?</returns>
        public override bool Process()
        {
            _loaded = false;

            try
            {
                // Create our document
                _document = new PdfReader(_target.AbsolutePath);

                // Read meta data only if its not encrypted
                if (!_document.IsMetadataEncrypted())
                {
                    // Meta
                    if (_document.Info.ContainsKey("Author"))
                    {
                        _target.MetaCreator = _document.Info["Author"];
                    }

                    if (_document.Info.ContainsKey("CreationDate"))
                    {
                        DateTime.TryParse(_document.Info["CreationDate"], out _target.MetaDateCreated);
                    }

                    if (_document.Info.ContainsKey("ModDate"))
                    {
                        DateTime.TryParse(_document.Info["ModDate"], out _target.MetaDateModified);
                    }
                }


                // Content
                StringWriter output = new StringWriter();

                for (int i = 1; i <= _document.NumberOfPages; i++)
                {
                    output.WriteLine(PdfTextExtractor.GetTextFromPage(_document, i, new SimpleTextExtractionStrategy()));
                }

                _target.Content = output.ToString();

                // Cache length for later comparison
                _target.ContentLength = _target.Content.Length;
                _target.ContentHash   = Compare.Hash(_target.Content);


                _loaded = true;
            }
            catch (Exception e)
            {
                _target.Logging.Add("- " + Markdown.Bold("An exception occured when processing " + _target.AbsolutePath + ", " + e.Message, true));
            }

            return(_loaded);
        }
コード例 #17
0
                public async ValueTask <AdminCommandResult> ListGuildSettingsAsync()
                {
                    var builder =
                        new StringBuilder(Localize("guild_settings", Markdown.Bold(Context.Guild.Name.Sanitize())))
                        .AppendNewline()
                        .AppendNewline();

                    var guild = await Context.Database.GetOrCreateGuildAsync(Context.Guild.Id);

                    foreach (var value in Enum.GetValues(typeof(GuildSettings)).Cast <GuildSettings>()
                             .Where(x => !x.Equals(default)))
コード例 #18
0
ファイル: ODTFileProcessor.cs プロジェクト: dotBunny/Galileo
        /// <summary>
        /// Process the submissions absolute path
        /// </summary>
        /// <returns>Was the submission able to be loaded?</returns>
        public override bool Process()
        {
            _loaded = false;
            try
            {
                var sb = new StringBuilder();
                _document = new TextDocument();
                _document.Load(_target.AbsolutePath);

                //The header and footer are in the DocumentStyles part. Grab the XML of this part
                XElement stylesPart = XElement.Parse(_document.DocumentStyles.Styles.OuterXml);
                //Take all headers and footers text, concatenated with return carriage
                string stylesText = string.Join("\r\n", stylesPart.Descendants().Where(x => x.Name.LocalName == "header" || x.Name.LocalName == "footer").Select(y => y.Value));

                //Main content
                var mainPart = _document.Content.Cast <IContent>();
                var mainText = String.Join("\r\n", mainPart.Select(x => x.Node.InnerText));

                //Append both text variables
                sb.Append(stylesText + "\r\n");
                sb.Append(mainText);

                _target.Content = sb.ToString();

                // Cache length for later comparison as well as generate a generic hash
                _target.ContentLength = _target.Content.Length;
                _target.ContentHash   = Compare.Hash(_target.Content);

                // Assign Meta Data
                if (_document.DocumentMetadata.Creator != null)
                {
                    // Format treats them the same
                    _target.MetaCreator        = _document.DocumentMetadata.Creator;
                    _target.MetaLastModifiedBy = _document.DocumentMetadata.Creator;
                    if (_target.MetaCreator == "\"\"")
                    {
                        _target.MetaCreator        = string.Empty;
                        _target.MetaLastModifiedBy = string.Empty;
                    }
                }
                _target.MetaDateCreated  = DateTime.Parse(_document.DocumentMetadata.CreationDate);
                _target.MetaDateModified = DateTime.Parse(_document.DocumentMetadata.LastModified);

                // Set loaded flag
                _loaded = true;
            }
            catch (Exception e)
            {
                _target.Logging.Add("- " + Markdown.Bold("An exception occured when processing " + _target.AbsolutePath + ", " + e.Message, true));
            }
            return(_loaded);
        }
コード例 #19
0
            public async ValueTask <AdminCommandResult> RevokeRoleAsync(CachedMember target,
                                                                        [RequireHierarchy] CachedRole role)
            {
                if (target.Roles.Keys.All(x => x != role.Id))
                {
                    return(CommandErrorLocalized("role_remove_role_exists", args: Markdown.Bold(target.Tag.Sanitize())));
                }

                await target.RevokeRoleAsync(role.Id);

                return(CommandSuccessLocalized("role_remove_success",
                                               args: new object[] { Markdown.Bold(target.Tag.Sanitize()), role.Format() }));
            }
コード例 #20
0
            public async ValueTask <AdminCommandResult> MoveRoleAsync([RequireHierarchy] CachedRole target,
                                                                      Direction direction, [Remainder] CachedRole move)
            {
                var user = (CachedMember)Context.User;

                if (direction == Direction.Below)
                {
                    if (target.IsDefault || move.IsDefault)
                    {
                        return(CommandErrorLocalized("role_move_below_everyone", args: "@\u200Beveryone"));
                    }

                    if (Context.Guild.CurrentMember.GetHighestRole().Position < move.Position)
                    {
                        return(CommandErrorLocalized("role_move_below_unable_self",
                                                     args: new object[] { Markdown.Bold(move.Name), Markdown.Bold(target.Name) }));
                    }
                    if (user.GetHighestRole().Position < move.Position)
                    {
                        return(CommandErrorLocalized("role_move_below_unable_user",
                                                     args: new object[] { Markdown.Bold(move.Name), Markdown.Bold(target.Name) }));
                    }

                    await target.ModifyAsync(x => x.Position = move.Position - 1);

                    return(CommandSuccessLocalized("role_move_below_success",
                                                   args: new object[] { target.Format(), move.Format() }));
                }

                if (target.IsDefault)
                {
                    return(CommandErrorLocalized("role_move_above_everyone", args: "@\u200Beveryone"));
                }

                if (Context.Guild.CurrentMember.GetHighestRole().Position < move.Position)
                {
                    return(CommandErrorLocalized("role_move_above_unable_self",
                                                 args: new object[] { Markdown.Bold(move.Name), Markdown.Bold(target.Name) }));
                }
                if (user.GetHighestRole().Position < move.Position)
                {
                    return(CommandErrorLocalized("role_move_above_unable_user",
                                                 args: new object[] { Markdown.Bold(move.Name), Markdown.Bold(target.Name) }));
                }

                await target.ModifyAsync(x => x.Position = move.Position + 1);

                return(CommandSuccessLocalized("role_move_above_success",
                                               args: new object[] { target.Format(), move.Format() }));
            }
コード例 #21
0
                public async ValueTask <AdminCommandResult> ListPrefixesAsync()
                {
                    var guild = await Context.Database.GetOrCreateGuildAsync(Context.Guild.Id);

                    if (guild.CustomPrefixes.Count == 0)
                    {
                        return(CommandErrorLocalized("guild_prefixes_none"));
                    }

                    return(CommandSuccess(
                               new StringBuilder(Localize("guild_prefixes", Markdown.Bold(Context.Guild.Name.Sanitize())))
                               .AppendNewline()
                               .AppendNewline()
                               .AppendJoin('\n', guild.CustomPrefixes.Select(x => $"\"{x.Sanitize()}\"")).ToString()));
                }
コード例 #22
0
            public async ValueTask <AdminCommandResult> SetLanguageAsync([Remainder] LocalizedLanguage newLanguage)
            {
                var guild = await Context.Database.GetOrCreateGuildAsync(Context.Guild.Id);

                guild.Language = newLanguage;
                Context.Database.Guilds.Update(guild);
                await Context.Database.SaveChangesAsync();

                Context.Language = newLanguage;

                CommandHandler.UpdateLanguage(Context.Guild.Id, newLanguage);

                return(CommandSuccessLocalized("guild_language_set", args:
                                               $"{Markdown.Bold(guild.Language.NativeName)} ({guild.Language.EnglishName}, `{guild.Language.CultureCode}`)"));
            }
コード例 #23
0
ファイル: HelpModule.cs プロジェクト: Zackattak01/CheeseBot
        public DiscordCommandResult Help([Remainder] string query)
        {
            var matches = _commandService.FindCommands(query);

            if (matches.Count == 0)
            {
                return(Response("No matches were found.  Please try refining your search query."));
            }

            var selectionPages = new List <SelectionPage>
            {
                new(GetSyntaxExplanationPage(), "Help")
            };

            foreach (var command in matches.Select(x => x.Command))
            {
                var embed = new LocalEmbed()
                            .WithDefaultColor()
                            .WithTitle(command.GetHelpString())
                            .AddField("Description", command.Description ?? "No description");

                var displayableAliases = new List <string>();

                foreach (var alias in command.FullAliases)
                {
                    var trimmedAlias = alias.Trim();
                    if (trimmedAlias == command.Name || trimmedAlias == string.Empty)
                    {
                        continue;
                    }

                    displayableAliases.Add($"• {command.GetHelpString(trimmedAlias)}");
                }

                if (displayableAliases.Count > 0)
                {
                    embed.WithDescription($"{Markdown.Bold("Aliases")}\n{string.Join('\n', displayableAliases)}");
                }

                var page = new Page().AddEmbed(embed);
                selectionPages.Add(new SelectionPage(
                                       page,
                                       command.Name,
                                       command.Description?.HumanTruncateAt(LocalSelectionComponentOption.MaxDescriptionLength) ?? "No description"));
            }

            return(View(new SelectionPagedView(new SelectionPageProvider(selectionPages))));
        }
コード例 #24
0
ファイル: DOCXFileProcessor.cs プロジェクト: dotBunny/Galileo
        /// <summary>
        /// Process the submissions absolute path
        /// </summary>
        /// <returns>Was the submission able to be loaded?</returns>
        public override bool Process()
        {
            _loaded = false;
            try
            {
                _document = WordprocessingDocument.Open(_target.AbsolutePath, false);

                // Build Plain Text Version
                OpenXmlElement element = _document.MainDocumentPart.Document.Body;
                if (element != null)
                {
                    // Get plain text of content
                    _target.Content = GetPlainText(element);

                    // Cache length for later comparison
                    _target.ContentLength = _target.Content.Length;

                    _target.ContentHash = Core.Compare.Hash(_target.Content);
                }


                // Collect Meta Data
                _target.MetaCreator        = _document.PackageProperties.Creator;
                _target.MetaLastModifiedBy = _document.PackageProperties.LastModifiedBy;

                if (_document.PackageProperties.LastPrinted != null)
                {
                    _target.MetaDateLastPrinted = (DateTime)_document.PackageProperties.LastPrinted;
                }

                if (_document.PackageProperties.Created != null)
                {
                    _target.MetaDateCreated = (DateTime)_document.PackageProperties.Created;
                }

                if (_document.PackageProperties.Modified != null)
                {
                    _target.MetaDateModified = (DateTime)_document.PackageProperties.Modified;
                }

                _loaded = true;
            }
            catch (Exception e)
            {
                _target.Logging.Add("- " + Markdown.Bold("An exception occured when processing " + _target.AbsolutePath + ", " + e.Message, true));
            }
            return(_loaded);
        }
コード例 #25
0
            private async ValueTask <AdminCommandResult> BlockUserAsync(CachedMember target, CachedTextChannel channel,
                                                                        TimeSpan?duration, string reason)
            {
                channel ??= (CachedTextChannel)Context.Channel;

                if (channel.Overwrites.Any(x => x.TargetId == target.Id))
                {
                    return(CommandErrorLocalized("moderation_alreadyblocked", args: Markdown.Bold(target.Tag)));
                }

                var guild = await Context.Database.GetOrCreateGuildAsync(Context.Guild.Id);

                Mute mute = null;

                if (guild.Settings.HasFlag(GuildSettings.Punishments))
                {
                    var image  = new MemoryStream();
                    var format = ImageFormat.Default;
                    if (Context.Message.Attachments.FirstOrDefault() is { } attachment&&
                        attachment.FileName.HasImageExtension(out format))
                    {
                        var stream = await Http.GetStreamAsync(attachment.Url);

                        await stream.CopyToAsync(image);

                        image.Seek(0, SeekOrigin.Begin);
                    }

                    mute = new Mute(Context.Guild.Id, target.Id, Context.User.Id, reason, duration, channel.Id, image, format);
                    if (channel.Overwrites.FirstOrDefault(x => x.TargetId == target.Id) is CachedOverwrite overwrite)
                    {
                        mute.StoreOverwrite(overwrite);
                        await channel.DeleteOverwriteAsync(target.Id);
                    }
                    mute = Context.Database.Punishments.Add(mute).Entity as Mute;
                    await Context.Database.SaveChangesAsync();

                    await Punishments.LogMuteAsync(target, Context.Guild, Context.User, mute);
                }

                await channel.AddOrModifyOverwriteAsync(new LocalOverwrite(target,
                                                                           new OverwritePermissions().Deny(Permission.SendMessages).Deny(Permission.AddReactions)));

                return(duration.HasValue
                    ? CommandSuccessLocalized("moderation_block_temporary", args: new object[]
                {
                    (mute is { } ? $"`[#{mute.Id}]` " : string.Empty) + target.Format(),
コード例 #26
0
        public async Task <DiscordCommandResult> RemoveMainAsync(
            [Description("The emoji for the character you wish to remove.")]
            IGuildEmoji emoji)
        {
            if (!EmojiToRoleMap.TryGetValue(emoji.Id, out var roleId))
            {
                return(Response("That emoji doesn't belong to a character!"));
            }

            if (!Context.Author.RoleIds.Contains(roleId))
            {
                return(Response("You haven't added that character as a main!"));
            }

            await Context.Author.RevokeRoleAsync(roleId);

            return(Response($"You've abandoned {Markdown.Bold(Context.Guild.Roles[roleId].Name)} as a main. For shame!"));
        }
コード例 #27
0
        public async ValueTask <AdminCommandResult> RemoveAsync([Remainder] CachedRole role)
        {
            if (!(await Context.Database.SelfRoles.FindAsync(Context.Guild.Id.RawValue, role.Id.RawValue) is { }
                  selfRole))
            {
                return(CommandErrorLocalized("selfrole_invalid"));
            }

            var member = (CachedMember)Context.User;

            if (!member.Roles.ContainsKey(selfRole.RoleId))
            {
                return(CommandErrorLocalized("selfrole_remove_none"));
            }

            await member.RevokeRoleAsync(selfRole.RoleId);

            return(CommandSuccessLocalized("selfrole_remove_success", args: Markdown.Bold(role.Name.Sanitize())));
        }
コード例 #28
0
        private async ValueTask <AdminCommandResult> BanUserAsync(IUser target, string reason, Warning source = null)
        {
            if (!(await Context.Guild.GetBanAsync(target.Id) is null))
            {
                return(CommandErrorLocalized("moderation_alreadybanned", args: Markdown.Bold(target.Tag)));
            }

            var guild = await Context.Database.GetOrCreateGuildAsync(Context.Guild.Id);

            Ban ban = null;

            if (guild.Settings.HasFlag(GuildSettings.Punishments))
            {
                var image  = new MemoryStream();
                var format = ImageFormat.Default;
                if (Context.Message.Attachments.FirstOrDefault() is { } attachment&&
                    attachment.FileName.HasImageExtension(out format))
                {
                    var stream = await Http.GetStreamAsync(attachment.Url);

                    await stream.CopyToAsync(image);

                    image.Seek(0, SeekOrigin.Begin);
                }

                ban = Context.Database.Punishments
                      .Add(new Ban(Context.Guild.Id, target.Id, Context.User.Id, reason, null, image, format)).Entity as Ban;
                await Context.Database.SaveChangesAsync();

                await Punishments.LogBanAsync(target, Context.Guild, ban);

                source?.SetSecondaryPunishment(ban);
            }

            await Context.Guild.BanMemberAsync(target.Id,
                                               FormatAuditLogReason(reason ?? Context.Localize("punishment_noreason"),
                                                                    ban?.CreatedAt ?? DateTimeOffset.UtcNow, Context.User),
                                               7);

            Punishments.BannedUserIds.Add(target.Id);
            return(CommandSuccessLocalized("moderation_ban",
                                           args: (ban is { } ? $"`[#{ban.Id}]` " : string.Empty) + target.Format()));
コード例 #29
0
        /// <summary>
        /// Process the submissions absolute path
        /// </summary>
        /// <returns>Was the submission able to be loaded?</returns>
        public override bool Process()
        {
            _loaded = false;

            try
            {
                _target.Content       = File.ReadAllText(_target.AbsolutePath);
                _target.ContentLength = _target.Content.Length;
                _target.ContentHash   = Compare.Hash(_target.Content);


                _loaded = true;
            }
            catch (Exception e)
            {
                _target.Logging.Add("- " + Markdown.Bold("An exception occured when processing " + _target.AbsolutePath + ", " + e.Message));
            }

            return(_loaded);
        }
コード例 #30
0
        public async ValueTask <AdminCommandResult> AddAsync([Remainder] CachedRole role)
        {
            if (!(await Context.Database.SelfRoles.FindAsync(Context.Guild.Id.RawValue, role.Id.RawValue) is { }
                  selfRole))
            {
                return(CommandErrorLocalized("selfrole_invalid"));
            }

            var member = (CachedMember)Context.User;

            if (member.Roles.ContainsKey(selfRole.RoleId))
            {
                return(CommandErrorLocalized("selfrole_add_exists"));
            }

            if (selfRole.Groups.Length > 0)
            {
                var groupRoles = await Context.Database.SelfRoles
                                 .Where(x => x.GuildId == Context.Guild.Id && x.Groups.Length > 0)
                                 .ToListAsync();

                foreach (var group in selfRole.Groups)
                {
                    if (member.Roles.Values.FirstOrDefault(x =>
                                                           groupRoles.Any(y => y.RoleId == x.Id && y.Groups.Contains(group))) is { } exclusiveRole)
                    {
                        return(CommandErrorLocalized("selfrole_add_group_exists",
                                                     args: new object[]
                                                     { Markdown.Code(group.ToString()), Markdown.Bold(exclusiveRole.Name.Sanitize()) }));
                    }
                }

                // if (selfRole.Groups.FirstOrDefault(x => groupRoles.Any(y => y.Groups.Contains(x) && member.Roles.ContainsKey(y.RoleId))) is { } group)
                //     return CommandErrorLocalized("selfrole_add_group_exists", args: Markdown.Bold(group.ToString())); // Has a role in the group already
            }

            await member.GrantRoleAsync(selfRole.RoleId);

            return(CommandSuccessLocalized("selfrole_add_success", args: Markdown.Bold(role.Name.Sanitize())));
        }