Skip to content

Commit

Permalink
Merge branch 'development'
Browse files Browse the repository at this point in the history
  • Loading branch information
Blackcatmaxy committed Dec 29, 2020
2 parents 7508328 + 17e55ed commit 1c5e3a8
Show file tree
Hide file tree
Showing 30 changed files with 573 additions and 547 deletions.
6 changes: 4 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore

# User-specific files
BotCatMaxy/HiddenInfo.cs
*.rsuser
*.suo
*.user
Expand Down Expand Up @@ -338,4 +337,7 @@ ASALocalRun/
.localhistory/

# BeatPulse healthcheck temp database
healthchecksdb
healthchecksdb

# Tokens file
/BotCatMaxy/Properties/Tokens.targets
38 changes: 21 additions & 17 deletions BotCatMaxy/BotCatMaxy.csproj
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk;Microsoft.NET.Sdk.Publish">
<Project Sdk="Microsoft.NET.Sdk;Microsoft.NET.Sdk.Publish" InitialTargets="WriteLaunchers">
<PropertyGroup>
<SourceRevisionId>build$([System.DateTime]::UtcNow.ToString("yyyyMMddHHmmss"))</SourceRevisionId>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<TargetFramework>net5.0</TargetFramework>
<StartupObject>BotCatMaxy.MainClass</StartupObject>
<AssemblyName>BotCatMaxy</AssemblyName>
<Authors>Blackcatmaxy</Authors>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DocumentationFile></DocumentationFile>
<OutputPath>C:\Users\bobth\Documents\Botcatmaxy</OutputPath>
<Optimize>true</Optimize>
<Deterministic>false</Deterministic>
<Deterministic>false</Deterministic>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<Prefer32Bit>true</Prefer32Bit>
Expand All @@ -23,19 +22,24 @@
<ItemGroup>
<PackageReference Include="Discord.Addons.Interactive" Version="2.0.0" />
<PackageReference Include="Discord.Addons.Preconditions" Version="2.2.0-dev3" />
<PackageReference Include="Discord.Net" Version="2.3.0-dev-20200904.2" />
<PackageReference Include="Discord.Net.Commands" Version="2.3.0-dev-20200904.2" />
<PackageReference Include="Discord.Net.WebSocket" Version="2.3.0-dev-20200904.2" />
<PackageReference Include="Discord.Net" Version="2.3.0-dev-20201220.5" />
<PackageReference Include="Discord.Net.Commands" Version="2.3.0-dev-20201220.5" />
<PackageReference Include="Discord.Net.WebSocket" Version="2.3.0-dev-20201220.5" />
<PackageReference Include="DotNetEnv" Version="2.0.0" />
<PackageReference Include="Humanizer.Core" Version="2.8.26" />
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="3.3.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.9" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="5.0.1" />
<PackageReference Include="Microsoft.Web.WebJobs.Publish" Version="2.0.0" />
<PackageReference Include="MongoDB.Driver" Version="2.11.2" />
<PackageReference Include="Serilog" Version="2.10.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
<PackageReference Include="Serilog.Sinks.File" Version="4.1.0" />
<PackageReference Include="MongoDB.Driver" Version="2.12.0-beta1" />
<PackageReference Include="Polly" Version="7.2.1" />
<PackageReference Include="Serilog" Version="2.10.1-dev-01265" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.0.0-dev-00839" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0-dev-00905" />
</ItemGroup>

<Import Condition="$(IsBuildAction)==''" Project="Properties\Tokens.targets" />

