public async Task HandleAsync(MemberLeftEventArgs args) { using var ctx = new AdminDatabaseContext(_provider); var guild = await ctx.GetOrCreateGuildAsync(args.Guild.Id); if (string.IsNullOrWhiteSpace(guild.Goodbye)) { return; } var goodbye = await guild.Goodbye.FormatPlaceHoldersAsync( AdminCommandContext.MockContext(guild.Language, _provider, args.User, args.Guild)); if (!(await ctx.GetLoggingChannelAsync(args.Guild.Id, LogType.Goodbye) is { } channel)) { return; } if (JsonEmbed.TryParse(goodbye, out var embed)) { await channel.SendMessageAsync(embed.Text ?? string.Empty, embed : embed.ToLocalEmbed()); return; } await channel.SendMessageAsync(goodbye); }
public async Task HandleAsync(MessageReceivedEventArgs args) { if (!(args.Message is CachedUserMessage message) || message.Author.IsBot || string.IsNullOrWhiteSpace(message.Content)) { return; } var prefixes = new List <string> { _config.DefaultPrefix }; LocalizedLanguage language; using var ctx = new AdminDatabaseContext(_provider); if (message.Channel is IGuildChannel guildChannel) { Guild guild = null; if (!_languages.TryGetValue(guildChannel.GuildId, out language)) { guild = await ctx.GetOrCreateGuildAsync(guildChannel.GuildId); _languages[guild.Id] = language = guild.Language; } if (!_guildPrefixes.TryGetValue(guildChannel.GuildId, out var customPrefixes)) { guild ??= await ctx.GetOrCreateGuildAsync(guildChannel.GuildId); _guildPrefixes[guild.Id] = customPrefixes = guild.CustomPrefixes; } prefixes.AddRange(customPrefixes); } else if (!_languages.TryGetValue(message.Author.Id, out language)) { var user = await ctx.GetOrCreateGlobalUserAsync(message.Author.Id); _languages[user.Id] = language = user.Language; } if (!CommandUtilities.HasAnyPrefix(message.Content, prefixes, StringComparison.OrdinalIgnoreCase, out var prefix, out var input)) { return; } var context = new AdminCommandContext(message, prefix, language, _provider); IResult result; if (!context.IsPrivate && await ctx.CommandAliases .FirstOrDefaultAsync(x => x.GuildId == context.Guild.Id && input.StartsWith(x.Alias, StringComparison.InvariantCultureIgnoreCase)) is { } alias) { result = await _commands.ExecuteAsync(alias, input, context); }
public async Task <string> ReplaceCommandAsync(string command, AdminCommandContext context) { var formattedCommand = await Command.FormatPlaceHoldersAsync(context); return(new Regex($@"{Alias}\b", RegexOptions.IgnoreCase) .Replace(command, Replace, 1)); string Replace(Match match) => formattedCommand; }
public async Task <bool> TryExecuteCommandAsync(SocketUserMessage userMessage) { if (userMessage.Source != MessageSource.User || string.IsNullOrWhiteSpace(userMessage.Content)) { return(false); } var prefixes = new List <string> { _config.DefaultPrefix, $"<@{_client.CurrentUser.Id}> ", $"<@!{_client.CurrentUser.Id}> " }; LocalizedLanguage language; using (var ctx = new AdminDatabaseContext(_provider)) { if (userMessage.Channel is IGuildChannel guildChannel) { var guild = await ctx.GetOrCreateGuildAsync(guildChannel.GuildId); prefixes.AddRange(guild.CustomPrefixes); language = guild.Language; } else { var user = await ctx.GetOrCreateGlobalUserAsync(userMessage.Author.Id); language = user.Language; } } if (!CommandUtilities.HasAnyPrefix(userMessage.Content, prefixes, StringComparison.OrdinalIgnoreCase, out var prefix, out var input)) { return(false); } var context = new AdminCommandContext(userMessage, prefix, language, _provider); var result = await _commands.ExecuteAsync(input, context, _provider); if (!(result is FailedResult failedResult)) { return(true); } // TODO: localized error messages, log var error = new StringBuilder() .Append(failedResult switch { ParameterChecksFailedResult parameterChecksResult => string.Join('\n', parameterChecksResult.FailedChecks.Select(x => x.Error)), ChecksFailedResult checkResult => string.Join('\n', checkResult.FailedChecks.Select(x => x.Error)), ExecutionFailedResult execResult => GenerateException(execResult.Exception), CommandNotFoundResult _ => string.Empty, _ => failedResult.Reason }).ToString();
public PunishmentPaginator(List <List <Punishment> > pages, int currentPage, ulong targetId, PunishmentListType type, AdminCommandContext context) : base(new[] { EmojiTools.Left, EmojiTools.Right }) { _pages = pages; _currentPage = currentPage; _targetId = targetId; _type = type; _context = context; _tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30)); _cachedUsers = new Dictionary <ulong, IUser>(); Task.Delay(-1, _tokenSource.Token).ContinueWith(_ => DisposeAsync()); }
public async Task HandleAsync(MemberJoinedEventArgs args) { using var ctx = new AdminDatabaseContext(_provider); var guild = await ctx.GetOrCreateGuildAsync(args.Member.Guild.Id); if (string.IsNullOrWhiteSpace(guild.Greeting)) { return; } var greeting = await guild.Greeting.FormatPlaceHoldersAsync( AdminCommandContext.MockContext(guild.Language, _provider, args.Member, args.Member.Guild)); var hasEmbed = JsonEmbed.TryParse(greeting, out var embed); if (guild.DmGreeting) { if (hasEmbed) { _ = args.Member.SendMessageAsync(embed.Text ?? string.Empty, embed: embed.ToLocalEmbed()); } else { _ = args.Member.SendMessageAsync(greeting); } return; } if (!(await ctx.GetLoggingChannelAsync(args.Member.Guild.Id, LogType.Greeting) is { } channel)) { return; } if (hasEmbed) { await channel.SendMessageAsync(embed.Text ?? string.Empty, embed : embed.ToLocalEmbed()); return; } await channel.SendMessageAsync(greeting); }
public async Task <Stream> CreateXpImageAsync(AdminCommandContext context, CachedUser target) { var output = new MemoryStream(); try { var user = await context.Database.GetOrCreateGlobalUserAsync(target.Id); var globalUsers = await context.Database.GlobalUsers.OrderByDescending(x => x.TotalXp).ToListAsync(); GuildUser guildUser = null; Guild guild = null; Stream guildIcon = null; var guildPosition = 1; if (target is CachedMember guildTarget) { guildUser = await context.Database.GetOrCreateGuildUserAsync(target.Id, guildTarget.Guild.Id); guild = await context.Database.GetOrCreateGuildAsync(guildTarget.Guild.Id); guildIcon = await _http.GetStreamAsync(guildTarget.Guild.GetIconUrl()); var guildUsers = await context.Database.GuildUsers.OrderByDescending(x => x.TotalXp).ToListAsync(); guildPosition = guildUsers.IndexOf(guildUser) + 1; } var guildOffset = guild?.Settings.HasFlag(GuildSettings.XpTracking) == true ? 45 : 0; using var background = Image.Load <Rgba32>(new FileStream("./Data/Images/01.png", FileMode.Open)); using var avatarStream = await _http.GetStreamAsync(target.GetAvatarUrl()); using var avatar = Image.Load <Rgba32>(avatarStream); using var canvas = new Image <Rgba32>(Configuration.Default, 450, 300); using var currentLevelStream = await _http.GetStreamAsync(EmojiTools.GetUrl(GetLevelEmoji(user))); using var currentLevel = Image.Load <Rgba32>(currentLevelStream); currentLevel.Mutate(x => x.Resize(45 / currentLevel.Height * currentLevel.Width, 45)); Stream currentGuildLevelStream = null; if (guildUser is { }) { currentGuildLevelStream = await _http.GetStreamAsync(EmojiTools.GetUrl(GetLevelEmoji(guildUser))); } canvas.Mutate(cnvs => { var sb = new StringBuilder(); foreach (var c in target.Name) { if (char.IsLetterOrDigit(c)) { sb.Append(c); } } sb.Append($"#{target.Discriminator}"); var userFontSize = 20; var box = TextMeasurer.MeasureBounds(sb.ToString(), new RendererOptions(ImageTools.Fonts.TF2(userFontSize))); while (box.Width > 420 || box.Height > 20) { box = TextMeasurer.MeasureBounds(sb.ToString(), new RendererOptions(ImageTools.Fonts.TF2(--userFontSize))); } // Draw XP image (background) cnvs.DrawImage(background, PixelColorBlendingMode.Normal, 1); // Draw outer bounding box cnvs.FillPolygon(ImageTools.Colors.DarkButTransparent, new PointF(10, 190 - guildOffset), new PointF(440, 190 - guildOffset), /* * new PointF(440, 210 - guildReduction), * new PointF(10, 210 - guildReduction), * new PointF(440, 210 - guildReduction), */ new PointF(440, 290 - guildOffset), new PointF(10, 290 - guildOffset)); // Draw avatar bounding box cnvs.FillPolygon(ImageTools.Colors.Blurple, new PointF(385, 215 - guildOffset), new PointF(435, 215 - guildOffset), new PointF(435, 265 - guildOffset), new PointF(385, 265 - guildOffset)); // Draw avatar cnvs.DrawImage(avatar.Clone(x => x.Resize(50, 50)), new Point(385, 215 - guildOffset), PixelColorBlendingMode.Normal, PixelAlphaCompositionMode.SrcOver, 1); // Draw avatar bounding box outline cnvs.DrawPolygon(Rgba32.WhiteSmoke, 2, new PointF(386, 216 - guildOffset), new PointF(434, 216 - guildOffset), new PointF(434, 264 - guildOffset), new PointF(386, 264 - guildOffset)); // Write username cnvs.DrawText(sb.ToString().Trim(), ImageTools.Fonts.TF2(userFontSize), Rgba32.WhiteSmoke, new PointF(15, 195 - guildOffset)); /* Write user info * if (!string.IsNullOrWhiteSpace(global.Info)) * { * cnvs.DrawText(new TextGraphicsOptions { WrapTextWidth = 350 }, * global.Info, * ImageTools.Fonts.TF2Secondary(13), * Rgba32.WhiteSmoke, * new PointF(15, 215 - guildOffset)); * }*/ // Draw inner box (XP bar outline) cnvs.FillPolygon(ImageTools.Colors.LessDark, new PointF(75, 272 - guildOffset), new PointF(435, 272 - guildOffset), new PointF(435, 285 - guildOffset), new PointF(75, 285 - guildOffset)); // Draw current XP bar cnvs.FillPolygon(ImageTools.Colors.XpBar, new PointF(77, 274 - guildOffset), new PointF(356F * ((float)user.CurrentLevelXp / user.NextLevelXp) + 77, 274 - guildOffset), new PointF(356F * ((float)user.CurrentLevelXp / user.NextLevelXp) + 77, 283 - guildOffset), new PointF(77, 283 - guildOffset)); // Write current level text cnvs.DrawText(new TextGraphicsOptions { HorizontalAlignment = HorizontalAlignment.Center }, $"Tier {user.Tier}, Level {user.Level} ({user.Grade} Grade)", ImageTools.Fonts.TF2(13), ImageTools.Colors.GetGradeColor(user.Grade), new PointF(255, 259 - guildOffset)); // Write current XP text cnvs.DrawText(new TextGraphicsOptions { HorizontalAlignment = HorizontalAlignment.Center }, $"{user.TotalXp} / {user.NextLevelTotalXp} XP", ImageTools.Fonts.TF2(13), Rgba32.WhiteSmoke, new PointF(255, 273 - guildOffset)); // Draw current level cnvs.DrawImage( currentLevel.Clone(x => x.Resize(45 / currentLevel.Height * currentLevel.Width, 45)), ImageTools.Justify(new Point(45, 285 - guildOffset), currentLevel, Justification.BottomCenter), PixelColorBlendingMode.Normal, PixelAlphaCompositionMode.SrcOver, 1); // Write current global position cnvs.DrawText(new TextGraphicsOptions { HorizontalAlignment = HorizontalAlignment.Center }, $"Global position #{globalUsers.IndexOf(user) + 1}", ImageTools.Fonts.TF2(11), Rgba32.WhiteSmoke, new PointF(255, 248 - guildOffset)); if (guildUser is { } && guildOffset > 0) { // Draw guild bounding box // 270 cnvs.FillPolygon(ImageTools.Colors.DarkButTransparent, new PointF(10, 250), new PointF(440, 250), new PointF(440, 295), new PointF(10, 295)); // Draw guild XP bar outline cnvs.FillPolygon(ImageTools.Colors.LessDark, new PointF(75, 277), new PointF(435, 277), new PointF(435, 290), new PointF(75, 290)); // Draw guild XP bar cnvs.FillPolygon(ImageTools.Colors.XpBar, new PointF(77, 279), new PointF(356F * ((float)guildUser.CurrentLevelXp / guildUser.NextLevelXp) + 77, 279), new PointF(356F * ((float)guildUser.CurrentLevelXp / guildUser.NextLevelXp) + 77, 288), new PointF(77, 288)); // Write current guild level text cnvs.DrawText(new TextGraphicsOptions { HorizontalAlignment = HorizontalAlignment.Center }, $"Tier {guildUser.Tier}, Level {guildUser.Level} ({guildUser.Grade} Grade)", ImageTools.Fonts.TF2(13), ImageTools.Colors.GetGradeColor(guildUser.Grade), new PointF(255, 264)); // Write current guild XP text cnvs.DrawText(new TextGraphicsOptions { HorizontalAlignment = HorizontalAlignment.Center }, $"{guildUser.TotalXp} / {guildUser.NextLevelTotalXp} XP", ImageTools.Fonts.TF2(13), Rgba32.WhiteSmoke, new PointF(255, 278)); // using (var guildLevel = Image.Load(guildLevelStream)) using var guildImage = Image.Load <Rgba32>(guildIcon); using var currentGuildLevel = Image.Load <Rgba32>(currentGuildLevelStream); currentGuildLevel.Mutate(x => x.Resize(40 / currentGuildLevel.Height * currentGuildLevel.Width, 40)); // Draw current guild level cnvs.DrawImage(currentGuildLevel, ImageTools.Justify(new Point(45, 292), currentGuildLevel, Justification.BottomCenter), PixelColorBlendingMode.Normal, PixelAlphaCompositionMode.SrcOver, 1); // Draw current guild icon guildImage.Mutate(img => img.Resize(18, 18)); cnvs.DrawImage(guildImage, ImageTools.Justify(new Point(435, 255), guildImage, Justification.TopRight), PixelColorBlendingMode.Normal, PixelAlphaCompositionMode.SrcOver, 1f); // Write current guild position cnvs.DrawText(new TextGraphicsOptions { HorizontalAlignment = HorizontalAlignment.Center }, $"Guild position #{guildPosition}", ImageTools.Fonts.TF2(11), Rgba32.WhiteSmoke, new PointF(255, 253)); } });
public async ValueTask <AdminCommandResult> TriggerAsync() { var guild = await Context.Database.GetOrCreateGuildAsync(Context.Guild.Id); if (string.IsNullOrWhiteSpace(guild.Greeting)) { return(CommandErrorLocalized("guild_greeting_empty")); } var channel = await Context.Database.GetLoggingChannelAsync(Context.Guild.Id, LogType.Greeting); var greeting = await guild.Greeting.FormatPlaceHoldersAsync( AdminCommandContext.MockContext(Context.Language, Provider, Context.User, Context.Guild), Context.User.Mention, Random); JsonEmbed embed; if (!guild.DmGreeting) { if (channel is null) { return(CommandErrorLocalized("guild_greeting_nochannel")); } IUserMessage message; if (JsonEmbed.TryParse(greeting, out embed)) { message = await channel.SendMessageAsync(embed.Text ?? string.Empty, embed : embed.ToLocalEmbed()); } else { message = await channel.SendMessageAsync(greeting); } if (guild.GreetingDuration.HasValue) { _ = Task.Run(async() => await Task.Delay(guild.GreetingDuration.Value) .ContinueWith(_ => message.DeleteAsync())); } await Context.Message.AddReactionAsync(EmojiTools.Checkmark); return(CommandSuccess()); } if (JsonEmbed.TryParse(greeting, out embed)) { try { await Context.User.SendMessageAsync(embed.Text ?? string.Empty, embed : embed.ToLocalEmbed()); await Context.Message.AddReactionAsync(EmojiTools.Checkmark); } catch (DiscordHttpException ex) when(ex.JsonErrorCode == JsonErrorCode.CannotSendMessagesToThisUser) { await Context.Message.AddReactionAsync(EmojiTools.X); } } else { try { await Context.User.SendMessageAsync(greeting); await Context.Message.AddReactionAsync(EmojiTools.Checkmark); } catch (DiscordHttpException ex) when(ex.JsonErrorCode == JsonErrorCode.CannotSendMessagesToThisUser) { await Context.Message.AddReactionAsync(EmojiTools.X); } } return(CommandSuccess()); }