private static async Task UserBanned(SocketUser user, SocketGuild guild) { if (_DiscordClient.GetChannel(WubbysFunHouse.UserLogsChannelId) is IMessageChannel userLogChannel) { await userLogChannel.SendMessageAsync($"`[{DateTime.UtcNow.ToString(Constants.DateTimeFormatMedium)}]` :no_entry: {user} (`{user.Id}`) was banned."); } try { // Lookup audit log event Task runner = Task.Run(async() => { await Task.Delay(4000); if (_DiscordClient.GetChannel(WubbysFunHouse.ModLogsChannelId) is IMessageChannel modLogChannel) { IEnumerable <RestAuditLogEntry> userBans = await guild.GetAuditLogsAsync(10, actionType: ActionType.Ban).FlattenAsync(); RestAuditLogEntry bannedEvent = userBans.Where(x => x.Data is BanAuditLogData data && data.Target.Id == user.Id).FirstOrDefault(); if (string.IsNullOrEmpty(bannedEvent.Reason)) { await modLogChannel.SendMessageAsync($":no_entry: {user} (`{user.Id}`) was banned by {bannedEvent.User} (`{bannedEvent.User.Id}`) with no reason specified."); } else { await modLogChannel.SendMessageAsync($":no_entry: {user} (`{user.Id}`) was banned by {bannedEvent.User} (`{bannedEvent.User.Id}`) with reason: **{bannedEvent.Reason}**"); } } }); } catch (Exception ex) { LoggingManager.Log.Error(ex); } }
private async Task <RestAuditLogEntry> GetAuditLogEntry(SocketGuild guild) { IAsyncEnumerable <IReadOnlyCollection <RestAuditLogEntry> > auditLog = guild.GetAuditLogsAsync(1); List <IReadOnlyCollection <RestAuditLogEntry> > auditList = await auditLog.ToList(); RestAuditLogEntry[] restAuditLogs = auditList[0].ToArray(); RestAuditLogEntry logEntry = restAuditLogs[0]; return(logEntry); }
private async Task OnUserBanned(SocketUser user, SocketGuild guild) { Server server; if (!this.Client.Servers.ContainsKey(guild.Id) || (server = this.Client.Servers[guild.Id]) == null || this.RecentlyBannedUserIDs.Contains(user.Id)) { return; } BanAuditLogData auditData = null; RestAuditLogEntry auditEntry = null; if (guild.CurrentUser.GuildPermissions.ViewAuditLog) { await Task.Delay(500); try { auditEntry = await guild.GetAuditLogsAsync(10)?.Flatten()?.FirstOrDefault(e => e != null && e.Action == ActionType.Ban && (auditData = e.Data as BanAuditLogData) != null && auditData.Target.Id == user.Id); //One huge line because black magic from .NET Core? } catch (Exception) { } } string reason = "unknown"; RestBan ban = await server.Guild.GetBanAsync(user); if (ban != null) { reason = ban.Reason; await this.Client.Events.AddBan(guild.Id, user.Id, TimeSpan.Zero, reason); } await LogBan(server, user.GetUsername(), user.Id, reason, "permanently", auditEntry?.User as SocketGuildUser); }
private async Task Client_UserUnbanned(SocketUser user, SocketGuild guild) { RestAuditLogEntry logEntry = await GetAuditLogEntry(guild); if (logEntry.Action != ActionType.Unban) { return; } UnbanAuditLogData data = (UnbanAuditLogData)logEntry.Data; string targetUsername = "******" + user + "** _(" + user.Id + ")_"; string adminUsername = "******" + logEntry.User + "**"; string msg = targetUsername + " was unbanned by " + adminUsername + "\nReason: " + (string.IsNullOrEmpty(logEntry.Reason) ? "No reason provided." : logEntry.Reason); foreach (SocketTextChannel channel in Global.SECURITY_CHANNELS) { if (channel.Guild.Id == guild.Id) { await SendSecurityLog(msg, new Color(255, 0, 0), channel, logEntry.Id.ToString(), logEntry.User.GetAvatarUrl()); break; } } }
public static async Task AuditUpdate(SocketGuild guild) { foreach (SocketTextChannel chan in guild.TextChannels) { if (chan.Name.ToLower().Contains("security")) { ConsolePrint("Security channel found in " + guild.Name); IAsyncEnumerable <IReadOnlyCollection <RestAuditLogEntry> > auditLog = guild.GetAuditLogsAsync(10); List <IReadOnlyCollection <RestAuditLogEntry> > auditList = await auditLog.ToList(); IAsyncEnumerable <IReadOnlyCollection <IMessage> > messages = chan.GetMessagesAsync(1); List <IReadOnlyCollection <IMessage> > msgList = await messages.ToList(); IMessage mesg = null; if (msgList[1].Count > 0) { mesg = msgList[1].ToArray()[0];// Newest Message } RestAuditLogEntry[] restAuditLogs = auditList[0].ToArray(); if (mesg != null) { if (mesg.Embeds.Count > 0) { if (restAuditLogs[0].Id.ToString() == mesg.Embeds.FirstOrDefault().Footer.Value.Text) { break; } } else { continue; } } for (int i = restAuditLogs.Length - 1; i >= 0; i--) { if (mesg != null) { if (mesg.Embeds.Count > 0) { int dif = DateTimeOffset.Compare(mesg.Embeds.FirstOrDefault().Timestamp.Value, restAuditLogs[i].CreatedAt); if (dif >= 0) { continue; } } else { continue; } } RestAuditLogEntry logEntry = restAuditLogs[i]; bool send = false; EmbedBuilder embed = new EmbedBuilder(); string adminUsername = "******" + logEntry.User + "**"; string title = "Server Report"; embed.WithTimestamp(logEntry.CreatedAt); string msg = ""; if (logEntry.Action == ActionType.MemberRoleUpdated) { MemberRoleAuditLogData data = (MemberRoleAuditLogData)logEntry.Data; string targetUsername = "******" + data.Target + "** _(" + data.Target.Id + ")_"; string roles = ""; foreach (MemberRoleEditInfo role in data.Roles) { roles += string.Format(((role.Added) ? " Added role {0} to " : " Removed role {0} from "), "**_" + role.Name + "_**"); } msg = adminUsername + roles + targetUsername; embed.WithColor(new Color(255, 190, 0)); send = true; }// end if log entry role updated else if (logEntry.Action == ActionType.MemberUpdated) { MemberUpdateAuditLogData data = (MemberUpdateAuditLogData)logEntry.Data; string targetUsername = "******" + data.Target + "** _(" + data.Target.Id + ")_"; if (data.Before.Deaf != data.After.Deaf) { msg += string.Format(adminUsername + " {0} " + targetUsername + "\n", (data.After.Deaf.Value) ? "deafened" : "undeafened"); } if (data.Before.Mute != data.After.Mute) { msg += string.Format(adminUsername + " {0} " + targetUsername + "\n", (data.After.Mute.Value) ? "muted" : "unmuted"); } if (data.Before.Nickname != data.After.Nickname) { msg += string.Format(adminUsername + " changed {0}'s nickname from *{1}* to *{2}*\n", targetUsername, (data.Before.Nickname == null) ? data.Target.Username : data.Before.Nickname, (data.After.Nickname == null) ? data.Target.Username : data.After.Nickname); } Console.WriteLine(msg); embed.WithColor(255, 255, 0); send = true; } else if (logEntry.Action == ActionType.Kick) { KickAuditLogData data = (KickAuditLogData)logEntry.Data; string targetUsername = "******" + data.Target + "** _(" + data.Target.Id + ")_"; msg = targetUsername + " was kicked by " + adminUsername + "\nReason: " + logEntry.Reason; embed.WithColor(new Color(255, 0, 0)); send = true; } else if (logEntry.Action == ActionType.Ban) { BanAuditLogData data = (BanAuditLogData)logEntry.Data; string targetUsername = "******" + data.Target + "** _(" + data.Target.Id + ")_"; msg = targetUsername + " was banned by " + adminUsername + "\nReason: " + logEntry.Reason; embed.WithColor(new Color(255, 0, 0)); send = true; } else if (logEntry.Action == ActionType.Unban) { UnbanAuditLogData data = (UnbanAuditLogData)logEntry.Data; string targetUsername = "******" + data.Target + "** _(" + data.Target.Id + ")_"; msg = targetUsername + " was unbanned by " + adminUsername + "\nReason: " + logEntry.Reason; embed.WithColor(new Color(255, 255, 0)); send = true; } else if (logEntry.Action == ActionType.Prune) { PruneAuditLogData data = (PruneAuditLogData)logEntry.Data; msg = adminUsername + " removed " + data.MembersRemoved + " users in a " + data.PruneDays + " day prune" + "\nReason: " + logEntry.Reason; embed.WithColor(new Color(255, 0, 0)); send = true; } else if (logEntry.Action == ActionType.MessageDeleted) { MessageDeleteAuditLogData data = (MessageDeleteAuditLogData)logEntry.Data; msg = adminUsername + " deleted _" + data.MessageCount + "_ messages in **#" + guild.GetChannel(data.ChannelId).Name + "** channel"; embed.WithColor(new Color(255, 190, 0)); send = true; } else if (logEntry.Action == ActionType.InviteCreated) { InviteCreateAuditLogData data = (InviteCreateAuditLogData)logEntry.Data; string creatorUsername = "******" + data.Creator + "** _(" + data.Creator.Id + ")_"; msg = creatorUsername + " created invite **" + data.Code + "**\n" + "Channel: " + guild.GetChannel(data.ChannelId).Name + "\n" + "Max Uses: " + data.MaxUses + "\n" + "Max Age: " + (data.MaxAge / 60 / 60 / 24) + "\n" + "Temporary: " + data.Temporary; embed.WithColor(new Color(255, 255, 0)); send = true; } else if (logEntry.Action == ActionType.InviteDeleted) { InviteDeleteAuditLogData data = (InviteDeleteAuditLogData)logEntry.Data; string creatorUsername = "******" + data.Creator + "** _(" + data.Creator.Id + ")_"; msg = adminUsername + " deleted invite **" + data.Code + "** created by " + creatorUsername + "\n" + "Channel: " + guild.GetChannel(data.ChannelId).Name + "\n" + "Uses: " + data.Uses + "\n" + "Max Uses: " + data.MaxUses + "\n" + "Max Age: " + (data.MaxAge / 60 / 60 / 24) + "\n" + "Temporary: " + data.Temporary; embed.WithColor(new Color(255, 255, 0)); send = true; } else { ConsolePrint("LE_Action: " + logEntry.Action + "; LE_Data: " + logEntry.Data.ToString() + "; "); } embed.WithAuthor(title, logEntry.User.GetAvatarUrl()); embed.WithDescription(msg); embed.WithFooter(logEntry.Id.ToString()); if (send) { await chan.SendMessageAsync("", false, embed.Build()); } if (send) { ConsolePrint("Sent " + embed.Description); } }//end restAuditLog loop ConsolePrint("Finished Audit Log for " + guild.Name); break; } // end if security channel } // end for each text channel in guild }
private async Task OnMessageDeleted(SocketMessage message, ISocketMessageChannel c) { if (!this.Client.GlobalConfig.ModuleUpdateEnabled) { return; } if (!(c is SocketTextChannel channel)) { return; } Server server; if (!this.Client.Servers.ContainsKey(channel.Guild.Id) || (server = this.Client.Servers[channel.Guild.Id]) == null || server.Config.IgnoreBots && message.Author.IsBot || !(message.Author is SocketGuildUser user)) { return; } try { SocketTextChannel logChannel; if (server.Config.LogDeletedMessages && (logChannel = server.Guild.GetTextChannel(server.Config.LogChannelId)) != null && !( (this.Client.ClearedMessageIDs.ContainsKey(server.Id) && this.Client.ClearedMessageIDs[server.Id].Contains(message.Id)) || server.IgnoredChannels.Contains(channel.Id) || server.Roles.Where(r => r.Value.LoggingIgnored).Any(r => user.Roles.Any(role => role.Id == r.Value.RoleId)))) { StringBuilder attachment = new StringBuilder(); if (message.Attachments != null && message.Attachments.Any()) { foreach (Attachment a in message.Attachments) { if (!string.IsNullOrWhiteSpace(a.Url)) { attachment.AppendLine(a.Url); } } } MessageDeleteAuditLogData auditData = null; RestAuditLogEntry auditEntry = null; if (server.Guild.CurrentUser.GuildPermissions.ViewAuditLog) { await Task.Delay(500); try { auditEntry = await server.Guild.GetAuditLogsAsync(10)?.Flatten()?.FirstOrDefault(e => e != null && e.Action == ActionType.MessageDeleted && (auditData = e.Data as MessageDeleteAuditLogData) != null && auditData.ChannelId == c.Id && (Utils.GetTimeFromId(e.Id) + TimeSpan.FromMinutes(5)) > DateTime.UtcNow); //One huge line because black magic from .NET Core? } catch (Exception) { } } bool byAntispam = this.Client.AntispamMessageIDs.Contains(message.Id); string title = "Message Deleted" + (byAntispam ? " by Antispam" : auditEntry != null ? (" by " + auditEntry.User.GetUsername()) : ""); if (server.Config.LogChannelEmbeds) { Color color = byAntispam ? this.AntispamLightColor : new Color(server.Config.LogMessagesColor); await logChannel.SendMessageAsync("", embed : GetLogEmbed(color, user?.GetAvatarUrl(), title, "in #" + channel.Name, message.Author.GetUsername(), message.Author.Id.ToString(), message.Id, "Message", message.Content.Replace("@everyone", "@-everyone").Replace("@here", "@-here"), message.Attachments.Any() ? "Files" : "", attachment.ToString())); } else { await logChannel.SendMessageSafe( GetLogMessage(title, "#" + channel.Name, message.Author.GetUsername(), message.Author.Id.ToString(), message.Id, "Message", message.Content.Replace("@everyone", "@-everyone").Replace("@here", "@-here"), message.Attachments.Any() ? "Files" : "", attachment.ToString())); } } } catch (HttpException) { } catch (Exception exception) { await this.HandleException(exception, "OnMessageDeleted", server.Id); } }
static Logging() { Program.Initialize += delegate(object?sender, DiscordSocketClient client) { client.ChannelDestroyed += delegate(SocketChannel channel) { //Only currently needed for Logs at the moment //Will try to remove the pair if it exists in the list SaveHandler.LogSave.Remove(new KeyValuePair <ulong, ulong>(((SocketGuildChannel)channel).Guild.Id, channel.Id)); SaveHandler.LockdownSave[((SocketGuildChannel)channel).Guild.Id] .Remove(((SocketGuildChannel)channel).Id); return(Task.CompletedTask); }; client.MessageUpdated += async delegate(Cacheable <IMessage, ulong> oldMessage, SocketMessage newMessage, ISocketMessageChannel channel) { if (!oldMessage.HasValue || newMessage.Author.IsBot) { return; } SocketGuild guild = ((SocketTextChannel)channel).Guild; if (SaveHandler.LogSave.ContainsKey(guild.Id)) { SocketTextChannel logChannel = guild.GetTextChannel(SaveHandler.LogSave[guild.Id]); if (oldMessage.Value.Content != newMessage.Content) { EmbedBuilder builder = new EmbedBuilder { Color = Color.Teal, Title = "Message Edited", Url = newMessage.GetJumpUrl(), Description = $"From {newMessage.Author.Mention} in <#{channel.Id}>:\n**Before:**\n{oldMessage.Value.Content}\n**After:**\n{newMessage.Content}" }; if (builder.Length > EmbedBuilder.MaxDescriptionLength) { string[] msgs = Misc.ConvertToDiscordSendable(builder.Description); for (int i = 0; i < msgs.Length; i++) { string msg = msgs[i]; builder.Description = msg; if (msgs.Length - 1 == i) { builder.WithCurrentTimestamp(); } await logChannel.SendMessageAsync(embed : builder.Build()); if (i == 0) { builder.Title = null; } } } else { builder.WithCurrentTimestamp(); await logChannel.SendMessageAsync(embed : builder.Build()); } } } }; client.UserLeft += async delegate(SocketGuildUser user) { if (SaveHandler.LogSave.ContainsKey(user.Guild.Id)) { SocketTextChannel logChannel = user.Guild.GetTextChannel(SaveHandler.LogSave[user.Guild.Id]); RestAuditLogEntry lastKick = (await user.Guild.GetAuditLogsAsync(3, actionType: ActionType.Kick).FlattenAsync()).FirstOrDefault(l => (l.Data as KickAuditLogData).Target == user); EmbedBuilder builder = new EmbedBuilder { Color = Color.Teal }; if (lastKick != null) { string msg = $"You were kicked from {user.Guild.Name}"; if (lastKick.Reason != null) { msg += $"\nReason: {lastKick.Reason}"; } try { await user.SendMessageAsync(msg); } catch { } builder.WithCurrentTimestamp(); builder.Title = "User Kicked"; builder.Description = $"{lastKick.User.Mention} kicked {user.Mention} | {user}"; if (lastKick.Reason != null) { builder.Description += $"\n__Reason__: \"{lastKick.Reason}\""; } await logChannel.SendMessageAsync(embed : builder.Build()); } builder.WithCurrentTimestamp(); builder.Title = "User Left"; builder.Description = $"{user.Mention} | {user}"; await logChannel.SendMessageAsync(embed : builder.Build()); } }; client.UserBanned += async delegate(SocketUser user, SocketGuild guild) { if (SaveHandler.LogSave.ContainsKey(guild.Id)) { RestAuditLogEntry lastBan = (await guild.GetAuditLogsAsync(3, actionType: ActionType.Ban).FlattenAsync()).FirstOrDefault(l => (l.Data as BanAuditLogData).Target == user); if (lastBan != null) { string msg = $"You were banned from {guild.Name}"; if (lastBan.Reason != null) { msg += $"\nReason: {lastBan.Reason}"; } try { await user.SendMessageAsync(msg); } catch { } SocketTextChannel logChannel = guild.GetTextChannel(SaveHandler.LogSave[guild.Id]); EmbedBuilder builder = new EmbedBuilder { Color = Color.Teal, Title = "User Banned", Description = $"{lastBan.User.Mention} banned {user.Mention} | {user}" }; builder.WithCurrentTimestamp(); if (!string.IsNullOrWhiteSpace(lastBan.Reason)) { builder.Description += $"\n__Reason__: \"{lastBan.Reason}\""; } await logChannel.SendMessageAsync(embed : builder.Build()); } } }; client.MessageDeleted += async delegate(Cacheable <IMessage, ulong> message, ISocketMessageChannel channel) { if (!message.HasValue || message.Value.Author.IsBot) { return; } SocketGuild guild = ((SocketGuildChannel)channel).Guild; if (SaveHandler.LogSave.ContainsKey(guild.Id)) { SocketTextChannel logChannel = guild.GetTextChannel(SaveHandler.LogSave[guild.Id]); if (logChannel.Id != channel.Id && (!string.IsNullOrWhiteSpace(message.Value.Content) || message.Value.Attachments.Any())) { EmbedBuilder builder = new EmbedBuilder { Description = "", Color = Color.Teal, Title = "Message Deleted", }; RestAuditLogEntry messageDeleted = (await guild.GetAuditLogsAsync(3, actionType: ActionType.MessageDeleted).FlattenAsync()).FirstOrDefault(l => (l.Data as MessageDeleteAuditLogData).Target.Id == message.Value.Author.Id); if (!string.IsNullOrWhiteSpace(message.Value.Content)) { builder.Description += $"From {message.Value.Author.Mention}, in <#{channel.Id}>"; } if (messageDeleted != null) { builder.Description += $", deleted by {messageDeleted.User.Mention}"; } builder.Description += $":\n{message.Value.Content}"; if (message.Value.Attachments.Any()) { builder.Description += "\n\nAttachments:\n"; foreach (IAttachment attachment in message.Value.Attachments) { builder.Description += $"{attachment.Url}\n"; } } if (builder.Length > EmbedBuilder.MaxDescriptionLength) { string[] msgs = Misc.ConvertToDiscordSendable(builder.Description); for (int i = 0; i < msgs.Length; i++) { string msg = msgs[i]; builder.Description = msg; if (msgs.Length - 1 == i) { builder.WithCurrentTimestamp(); } await logChannel.SendMessageAsync(embed : builder.Build()); if (i == 0) { builder.Title = null; } } } else { builder.WithCurrentTimestamp(); await logChannel.SendMessageAsync(embed : builder.Build()); } } } }; client.GuildMemberUpdated += async delegate(SocketGuildUser before, SocketGuildUser after) { if (before.IsBot) { return; } if (SaveHandler.LogSave.ContainsKey(after.Guild.Id)) { SocketTextChannel logChannel = after.Guild.GetTextChannel(SaveHandler.LogSave[after.Guild.Id]); if (logChannel != null) { if (before.Nickname != after.Nickname) { EmbedBuilder builder = new EmbedBuilder { Color = Color.Teal }; builder.WithCurrentTimestamp(); if (string.IsNullOrWhiteSpace(after.Nickname)) { builder.Title = "Nickname Removal"; builder.Description = $"{after.Mention}:\n`{before.Nickname}` -> `None`"; } else if (string.IsNullOrWhiteSpace(before.Nickname)) { builder.Title = "Nickname Changed"; builder.Description = $"{after.Mention}:\n`None` -> `{after.Nickname}`"; } else { builder.Title = "Nickname Changed"; builder.Description = $"{after.Mention}:\n`{before.Nickname}` -> `{after.Nickname}`"; } await logChannel.SendMessageAsync(embed : builder.Build()); } } } }; }; }