diff --git a/Boyfriend.cs b/Boyfriend.cs index f22da61..c5c8a73 100644 --- a/Boyfriend.cs +++ b/Boyfriend.cs @@ -14,8 +14,8 @@ public static class Boyfriend { private static readonly DiscordSocketConfig Config = new() { MessageCacheSize = 250, GatewayIntents - = (GatewayIntents.AllUnprivileged | GatewayIntents.MessageContent | GatewayIntents.GuildMembers) & - ~GatewayIntents.GuildInvites, + = (GatewayIntents.AllUnprivileged | GatewayIntents.MessageContent | GatewayIntents.GuildMembers) + & ~GatewayIntents.GuildInvites, AlwaysDownloadUsers = true, AlwaysResolveStickers = false, AlwaysDownloadDefaultStickers = false, @@ -23,10 +23,11 @@ public static class Boyfriend { }; private static DateTimeOffset _nextSongAt = DateTimeOffset.MinValue; - private static uint _nextSongIndex; + private static uint _nextSongIndex; private static readonly Tuple[] ActivityList = { - Tuple.Create(new Game("Masayoshi Minoshima (ft. nomico) - Bad Apple!!", ActivityType.Listening), + Tuple.Create( + new Game("Masayoshi Minoshima (ft. nomico) - Bad Apple!!", ActivityType.Listening), new TimeSpan(0, 3, 40)), Tuple.Create(new Game("Xi - Blue Zenith", ActivityType.Listening), new TimeSpan(0, 4, 16)), Tuple.Create(new Game("Kurokotei - Scattered Faith", ActivityType.Listening), new TimeSpan(0, 8, 21)), @@ -75,8 +76,10 @@ public static class Boyfriend { try { Task.WaitAll(GuildTickTasks.ToArray()); } catch (AggregateException ex) { foreach (var exc in ex.InnerExceptions) - await Log(new LogMessage(LogSeverity.Error, nameof(Boyfriend), - "Exception while ticking guilds", exc)); + await Log( + new LogMessage( + LogSeverity.Error, nameof(Boyfriend), + "Exception while ticking guilds", exc)); } GuildTickTasks.Clear(); @@ -115,10 +118,13 @@ public static class Boyfriend { var saveData = false; _ = int.TryParse(config["EventEarlyNotificationOffset"], out var offset); foreach (var schEvent in guild.Events) - if (schEvent.Status is GuildScheduledEventStatus.Scheduled && config["AutoStartEvents"] is "true" && - DateTimeOffset.Now >= schEvent.StartTime) { await schEvent.StartAsync(); } else if - (!data.EarlyNotifications.Contains(schEvent.Id) && - DateTimeOffset.Now >= schEvent.StartTime.Subtract(new TimeSpan(0, offset, 0))) { + if (schEvent.Status is GuildScheduledEventStatus.Scheduled + && config["AutoStartEvents"] is "true" + && DateTimeOffset + .Now + >= schEvent.StartTime) await schEvent.StartAsync(); + else if (!data.EarlyNotifications.Contains(schEvent.Id) + && DateTimeOffset.Now >= schEvent.StartTime.Subtract(new TimeSpan(0, offset, 0))) { data.EarlyNotifications.Add(schEvent.Id); var receivers = config["EventStartedReceivers"]; var role = guild.GetRole(ulong.Parse(config["EventNotificationRole"])); @@ -127,42 +133,43 @@ public static class Boyfriend { if (receivers.Contains("role") && role is not null) mentions.Append($"{role.Mention} "); if (receivers.Contains("users") || receivers.Contains("interested")) mentions = (await schEvent.GetUsersAsync(15)) - .Where(user => role is null || !((RestGuildUser)user).RoleIds.Contains(role.Id)) - .Aggregate(mentions, (current, user) => current.Append($"{user.Mention} ")); + .Where(user => role is null || !((RestGuildUser)user).RoleIds.Contains(role.Id)) + .Aggregate(mentions, (current, user) => current.Append($"{user.Mention} ")); - await Utils.GetEventNotificationChannel(guild)?.SendMessageAsync(string.Format( - Messages.EventEarlyNotification, - mentions, - Utils.Wrap(schEvent.Name), - schEvent.StartTime.ToUnixTimeSeconds().ToString()))!; + await Utils.GetEventNotificationChannel(guild)?.SendMessageAsync( + string.Format( + Messages.EventEarlyNotification, + mentions, + Utils.Wrap(schEvent.Name), + schEvent.StartTime.ToUnixTimeSeconds().ToString()))!; mentions.Clear(); } foreach (var mData in data.MemberData.Values) { if (DateTimeOffset.Now >= mData.BannedUntil) _ = guild.RemoveBanAsync(mData.Id); + if (!mData.IsInGuild) continue; - if (mData.IsInGuild) { - if (DateTimeOffset.Now >= mData.MutedUntil) { - await Utils.UnmuteMemberAsync(data, Client.CurrentUser.ToString(), guild.GetUser(mData.Id), - Messages.PunishmentExpired); - saveData = true; + if (DateTimeOffset.Now >= mData.MutedUntil) { + await Utils.UnmuteMemberAsync( + data, Client.CurrentUser.ToString(), guild.GetUser(mData.Id), + Messages.PunishmentExpired); + saveData = true; + } + + for (var i = mData.Reminders.Count - 1; i >= 0; i--) { + var reminder = mData.Reminders[i]; + if (DateTimeOffset.Now < reminder.RemindAt) continue; + + var channel = guild.GetTextChannel(reminder.ReminderChannel); + if (channel is null) { + await Utils.SendDirectMessage(Client.GetUser(mData.Id), reminder.ReminderText); + continue; } - for (var i = mData.Reminders.Count - 1; i >= 0; i--) { - var reminder = mData.Reminders[i]; - if (DateTimeOffset.Now >= reminder.RemindAt) { - var channel = guild.GetTextChannel(reminder.ReminderChannel); - if (channel is null) { - await Utils.SendDirectMessage(Client.GetUser(mData.Id), reminder.ReminderText); - continue; - } + await channel.SendMessageAsync($"<@{mData.Id}> {Utils.Wrap(reminder.ReminderText)}"); + mData.Reminders.RemoveAt(i); - await channel.SendMessageAsync($"<@{mData.Id}> {Utils.Wrap(reminder.ReminderText)}"); - mData.Reminders.RemoveAt(i); - - saveData = true; - } - } + saveData = true; } } diff --git a/CommandProcessor.cs b/CommandProcessor.cs index c20603c..739ab4d 100644 --- a/CommandProcessor.cs +++ b/CommandProcessor.cs @@ -18,9 +18,9 @@ public sealed class CommandProcessor { }; private readonly StringBuilder _stackedPrivateFeedback = new(); - private readonly StringBuilder _stackedPublicFeedback = new(); - private readonly StringBuilder _stackedReplyMessage = new(); - private readonly List _tasks = new(); + private readonly StringBuilder _stackedPublicFeedback = new(); + private readonly StringBuilder _stackedReplyMessage = new(); + private readonly List _tasks = new(); public readonly SocketCommandContext Context; @@ -47,8 +47,10 @@ public sealed class CommandProcessor { try { Task.WaitAll(_tasks.ToArray()); } catch (AggregateException e) { foreach (var ex in e.InnerExceptions) - await Boyfriend.Log(new LogMessage(LogSeverity.Error, nameof(CommandProcessor), - "Exception while executing commands", ex)); + await Boyfriend.Log( + new LogMessage( + LogSeverity.Error, nameof(CommandProcessor), + "Exception while executing commands", ex)); } _tasks.Clear(); @@ -74,7 +76,8 @@ public sealed class CommandProcessor { } public void Reply(string response, string? customEmoji = null) { - Utils.SafeAppendToBuilder(_stackedReplyMessage, $"{customEmoji ?? ReplyEmojis.Success} {response}", + Utils.SafeAppendToBuilder( + _stackedReplyMessage, $"{customEmoji ?? ReplyEmojis.Success} {response}", Context.Message); } @@ -91,15 +94,18 @@ public sealed class CommandProcessor { _ = Context.Message.ReplyAsync(_stackedReplyMessage.ToString(), false, null, AllowedMentions.None); var data = GuildData.Get(Context.Guild); - var adminChannel = data.PublicFeedbackChannel; - var systemChannel = data.PrivateFeedbackChannel; - if (_stackedPrivateFeedback.Length > 0 && adminChannel is not null && - adminChannel.Id != Context.Message.Channel.Id) { + var adminChannel = data.PrivateFeedbackChannel; + var systemChannel = data.PublicFeedbackChannel; + if (_stackedPrivateFeedback.Length > 0 + && adminChannel is not null + && adminChannel.Id != Context.Message.Channel.Id) { _ = Utils.SilentSendAsync(adminChannel, _stackedPrivateFeedback.ToString()); _stackedPrivateFeedback.Clear(); } - if (_stackedPublicFeedback.Length > 0 && systemChannel is not null && systemChannel.Id != adminChannel?.Id + if (_stackedPublicFeedback.Length > 0 + && systemChannel is not null + && systemChannel.Id != adminChannel?.Id && systemChannel.Id != Context.Message.Channel.Id) { _ = Utils.SilentSendAsync(systemChannel, _stackedPublicFeedback.ToString()); _stackedPublicFeedback.Clear(); @@ -108,7 +114,8 @@ public sealed class CommandProcessor { public string? GetRemaining(string[] from, int startIndex, string? argument) { if (startIndex >= from.Length && argument is not null) - Utils.SafeAppendToBuilder(_stackedReplyMessage, + Utils.SafeAppendToBuilder( + _stackedReplyMessage, $"{ReplyEmojis.MissingArgument} {Utils.GetMessage($"Missing{argument}")}", Context.Message); else return string.Join(" ", from, startIndex, from.Length - startIndex); return null; @@ -116,14 +123,16 @@ public sealed class CommandProcessor { public Tuple? GetUser(string[] args, string[] cleanArgs, int index) { if (index >= args.Length) { - Utils.SafeAppendToBuilder(_stackedReplyMessage, $"{ReplyEmojis.MissingArgument} {Messages.MissingUser}", + Utils.SafeAppendToBuilder( + _stackedReplyMessage, $"{ReplyEmojis.MissingArgument} {Messages.MissingUser}", Context.Message); return null; } var mention = Utils.ParseMention(args[index]); if (mention is 0) { - Utils.SafeAppendToBuilder(_stackedReplyMessage, + Utils.SafeAppendToBuilder( + _stackedReplyMessage, $"{ReplyEmojis.InvalidArgument} {string.Format(Messages.InvalidUser, Utils.Wrap(cleanArgs[index]))}", Context.Message); return null; @@ -131,7 +140,8 @@ public sealed class CommandProcessor { var exists = Utils.UserExists(mention); if (!exists) { - Utils.SafeAppendToBuilder(_stackedReplyMessage, + Utils.SafeAppendToBuilder( + _stackedReplyMessage, $"{ReplyEmojis.Error} {string.Format(Messages.UserNotFound, Utils.Wrap(cleanArgs[index]))}", Context.Message); return null; @@ -142,7 +152,8 @@ public sealed class CommandProcessor { public bool HasPermission(GuildPermission permission) { if (!Context.Guild.CurrentUser.GuildPermissions.Has(permission)) { - Utils.SafeAppendToBuilder(_stackedReplyMessage, + Utils.SafeAppendToBuilder( + _stackedReplyMessage, $"{ReplyEmojis.NoPermission} {Utils.GetMessage($"BotCannot{permission}")}", Context.Message); return false; @@ -150,7 +161,8 @@ public sealed class CommandProcessor { if (!GetMember().GuildPermissions.Has(permission) && Context.Guild.OwnerId != Context.User.Id) { - Utils.SafeAppendToBuilder(_stackedReplyMessage, + Utils.SafeAppendToBuilder( + _stackedReplyMessage, $"{ReplyEmojis.NoPermission} {Utils.GetMessage($"UserCannot{permission}")}", Context.Message); return false; @@ -169,14 +181,16 @@ public sealed class CommandProcessor { public SocketGuildUser? GetMember(string[] args, int index) { if (index >= args.Length) { - Utils.SafeAppendToBuilder(_stackedReplyMessage, $"{ReplyEmojis.MissingArgument} {Messages.MissingMember}", + Utils.SafeAppendToBuilder( + _stackedReplyMessage, $"{ReplyEmojis.MissingArgument} {Messages.MissingMember}", Context.Message); return null; } var member = Context.Guild.GetUser(Utils.ParseMention(args[index])); if (member is null) - Utils.SafeAppendToBuilder(_stackedReplyMessage, + Utils.SafeAppendToBuilder( + _stackedReplyMessage, $"{ReplyEmojis.InvalidArgument} {Messages.InvalidMember}", Context.Message); return member; @@ -184,7 +198,8 @@ public sealed class CommandProcessor { public ulong? GetBan(string[] args, int index) { if (index >= args.Length) { - Utils.SafeAppendToBuilder(_stackedReplyMessage, $"{ReplyEmojis.MissingArgument} {Messages.MissingUser}", + Utils.SafeAppendToBuilder( + _stackedReplyMessage, $"{ReplyEmojis.MissingArgument} {Messages.MissingUser}", Context.Message); return null; } @@ -200,14 +215,16 @@ public sealed class CommandProcessor { public int? GetNumberRange(string[] args, int index, int min, int max, string? argument) { if (index >= args.Length) { - Utils.SafeAppendToBuilder(_stackedReplyMessage, + Utils.SafeAppendToBuilder( + _stackedReplyMessage, $"{ReplyEmojis.MissingArgument} {string.Format(Messages.MissingNumber, min.ToString(), max.ToString())}", Context.Message); return null; } if (!int.TryParse(args[index], out var i)) { - Utils.SafeAppendToBuilder(_stackedReplyMessage, + Utils.SafeAppendToBuilder( + _stackedReplyMessage, $"{ReplyEmojis.InvalidArgument} {string.Format(Utils.GetMessage($"{argument}Invalid"), min.ToString(), max.ToString(), Utils.Wrap(args[index]))}", Context.Message); return null; @@ -215,14 +232,16 @@ public sealed class CommandProcessor { if (argument is null) return i; if (i < min) { - Utils.SafeAppendToBuilder(_stackedReplyMessage, + Utils.SafeAppendToBuilder( + _stackedReplyMessage, $"{ReplyEmojis.InvalidArgument} {string.Format(Utils.GetMessage($"{argument}TooSmall"), min.ToString())}", Context.Message); return null; } if (i > max) { - Utils.SafeAppendToBuilder(_stackedReplyMessage, + Utils.SafeAppendToBuilder( + _stackedReplyMessage, $"{ReplyEmojis.InvalidArgument} {string.Format(Utils.GetMessage($"{argument}TooLarge"), max.ToString())}", Context.Message); return null; @@ -267,31 +286,36 @@ public sealed class CommandProcessor { public bool CanInteractWith(SocketGuildUser user, string action) { if (Context.User.Id == user.Id) { - Utils.SafeAppendToBuilder(_stackedReplyMessage, + Utils.SafeAppendToBuilder( + _stackedReplyMessage, $"{ReplyEmojis.CantInteract} {Utils.GetMessage($"UserCannot{action}Themselves")}", Context.Message); return false; } if (Context.Guild.CurrentUser.Id == user.Id) { - Utils.SafeAppendToBuilder(_stackedReplyMessage, + Utils.SafeAppendToBuilder( + _stackedReplyMessage, $"{ReplyEmojis.CantInteract} {Utils.GetMessage($"UserCannot{action}Bot")}", Context.Message); return false; } if (Context.Guild.Owner.Id == user.Id) { - Utils.SafeAppendToBuilder(_stackedReplyMessage, + Utils.SafeAppendToBuilder( + _stackedReplyMessage, $"{ReplyEmojis.CantInteract} {Utils.GetMessage($"UserCannot{action}Owner")}", Context.Message); return false; } if (Context.Guild.CurrentUser.Hierarchy <= user.Hierarchy) { - Utils.SafeAppendToBuilder(_stackedReplyMessage, + Utils.SafeAppendToBuilder( + _stackedReplyMessage, $"{ReplyEmojis.CantInteract} {Utils.GetMessage($"BotCannot{action}Target")}", Context.Message); return false; } if (Context.Guild.Owner.Id != Context.User.Id && GetMember().Hierarchy <= user.Hierarchy) { - Utils.SafeAppendToBuilder(_stackedReplyMessage, + Utils.SafeAppendToBuilder( + _stackedReplyMessage, $"{ReplyEmojis.CantInteract} {Utils.GetMessage($"UserCannot{action}Target")}", Context.Message); return false; } diff --git a/EventHandler.cs b/EventHandler.cs index 3e3bcfd..0fb41d8 100644 --- a/EventHandler.cs +++ b/EventHandler.cs @@ -7,8 +7,8 @@ using Discord.WebSocket; namespace Boyfriend; public static class EventHandler { - private static readonly DiscordSocketClient Client = Boyfriend.Client; - private static bool _sendReadyMessages = true; + private static readonly DiscordSocketClient Client = Boyfriend.Client; + private static bool _sendReadyMessages = true; public static void InitEvents() { Client.Ready += ReadyEvent; @@ -49,11 +49,13 @@ public static class EventHandler { return Task.CompletedTask; } - private static async Task MessageDeletedEvent(Cacheable message, + private static async Task MessageDeletedEvent( + Cacheable message, Cacheable channel) { var msg = message.Value; - if (channel.Value is not SocketGuildChannel gChannel || msg is null or ISystemMessage || - msg.Author.IsBot) return; + if (channel.Value is not SocketGuildChannel gChannel + || msg is null or ISystemMessage + || msg.Author.IsBot) return; var guild = gChannel.Guild; @@ -64,22 +66,25 @@ public static class EventHandler { await Task.Delay(500); var auditLogEntry = (await guild.GetAuditLogsAsync(1).FlattenAsync()).First(); - if (auditLogEntry.CreatedAt >= DateTimeOffset.Now.Subtract(TimeSpan.FromSeconds(1)) && - auditLogEntry.Data is MessageDeleteAuditLogData data && msg.Author.Id == data.Target.Id) + if (auditLogEntry.CreatedAt >= DateTimeOffset.Now.Subtract(TimeSpan.FromSeconds(1)) + && auditLogEntry.Data is MessageDeleteAuditLogData data + && msg.Author.Id == data.Target.Id) mention = auditLogEntry.User.Mention; - await Utils.SendFeedbackAsync(string.Format(Messages.CachedMessageDeleted, msg.Author.Mention, - Utils.MentionChannel(channel.Id), - Utils.Wrap(msg.CleanContent)), guild, mention); + await Utils.SendFeedbackAsync( + string.Format( + Messages.CachedMessageDeleted, msg.Author.Mention, + Utils.MentionChannel(channel.Id), + Utils.Wrap(msg.CleanContent)), guild, mention); } private static Task MessageReceivedEvent(IDeletable messageParam) { if (messageParam is not SocketUserMessage message) return Task.CompletedTask; _ = message.CleanContent.ToLower() switch { - "whoami" => message.ReplyAsync("`nobody`"), + "whoami" => message.ReplyAsync("`nobody`"), "сука !!" => message.ReplyAsync("`root`"), - "воооо" => message.ReplyAsync("`removing /...`"), + "воооо" => message.ReplyAsync("`removing /...`"), "op ??" => message.ReplyAsync( "некоторые пасхальные цитаты которые вы могли найти были легально взяты у <@573772175572729876>"), _ => new CommandProcessor(message).HandleCommandAsync() @@ -87,18 +92,23 @@ public static class EventHandler { return Task.CompletedTask; } - private static async Task MessageUpdatedEvent(Cacheable messageCached, IMessage messageSocket, - ISocketMessageChannel channel) { + private static async Task MessageUpdatedEvent( + Cacheable messageCached, IMessage messageSocket, + ISocketMessageChannel channel) { var msg = messageCached.Value; - if (channel is not SocketGuildChannel gChannel || msg is null or ISystemMessage || - msg.CleanContent == messageSocket.CleanContent || msg.Author.IsBot) return; + if (channel is not SocketGuildChannel gChannel + || msg is null or ISystemMessage + || msg.CleanContent == messageSocket.CleanContent + || msg.Author.IsBot) return; var guild = gChannel.Guild; Utils.SetCurrentLanguage(guild); var isLimitedSpace = msg.CleanContent.Length + messageSocket.CleanContent.Length < 1940; - await Utils.SendFeedbackAsync(string.Format(Messages.CachedMessageEdited, Utils.MentionChannel(channel.Id), + await Utils.SendFeedbackAsync( + string.Format( + Messages.CachedMessageEdited, Utils.MentionChannel(channel.Id), Utils.Wrap(msg.CleanContent, isLimitedSpace), Utils.Wrap(messageSocket.CleanContent, isLimitedSpace)), guild, msg.Author.Mention); } @@ -111,10 +121,12 @@ public static class EventHandler { Utils.SetCurrentLanguage(guild); if (config["SendWelcomeMessages"] is "true" && data.PublicFeedbackChannel is not null) - await Utils.SilentSendAsync(data.PublicFeedbackChannel, - string.Format(config["WelcomeMessage"] is "default" - ? Messages.DefaultWelcomeMessage - : config["WelcomeMessage"], user.Mention, guild.Name)); + await Utils.SilentSendAsync( + data.PublicFeedbackChannel, + string.Format( + config["WelcomeMessage"] is "default" + ? Messages.DefaultWelcomeMessage + : config["WelcomeMessage"], user.Mention, guild.Name)); if (config["StarterRole"] is not "0") await user.AddRoleAsync(ulong.Parse(config["StarterRole"])); @@ -148,23 +160,24 @@ public static class EventHandler { var eventConfig = GuildData.Get(guild).Preferences; var channel = Utils.GetEventNotificationChannel(guild); Utils.SetCurrentLanguage(guild); + if (channel is null) return; - if (channel is not null) { - var role = guild.GetRole(ulong.Parse(eventConfig["EventNotificationRole"])); - var mentions = role is not null - ? $"{role.Mention} {scheduledEvent.Creator.Mention}" - : $"{scheduledEvent.Creator.Mention}"; + var role = guild.GetRole(ulong.Parse(eventConfig["EventNotificationRole"])); + var mentions = role is not null + ? $"{role.Mention} {scheduledEvent.Creator.Mention}" + : $"{scheduledEvent.Creator.Mention}"; - var location = Utils.Wrap(scheduledEvent.Location) ?? Utils.MentionChannel(scheduledEvent.Channel.Id); - var descAndLink - = $"\n{Utils.Wrap(scheduledEvent.Description)}\nhttps://discord.com/events/{guild.Id}/{scheduledEvent.Id}"; + var location = Utils.Wrap(scheduledEvent.Location) ?? Utils.MentionChannel(scheduledEvent.Channel.Id); + var descAndLink + = $"\n{Utils.Wrap(scheduledEvent.Description)}\nhttps://discord.com/events/{guild.Id}/{scheduledEvent.Id}"; - await Utils.SilentSendAsync(channel, - string.Format(Messages.EventCreated, mentions, - Utils.Wrap(scheduledEvent.Name), location, - scheduledEvent.StartTime.ToUnixTimeSeconds().ToString(), descAndLink), - true); - } + await Utils.SilentSendAsync( + channel, + string.Format( + Messages.EventCreated, mentions, + Utils.Wrap(scheduledEvent.Name), location, + scheduledEvent.StartTime.ToUnixTimeSeconds().ToString(), descAndLink), + true); } private static async Task ScheduledEventCancelledEvent(SocketGuildEvent scheduledEvent) { @@ -173,8 +186,10 @@ public static class EventHandler { var channel = Utils.GetEventNotificationChannel(guild); Utils.SetCurrentLanguage(guild); if (channel is not null) - await channel.SendMessageAsync(string.Format(Messages.EventCancelled, Utils.Wrap(scheduledEvent.Name), - eventConfig["FrowningFace"] is "true" ? $" {Messages.SettingsFrowningFace}" : "")); + await channel.SendMessageAsync( + string.Format( + Messages.EventCancelled, Utils.Wrap(scheduledEvent.Name), + eventConfig["FrowningFace"] is "true" ? $" {Messages.SettingsFrowningFace}" : "")); } private static async Task ScheduledEventStartedEvent(SocketGuildEvent scheduledEvent) { @@ -183,22 +198,24 @@ public static class EventHandler { var channel = Utils.GetEventNotificationChannel(guild); Utils.SetCurrentLanguage(guild); - if (channel is not null) { - var receivers = eventConfig["EventStartedReceivers"]; - var role = guild.GetRole(ulong.Parse(eventConfig["EventNotificationRole"])); - var mentions = Boyfriend.StringBuilder; + if (channel is null) return; - if (receivers.Contains("role") && role is not null) mentions.Append($"{role.Mention} "); - if (receivers.Contains("users") || receivers.Contains("interested")) - mentions = (await scheduledEvent.GetUsersAsync(15)) - .Where(user => role is null || !((RestGuildUser)user).RoleIds.Contains(role.Id)) - .Aggregate(mentions, (current, user) => current.Append($"{user.Mention} ")); + var receivers = eventConfig["EventStartedReceivers"]; + var role = guild.GetRole(ulong.Parse(eventConfig["EventNotificationRole"])); + var mentions = Boyfriend.StringBuilder; - await channel.SendMessageAsync(string.Format(Messages.EventStarted, mentions, + if (receivers.Contains("role") && role is not null) mentions.Append($"{role.Mention} "); + if (receivers.Contains("users") || receivers.Contains("interested")) + mentions = (await scheduledEvent.GetUsersAsync(15)) + .Where(user => role is null || !((RestGuildUser)user).RoleIds.Contains(role.Id)) + .Aggregate(mentions, (current, user) => current.Append($"{user.Mention} ")); + + await channel.SendMessageAsync( + string.Format( + Messages.EventStarted, mentions, Utils.Wrap(scheduledEvent.Name), Utils.Wrap(scheduledEvent.Location) ?? Utils.MentionChannel(scheduledEvent.Channel.Id))); - mentions.Clear(); - } + mentions.Clear(); } private static async Task ScheduledEventCompletedEvent(SocketGuildEvent scheduledEvent) { @@ -206,7 +223,9 @@ public static class EventHandler { var channel = Utils.GetEventNotificationChannel(guild); Utils.SetCurrentLanguage(guild); if (channel is not null) - await channel.SendMessageAsync(string.Format(Messages.EventCompleted, Utils.Wrap(scheduledEvent.Name), - Utils.GetHumanizedTimeSpan(DateTimeOffset.Now.Subtract(scheduledEvent.StartTime)))); + await channel.SendMessageAsync( + string.Format( + Messages.EventCompleted, Utils.Wrap(scheduledEvent.Name), + Utils.GetHumanizedTimeSpan(DateTimeOffset.Now.Subtract(scheduledEvent.StartTime)))); } }