<Target Condition="$(IsBuildAction)==''" Name="WriteLaunchers" AfterTargets="CopyFilesToOutputDirectory">
<Message Importance="High" Text="$(FileLines)" />
<WriteLinesToFile File="$(OutputPath)$(AssemblyName).env" Overwrite="true" Lines="$(FileLines)" />
</Target>
</Project>
14 changes: 10 additions & 4 deletions BotCatMaxy/Components/Data/DataManipulator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
Expand All @@ -23,6 +24,9 @@ public static async Task MapTypes()
{
try
{
var conventionPack = new ConventionPack { new CamelCaseElementNameConvention() };
ConventionRegistry.Register("camelCase", conventionPack, t => true);

BsonClassMap.RegisterClassMap<ModerationSettings>();
BsonClassMap.RegisterClassMap<UserInfractions>();
BsonClassMap.RegisterClassMap<LogSettings>();
Expand Down Expand Up @@ -120,12 +124,13 @@ public static T LoadFromFile<T>(this IGuild guild, bool createFile = false) wher

public static void SaveToFile<T>(this T file) where T : DataObject
{
if (file.guild == null) throw new InvalidOperationException("Data file does not have a guild");

file.AddToCache();
var collection = file.guild.GetCollection(true);
collection.FindOneAndDelete(Builders<BsonDocument>.Filter.Eq("_id", typeof(T).Name));
collection.InsertOne(file.ToBsonDocument());
var name = typeof(T).Name;
collection.FindOneAndDelete(Builders<BsonDocument>.Filter.Eq("_id", name));
var doc = file.ToBsonDocument();
doc.Set("_id", name);
collection.InsertOne(doc);
}

public static IMongoCollection<BsonDocument> GetInfractionsCollection(this IGuild guild, bool createDir = true)
Expand Down Expand Up @@ -211,6 +216,7 @@ public static void SaveInfractions(this ulong userID, IGuild guild, List<Infract
}
}

[BsonIgnoreExtraElements(Inherited = true)]
public class DataObject
{
[BsonIgnore]
Expand Down
66 changes: 36 additions & 30 deletions BotCatMaxy/Components/Filter/FilterCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public async Task ListAutoMod(string extension = "")

for (int i = 0; i < mutualGuilds.Length; i++)
{
guildsEmbed.AddField($"[{i + 1}] {mutualGuilds[i].Name} discord", mutualGuilds[i].Id);
guildsEmbed.AddField($"[{i + 1}] {mutualGuilds[i].Name}", mutualGuilds[i].Id);
}
await ReplyAsync(embed: guildsEmbed.Build());
SocketGuild guild;
Expand Down Expand Up @@ -89,12 +89,12 @@ public async Task ListAutoMod(string extension = "")
else
{
message = settings.allowedLinks.ListItems("\n");
if (message.NotEmpty()) embed.AddField("Allowed links", message, true);
if (message?.Length is not null or 0) embed.AddField("Allowed links", message, true);
if (settings.allowedToLink != null && settings.allowedToLink.Count > 0)
{
message = guild.Roles.Where(
role => (role.Permissions.Administrator && !role.IsManaged) || settings.allowedToLink.Contains(role.Id)).Select(role => role.Name).ToArray().ListItems("\n");
if (message.NotEmpty()) embed.AddField("Roles that can post links", message, true);
if (message?.Length is not null or 0) embed.AddField("Roles that can post links", message, true);
}
}
if (settings.allowedCaps > 0)
Expand All @@ -113,7 +113,7 @@ public async Task ListAutoMod(string extension = "")
if (settings.moderateNames) embed.AddField("Name moderation", "True", true);
if (settings.maxNewLines != null) embed.AddField("Maximum new lines", $"{settings.maxNewLines.Value} new lines", true);
}
if (badWords?.all != null && badWords.all.Count > 0 && (useExplicit || badWords.all.Any(word => !string.IsNullOrWhiteSpace(word.euphemism))))
if (badWords?.all != null && badWords.all.Count > 0 && (useExplicit || badWords.all.Any(word => !string.IsNullOrWhiteSpace(word.Euphemism))))
{
List<string> words = new List<string>();
foreach (List<BadWord> group in badWords.grouped)
Expand All @@ -124,21 +124,21 @@ public async Task ListAutoMod(string extension = "")
string word = "";
if (useExplicit)
{
if (group.Count == 1 || group.All(badWord => badWord.size == first.size))
if (group.Count == 1 || group.All(badWord => badWord.Size == first.Size))
{
word = $"[{first.size}x] ";
word = $"[{first.Size}x] ";
}
else
{
var sizes = group.Select(badword => badword.size);
var sizes = group.Select(badword => badword.Size);
word = $"[{sizes.Min()}-{sizes.Max()}x] ";
}
if (first.euphemism.NotEmpty()) word += $"{first.euphemism} ";
word += $"({group.Select(badWord => $"{badWord.word}{(badWord.partOfWord ? "¤" : "")}").ToArray().ListItems(", ")})";
if (first.Euphemism?.Length is not null or 0) word += $"{first.Euphemism} ";
word += $"({group.Select(badWord => $"{badWord.Word}{(badWord.PartOfWord ? "¤" : "")}").ToArray().ListItems(", ")})";
}
else if (!first.euphemism.IsNullOrEmpty())
word = first.euphemism;
if (first.partOfWord && (!first.euphemism.IsNullOrEmpty() && !useExplicit))
else if (!first.Euphemism.IsNullOrEmpty())
word = first.Euphemism;
if (first.PartOfWord && (!first.Euphemism.IsNullOrEmpty() && !useExplicit))
{
word += "¤";
}
Expand Down Expand Up @@ -170,7 +170,7 @@ public async Task AllowEmojis(uint amount)
settings.maxEmojis = amount;
settings.SaveToFile();
string extraInfo = "";
if (settings.allowedToLink.NotEmpty()) extraInfo = " except by role allowed to link";
if (settings.allowedToLink?.Count is not null or 0) extraInfo = " except by role allowed to link";
if (amount == 0) await ReplyAsync("No emojis are allowed" + extraInfo);
else await ReplyAsync($"Max {amount} emojis are allowed{extraInfo}");
}
Expand Down Expand Up @@ -201,7 +201,7 @@ public async Task SetMaxEmojis(string amount)
settings.maxEmojis = 0;
settings.SaveToFile();
string extraInfo = "";
if (settings.allowedToLink.NotEmpty()) extraInfo = " except by role allowed to link";
if (settings.allowedToLink?.Count is not null or 0) extraInfo = " except by role allowed to link";
await ReplyAsync("Emojis are now no longer allowed" + extraInfo);
break;
default:
Expand Down Expand Up @@ -322,23 +322,31 @@ public async Task RemoveAllowedLinkRole(SocketRole role)
[HasAdmin()]
public async Task ToggleContainBadWord(string word)
{
BadWords badWords = new BadWords(Context.Guild);
foreach (BadWord badWord in badWords.all)
var file = Context.Guild.LoadFromFile<BadWordList>(false);
var badWords = file?.badWords;
if (badWords?.Count is null or 0)
{
if (badWord.word.ToLower() == word.ToLower())
await ReplyAsync("No badwords have been set");
return;
}
var editedList = new List<BadWord>(badWords);
for (int i = 0; i < badWords.Count; i++)
{
var badWord = badWords[i];
if (badWord.Word.Equals(word, StringComparison.InvariantCultureIgnoreCase))
{
if (badWord.partOfWord)
if (badWord.PartOfWord)
{
badWord.partOfWord = false;
editedList[i] = badWord with { PartOfWord = false };
await ReplyAsync("Set badword to not be filtered if it's inside of another word");
}
else
{
badWord.partOfWord = true;
editedList[i] = badWord with { PartOfWord = true };
await ReplyAsync("Set badword to be filtered even if it's inside of another word");
}
BadWordList badWordList = new BadWordList { badWords = badWords.all, guild = Context.Guild };
badWordList.SaveToFile();
file.badWords = editedList;
file.SaveToFile();
return;
}
}
Expand Down Expand Up @@ -482,7 +490,7 @@ public async Task RemoveBadWord(string word)
await ReplyAsync("No bad words are set");
return;
}
BadWord badToRemove = badWordsClass.badWords.FirstOrDefault(badWord => badWord.word == word);
BadWord badToRemove = badWordsClass.badWords.FirstOrDefault(badWord => badWord.Word == word);
if (badToRemove != null)
{
badWordsClass.badWords.Remove(badToRemove);
Expand All @@ -504,15 +512,15 @@ public async Task AddBadWord(string word, string euphemism = null, float size =
{
BadWord badWord = new BadWord
{
word = word,
euphemism = euphemism,
size = size
Word = word,
Euphemism = euphemism,
Size = size
};
BadWordList badWordsClass = Context.Guild.LoadFromFile<BadWordList>(true);
badWordsClass.badWords.Add(badWord);
badWordsClass.SaveToFile();

await ReplyAsync($"Added {badWord.word}{((badWord.euphemism != null) ? $", also known as {badWord.euphemism}" : "")} to bad word list");
await ReplyAsync($"Added {badWord.Word}{((badWord.Euphemism != null) ? $", also known as {badWord.Euphemism}" : "")} to bad word list");
}

[Command("addanouncementchannel"), HasAdmin]
Expand Down Expand Up @@ -554,8 +562,6 @@ public async Task ToggleNameFilter()
ModerationSettings settings = Context.Guild.LoadFromFile<ModerationSettings>(true);
settings.moderateNames = !settings.moderateNames;
settings.SaveToFile();
string extra = "";
if (settings.moderateNames) extra = " note: existing usernames and nicknames won't be filtered";
await ReplyAsync("Set user name and nickname filtering to " + settings.moderateNames.ToString().ToLowerInvariant());
}

Expand Down Expand Up @@ -619,4 +625,4 @@ public async Task RemoveInviteWhitelist(ulong guildID)
}
}
}
}
}
16 changes: 8 additions & 8 deletions BotCatMaxy/Components/Filter/FilterHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,15 +85,15 @@ public async Task CheckNameInGuild(IUser user, string name, SocketGuild guild)
embed.WithColor(Color.DarkMagenta);
embed.WithAuthor(user);
embed.WithTitle("User kicked for bad username");
embed.WithDescription($"Name '{name}' contained '{detectedBadWord.word}'");
embed.WithDescription($"Name '{name}' contained '{detectedBadWord.Word}'");
embed.WithCurrentTimestamp();
embed.WithFooter("User ID: " + user.Id);
await (channel as SocketTextChannel).SendMessageAsync(embed: embed.Build());
}
//If user's DMs aren't blocked
if (await user.TryNotify($"Your username contains a filtered word ({detectedBadWord.word}). Please change it before rejoining {guild.Name} Discord"))
if (await user.TryNotify($"Your username contains a filtered word ({detectedBadWord.Word}). Please change it before rejoining {guild.Name} Discord"))
{
await gUser.KickAsync($"Username '{name}' triggered autofilter for '{detectedBadWord.word}'");
await gUser.KickAsync($"Username '{name}' triggered autofilter for '{detectedBadWord.Word}'");
user.Id.AddWarn(1, "Username with filtered word", guild, null);
return;
}//If user's DMs are blocked
Expand All @@ -104,7 +104,7 @@ public async Task CheckNameInGuild(IUser user, string name, SocketGuild guild)
else if (guild.TryGetTextChannel(logSettings.pubLogChannel, out ITextChannel pubChannel))
await pubChannel.SendMessageAsync($"{user.Mention} your username contains a bad word but your DMs are closed. Please clean up your username before rejoining");
await Task.Delay(10000);
await gUser.KickAsync($"Username '{name}' triggered autofilter for '{detectedBadWord.word}'");
await gUser.KickAsync($"Username '{name}' triggered autofilter for '{detectedBadWord.Word}'");
user.Id.AddWarn(1, "Username with filtered word (Note: DMs closed)", guild, null);

}
Expand Down Expand Up @@ -229,7 +229,7 @@ public async Task CheckMessage(SocketMessage message)
}

