Beispiel #1
0
        public async Task HandleAsync(MemberUpdatedEventArgs args)
        {
            var oldMember = args.OldMember;
            var newMember = args.NewMember;

            using var ctx = new AdminDatabaseContext(_provider);
            var language = (await ctx.GetOrCreateGuildAsync(args.NewMember.Guild.Id)).Language;
            var builder  = new LocalEmbedBuilder()
                           .WithSuccessColor()
                           .WithDescription(newMember.Format(false))
                           .WithTimestamp(DateTimeOffset.UtcNow);

            CachedTextChannel channel = null;

            // nickname
            if (!(newMember.Nick ?? string.Empty).Equals(oldMember.Nick ?? string.Empty,
                                                         StringComparison.OrdinalIgnoreCase))
            {
                channel = await ctx.GetLoggingChannelAsync(oldMember.Guild.Id, LogType.NicknameUpdate);

                builder.WithTitle(_localization.Localize(language, "logging_member_nickname"))
                .AddField(_localization.Localize(language, "logging_member_prevnick"),
                          oldMember.Nick?.Sanitize() ??
                          Markdown.Italics(_localization.Localize(language, "logging_member_noprevnick")))
                .AddField(_localization.Localize(language, "logging_member_newnick"),
                          newMember.Nick?.Sanitize() ??
                          Markdown.Italics(_localization.Localize(language, "logging_member_nonewnick")));
            }
            // role update
            else if (newMember.Roles.Count != oldMember.Roles.Count)
            {
                channel = await ctx.GetLoggingChannelAsync(oldMember.Guild.Id, LogType.UserRoleUpdate);

                var removedRoles = oldMember.Roles.Values.Where(x => !newMember.Roles.ContainsKey(x.Id)).ToList();
                var addedRoles   = newMember.Roles.Values.Where(x => !oldMember.Roles.ContainsKey(x.Id)).ToList();

                builder.WithTitle(_localization.Localize(language, "logging_member_roleupdate"));

                if (addedRoles.Count > 0)
                {
                    builder.AddField(_localization.Localize(language, "logging_member_addedroles"),
                                     string.Join('\n', addedRoles.Select(x => x.Format(false))));
                }

                if (removedRoles.Count > 0)
                {
                    builder.AddField(_localization.Localize(language, "logging_member_removedroles"),
                                     string.Join('\n', removedRoles.Select(x => x.Format(false))));
                }
            }

            if (channel is { })
        public static LocalEmbedBuilder GetModuleHelp(Module module)
        {
            if (module.Commands.Count == 0)
            {
                return(new LocalEmbedBuilder()
                       .WithTitle(module.FullAliases.FirstOrDefault() ?? module.Aliases.FirstOrDefault() ?? module.Name));
            }
            else if (module.Commands.Count <= 25)
            {
                var commandInfos = module.Commands.Select(x => GetCommandInfoField(x));
                var builder      = new LocalEmbedBuilder();
                foreach (var info in commandInfos)
                {
                    builder.AddField(info);
                }
                builder.Description = GetModuleInfoDescription(module);

                // TODO: Split based on max embed length (or x amount of fields + specific max length)
                return(builder
                       .WithTitle(module.FullAliases.FirstOrDefault() ?? module.Aliases.FirstOrDefault() ?? module.Name));
            }
            else
            {
                var commandInfos = module.Commands.Select(x => GetCommandHelp(x));

                // TODO: Split based on max embed length (or x amount of fields + specific max length)
                return(new LocalEmbedBuilder()
                       .WithDescription(string.Join("\n", commandInfos)).WithTitle(module.FullAliases.First()));
            }
        }
Beispiel #3
0
        public async Task HandleAsync(MessageDeletedEventArgs args)
        {
            if (!(args.Channel is CachedTextChannel channel) ||
                !args.Message.HasValue || args.Message.Value.Author.IsBot) // TODO: What to do when message doesn't have value, other than ignore
            {
                return;
            }

            using var ctx = new AdminDatabaseContext(_provider);
            var guild = await ctx.GetOrCreateGuildAsync(channel.Guild.Id);

            if (!(await ctx.GetLoggingChannelAsync(channel.Guild.Id, LogType.MessageDelete) is { } logChannel))
            {
                return;
            }

            var builder = new LocalEmbedBuilder()
                          .WithErrorColor()
                          .WithTitle(_localization.Localize(guild.Language, "logging_message_delete", channel.Tag))
                          .WithDescription(args.Message.Value.Author.Format(false))
                          .AddField(_localization.Localize(guild.Language, "info_id"), args.Message.Id)
                          .WithTimestamp(DateTimeOffset.UtcNow);

            if (!string.IsNullOrWhiteSpace(args.Message.Value.Content))
            {
                builder.AddField(_localization.Localize(guild.Language, "info_content"),
                                 args.Message.Value.Content.TrimTo(1024, true));
            }

            if (channel.Guild.CurrentMember.Permissions.ViewAuditLog)
            {
                await Task.Delay(TimeSpan.FromSeconds(1));

                var logs = await channel.Guild.GetAuditLogsAsync <RestMessagesDeletedAuditLog>(10);

                if (logs.FirstOrDefault(x =>
                                        x.TargetId == args.Message.Value.Author.Id && x.ChannelId == args.Channel.Id) is { } log)
                {
                    var moderator = await args.Client.GetOrDownloadUserAsync(log.ResponsibleUserId);

                    builder.WithTitle(_localization.Localize(guild.Language, "logging_message_delete_moderator", moderator.Tag, channel.Tag));
                }
            }

            if (_temporaryImages.Remove(args.Message.Id, out var attachment))
            {
                using (attachment)
                {
                    await logChannel.SendMessageAsync(attachment,
                                                      embed : builder
                                                      .WithImageUrl($"attachment://{attachment.FileName}")
                                                      .Build());
                }

                return;
            }

            await logChannel.SendMessageAsync(embed : builder.Build());
        }
        public static bool TryParseEmbed(string json, out LocalEmbedBuilder embed)
        {
            embed = new LocalEmbedBuilder();
            try
            {
                var embedDeserialized = JsonConvert.DeserializeObject <JsonEmbed>(json);

                var author      = embedDeserialized.Author;
                var title       = embedDeserialized.Title;
                var description = embedDeserialized.Description;

                var colorString = embedDeserialized.Color;
                var thumbnail   = embedDeserialized.Thumbnail;
                var image       = embedDeserialized.Image;
                var fields      = embedDeserialized.Fields;
                var footer      = embedDeserialized.Footer;
                var timestamp   = embedDeserialized.Timestamp;

                if (author != null)
                {
                    embed.WithAuthor(author);
                }

                if (!string.IsNullOrEmpty(title))
                {
                    embed.WithTitle(title);
                }

                if (!string.IsNullOrEmpty(description))
                {
                    embed.WithDescription(description);
                }

                if (!string.IsNullOrEmpty(colorString))
                {
                    embed.WithColor(HexToInt(colorString) ?? 0xFFFFFF);
                }

                if (!string.IsNullOrEmpty(thumbnail))
                {
                    embed.WithThumbnailUrl(thumbnail);
                }
                if (!string.IsNullOrEmpty(image))
                {
                    embed.WithImageUrl(image);
                }

                if (fields != null)
                {
                    foreach (var field in fields)
                    {
                        var fieldName   = field.Name;
                        var fieldValue  = field.Value;
                        var fieldInline = field.IsInline;

                        if (!string.IsNullOrEmpty(fieldName) && !string.IsNullOrEmpty(fieldValue))
                        {
                            embed.AddField(fieldName, fieldValue, fieldInline);
                        }
                    }
                }

                if (footer != null)
                {
                    embed.WithFooter(footer);
                }

                if (timestamp.HasValue)
                {
                    embed.WithTimestamp(timestamp.Value);
                }
                else if (embedDeserialized.WithCurrentTimestamp)
                {
                    embed.WithCurrentTimestamp();
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Beispiel #5
0
        private async Task HandleReceivedMessageAsync(CachedUserMessage message)
        {
            if (message.Author.IsBot)
            {
                return;
            }

            if (!(message.Channel is CachedTextChannel textChannel) ||
                !textChannel.Guild.CurrentMember.GetPermissionsFor(textChannel).Has(Permission.SendMessages))
            {
                return;
            }
            if (CommandUtilities.HasAnyPrefix(message.Content, Prefixes, StringComparison.CurrentCulture, out var prefix, out var output) ||
                CommandUtilities.HasPrefix(message.Content, $"<@{Client.CurrentUser.Id}>", StringComparison.Ordinal, out output) ||
                CommandUtilities.HasPrefix(message.Content, $"<@!{Client.CurrentUser.Id}>", StringComparison.Ordinal, out output))
            {
                if (string.IsNullOrWhiteSpace(output))
                {
                    return;
                }

                try
                {
                    if (prefix is null)
                    {
                        prefix = Client.CurrentUser.Mention;
                    }
                    var ctx = MummyContext.Create(Client, message, Services, prefix);


                    ActiveTimings[ctx.UserId] = Stopwatch.StartNew();
                    var r = await Commands.ExecuteAsync(output, ctx);

                    ActiveTimings[ctx.UserId].Stop();
                    ActiveTimings.Remove(ctx.UserId, out var st);
                    if (r.IsSuccessful)
                    {
                        LogService.LogInformation($"command: {ctx.Command.Name} has successful finished execution in {st.ElapsedMilliseconds}ms.", LogSource.MessagesService, ctx.GuildId);
                    }
                    else
                    {
                        switch (r)
                        {
                        case ExecutionFailedResult executionfailed:
                        {
                            LogService.LogError(executionfailed.ToString(), LogSource.MessagesService, ctx.GuildId, executionfailed.Exception);

                            break;
                        }

                        case ArgumentParseFailedResult parsefailed:
                        {
                            var eb = new LocalEmbedBuilder();
                            eb.WithAuthor(ctx.User);
                            eb.WithTitle("ArmgumentParseFailure");
                            eb.AddField(parsefailed.Reason, parsefailed.RawArguments);
                            await ctx.Channel.SendMessageAsync(embed : eb.Build());

                            break;
                        }

                        case ArgumentParserResult parseresult:
                        {
                            LogService.LogCritical("dunno argumentparse", LogSource.MessagesService, ctx.GuildId);
                            await ctx.Channel.SendMessageAsync("a error has occoured and not been handled this error will be resolved shortly. (hopefully)");

                            break;
                        }

                        case ChecksFailedResult checksfailed:
                        {
                            var eb = new LocalEmbedBuilder();
                            eb.WithAuthor(ctx.User);
                            eb.WithTitle($"{checksfailed.FailedChecks.Count} checks have failed");
                            foreach (var(Check, Result) in checksfailed.FailedChecks)
                            {
                                eb.AddField((Check as MummyCheckBase).Name, Result.Reason, true);
                            }
                            await ctx.Channel.SendMessageAsync(embed : eb.Build());

                            break;
                        }

                        case CommandDisabledResult disabled:
                        {
                            var eb = new LocalEmbedBuilder();
                            eb.WithAuthor(ctx.User);
                            await ctx.Channel.SendMessageAsync();

                            eb.WithTitle($"{disabled.Command} is currently diabled");

                            await ctx.Channel.SendMessageAsync(embed : eb.Build());

                            break;
                        }

                        case CommandNotFoundResult notfound:
                        {
                            var eb = new LocalEmbedBuilder();
                            eb.WithAuthor(ctx.User);
                            eb.WithTitle($"command with name {notfound.Reason}");
                            await ctx.Channel.SendMessageAsync(embed : eb.Build());

                            break;
                        }

                        case CommandOnCooldownResult oncooldown:
                        {
                            var eb = new LocalEmbedBuilder();
                            eb.WithAuthor(ctx.User);
                            eb.WithTitle($"{oncooldown.Command.Name} is currently on cooldown");
                            foreach (var(cooldown, retryafter) in oncooldown.Cooldowns)
                            {
                                int index     = cooldown.ToString().LastIndexOf('.');
                                var bucketype = (CooldownBucketType)cooldown.BucketType;
                                eb.AddField(cooldown.ToString().Substring(index + 1), $"is only allowed to be run {cooldown.Amount} per {cooldown.Per.Humanize()} and it forced per {bucketype}, currently locked for {retryafter.TotalMinutes} Minutes", true);
                            }
                            await ctx.Channel.SendMessageAsync(embed : eb.Build());

                            break;
                        }

                        case OverloadsFailedResult overloadsFailed:
                        {
                            var eb = new LocalEmbedBuilder();
                            eb.WithAuthor(ctx.User);
                            eb.WithDescription(overloadsFailed.Reason);
                            foreach (var(command, overloadResult) in overloadsFailed.FailedOverloads)
                            {
                                eb.AddField($"{command.Name} {string.Join(' ', command.Parameters.Select(x => x.Name))}", overloadResult.Reason);
                            }

                            await ctx.Channel.SendMessageAsync(embed : eb.Build());

                            break;
                        }

                        case ParameterChecksFailedResult paramcheckfailed:
                        {
                            var eb = new LocalEmbedBuilder();
                            eb.WithAuthor(ctx.User);
                            eb.WithTitle($"checks on {paramcheckfailed.Parameter} have failed with provided argument: {paramcheckfailed.Argument}");
                            foreach (var(Check, Result) in paramcheckfailed.FailedChecks)
                            {
                                var index = Check.ToString().LastIndexOf('.');
                                var name  = Check.ToString().Substring(index + 1);
                                eb.AddField(name, Result.Reason);
                            }
                            break;
                        }

                        case TypeParseFailedResult typeParseFailed:
                        {
                            var eb = new LocalEmbedBuilder();
                            eb.WithAuthor(ctx.User);
                            eb.AddField(typeParseFailed.Parameter.Name, typeParseFailed.Reason);
                            await ctx.Channel.SendMessageAsync(embed : eb.Build());

                            break;
                        }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogService.LogError("Issue with message service", LogSource.MessagesService, exception: ex);
                }
            }
        }
Beispiel #6
0
        public async Task Eval([Remainder] string code)
        {
            var builder = new LocalEmbedBuilder
            {
                Title       = "Evaluating Code...",
                Color       = Color.DarkRed,
                Description = "Waiting for completion...",
                Author      = new LocalEmbedAuthorBuilder
                {
                    IconUrl = Context.User.GetAvatarUrl(),
                    Name    = Context.User.DisplayName
                },
                Timestamp    = DateTimeOffset.UtcNow,
                ThumbnailUrl = Context.Guild.CurrentMember.GetAvatarUrl()
            };
            var msg = await ReplyAsync(embed : builder);

            var sw     = Stopwatch.StartNew();
            var script = EvalService.Build(code);

            string snippet = string.Join(Environment.NewLine, script.Code.Split(Environment.NewLine.ToCharArray()).Where(line => !line.StartsWith("using")));

            var diagnostics     = script.Compile();
            var compilationTime = sw.ElapsedMilliseconds;

            if (diagnostics.Any(x => x.Severity == DiagnosticSeverity.Error))
            {
                builder.WithDescription($"Compilation finished in: {compilationTime}ms");
                builder.WithColor(Color.Red);
                builder.WithTitle("Failed Evaluation");

                builder.AddField("Code", $"```cs{Environment.NewLine}{snippet}```");
                builder.AddField("Compilation Errors", string.Join('\n', diagnostics.Select(x => $"{x}")));

                await msg.ModifyAsync(x => x.Embed = builder.Build());

                return;
            }
            sw.Restart();

            var context = new RoslynContext(Context, Services);

            try
            {
                var result = await script.RunAsync(context);

                sw.Stop();
                builder.WithColor(Color.Green);

                builder.WithDescription($"Code compiled in {compilationTime}ms and ran in {sw.ElapsedMilliseconds}ms");
                builder.WithTitle("Code Evaluated");
                builder.AddField("Code", $"```cs{Environment.NewLine}{snippet}```");

                if (!(result.ReturnValue is null))
                {
                    var sb     = new StringBuilder();
                    var type   = result.ReturnValue.GetType();
                    var rValue = result.ReturnValue;

                    switch (rValue)
                    {
                    case Color col:
                        builder.WithColor(col);
                        builder.AddField("Colour", $"{col.RawValue}");
                        break;

                    case string str:
                        builder.AddField($"{type}", $"\"{str}\"");
                        break;

                    case IEnumerable enumerable:

                        var list     = enumerable.Cast <object>().ToList();
                        var enumType = enumerable.GetType();

                        if (list.Count > 25)
                        {
                            builder.AddField($"{enumType}", $"Enumerable has more than 10 elements ({list.Count})");
                            break;
                        }

                        if (list.Count > 0)
                        {
                            sb.AppendLine("```css");

                            foreach (var element in list)
                            {
                                sb.Append('[').Append(element).AppendLine("]");
                            }

                            sb.AppendLine("```");
                        }
                        else
                        {
                            sb.AppendLine("Collection is empty");
                        }

                        builder.AddField($"{enumType}", sb.ToString());

                        break;

                    case Enum @enum:

                        builder.AddField($"{@enum.GetType()}", $"```\n{@enum.Humanize()}\n```");

                        break;

                    default:

                        var messages = rValue.Inspect();

                        if (type.IsValueType && messages.Count == 0)
                        {
                            builder.AddField($"{type}", rValue);
                        }

                        foreach (var message in messages)
                        {
                            await ReplyAsync($"```css\n{message}\n```");
                        }

                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                sw.Stop();


                builder.WithDescription($"Code evaluated in {sw.ElapsedMilliseconds}ms but there was a issue tho");
                builder.WithColor(Color.Red);
                builder.WithTitle("Failed Evaluation");
                builder.AddField("Code", $"```cs{Environment.NewLine}{snippet}```");

                var str = ex.ToString();

                builder.AddField("Exception", Format.Sanitize(str.Length >= 1000 ? str.Substring(0, 1000) : str));
            }
            finally
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

            await msg.ModifyAsync(x => x.Embed = builder.Build());
        }
 public LocalizedEmbedBuilder WithTitle(string title)
 {
     _builder.WithTitle(title);
     return(this);
 }
Beispiel #8
0
        public async Task HelpAsync()
        {
            var options = PaginatedAppearanceOptions.Default;
            var msg     = new PaginatedMessage {
                Options = options
            };
            var infoemb = new LocalEmbedBuilder();

            infoemb.AddField("optional", $"*value*", true);
            infoemb.AddField("remainder", "__value__", true);
            infoemb.AddField("required", "**value**", true);
            infoemb.WithDescription("for example: !command __*cookies this can contain spaces*__ this  means the command take a optional remainder");

            msg.Pages.Add(infoemb);

            foreach (var module in Commands.GetAllModules())
            {
                try
                {
                    var modulecheck = await module.RunChecksAsync(Context);

                    if (modulecheck.IsSuccessful)
                    {
                        if (module.Commands.Count == 0)
                        {
                            continue; //skip module if commands are 0
                        }
                        if (module.Parent != null)
                        {
                            continue;
                        }

                        var emb = new LocalEmbedBuilder();
                        emb.WithTitle(module.Name);
                        emb.WithAuthor(Context.User.DisplayName, Context.User.GetAvatarUrl());
                        var sb       = new StringBuilder();
                        var commands = CommandUtilities.EnumerateAllCommands(module);
                        foreach (var command in commands)
                        {
                            var checks = await command.RunChecksAsync(Context);

                            if (checks.IsSuccessful)
                            {
                                sb.Append(Context.PrefixUsed).Append(command.Name).Append(" ");
                                foreach (var parameter in command.Parameters)
                                {
                                    if (parameter.IsOptional && parameter.IsRemainder)//optional remiander
                                    {
                                        sb.Append($"__*{parameter.Name}*__ ");
                                    }
                                    else if (parameter.IsOptional && !parameter.IsRemainder)//optional
                                    {
                                        sb.Append($"*{parameter.Name}* ");
                                    }
                                    else if (!parameter.IsOptional && parameter.IsRemainder) //required remainder
                                    {
                                        sb.Append($"__**{parameter.Name}**__ ");
                                    }
                                    else if (!parameter.IsOptional && !parameter.IsRemainder)//required
                                    {
                                        sb.Append($"**{parameter.Name}** ");
                                    }
                                }
                                sb.AppendLine();
                            }
                        }
                        emb.WithDescription(sb.ToString());

                        msg.Pages.Add(emb);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
            await new PaginatedMessageCallback(Iservice, Context, msg, new EnsureReactionFromUser(Context.User)).DisplayAsync();
        }