//Check for emojis
if (modSettings.badUEmojis.NotEmpty() && modSettings.badUEmojis.Any(s => message.Content.Contains(s)))
if (modSettings.badUEmojis?.Count is not null or 0 && modSettings.badUEmojis.Any(s => message.Content.Contains(s)))
{
await context.FilterPunish("Bad emoji used", modSettings, 0.8f);
return;
Expand All @@ -256,14 +256,14 @@ public async Task CheckMessage(SocketMessage message)
BadWord detectedBadWord = msgContent.CheckForBadWords(badWords?.ToArray());
if (detectedBadWord != null)
{
if (!string.IsNullOrEmpty(detectedBadWord.euphemism))
if (!string.IsNullOrEmpty(detectedBadWord.Euphemism))
{
await context.FilterPunish("Bad word used (" + detectedBadWord.euphemism + ")", modSettings, detectedBadWord.size);
await context.FilterPunish("Bad word used (" + detectedBadWord.Euphemism + ")", modSettings, detectedBadWord.Size);
return;
}
else
{
await context.FilterPunish("Bad word used", modSettings, detectedBadWord.size);
await context.FilterPunish("Bad word used", modSettings, detectedBadWord.Size);
return;
}
}
Expand Down
Loading

0 comments on commit 1c5e3a8

Please sign in to comment.