Skip to content

Commit

Permalink
Merge branch 'main' into floatingmilkshake/track-add-channel-option
Browse files Browse the repository at this point in the history
  • Loading branch information
FloatingMilkshake committed Dec 15, 2024
2 parents d645505 + db92550 commit a771ac2
Show file tree
Hide file tree
Showing 37 changed files with 466 additions and 197 deletions.
1 change: 1 addition & 0 deletions .env-example
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ CLIPTOK_ANTIPHISHING_ENDPOINT=useyourimagination
CLOUDFLARED_TOKEN=ignoreifnotrelevant
USERNAME_CHECK_ENDPOINT=https://api.example.com/username
CLIPTALK_WEBHOOK=https://discord.com
REACTION_LOG_WEBHOOK=https://discord.com
UPTIME_KUMA_PUSH_URL=
TS_AUTHKEY=tskey-auth-asdfg-asdfghj
12 changes: 6 additions & 6 deletions Cliptok.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,22 @@

<ItemGroup>
<PackageReference Include="Abyssal.HumanDateParser" Version="2.0.0-20191113.1" />
<PackageReference Include="DSharpPlus" Version="5.0.0-nightly-02374" />
<PackageReference Include="DSharpPlus.CommandsNext" Version="5.0.0-nightly-02374" />
<PackageReference Include="DSharpPlus.SlashCommands" Version="5.0.0-nightly-02374" />
<PackageReference Include="DSharpPlus" Version="5.0.0-nightly-02430" />
<PackageReference Include="DSharpPlus.CommandsNext" Version="5.0.0-nightly-02430" />
<PackageReference Include="DSharpPlus.SlashCommands" Version="5.0.0-nightly-02430" />
<PackageReference Include="Microsoft.Bcl.AsyncInterfaces" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Options" Version="9.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Serilog" Version="4.1.0" />
<PackageReference Include="Serilog" Version="4.2.0" />
<PackageReference Include="Serilog.Expressions" Version="5.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.Grafana.Loki" Version="8.3.0" />
<PackageReference Include="Serilog.Sinks.TextWriter" Version="3.0.0" />
<PackageReference Include="StackExchange.Redis" Version="2.8.16" />
<PackageReference Include="StackExchange.Redis" Version="2.8.22" />
<PackageReference Include="System.Linq" Version="4.3.0" />
<PackageReference Include="System.Linq.Async" Version="6.0.1" />
</ItemGroup>
Expand Down
6 changes: 3 additions & 3 deletions Commands/Bans.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public async Task MassBanCmd(CommandContext ctx, [RemainingText] string input)
[Command("ban")]
[Aliases("tempban", "bonk", "isekaitruck")]
[Description("Bans a user that you have permission to ban, deleting all their messages in the process. See also: bankeep.")]
[HomeServer, RequireHomeserverPerm(ServerPermLevel.Moderator), RequirePermissions(DiscordPermissions.BanMembers)]
[HomeServer, RequireHomeserverPerm(ServerPermLevel.Moderator), RequirePermissions(permissions: DiscordPermission.BanMembers)]
public async Task BanCmd(CommandContext ctx,
[Description("The user you wish to ban. Accepts many formats")] DiscordUser targetMember,
[RemainingText, Description("The time and reason for the ban. e.g. '14d trolling' NOTE: Add 'appeal' to the start of the reason to include an appeal link")] string timeAndReason = "No reason specified.")
Expand Down Expand Up @@ -134,7 +134,7 @@ public async Task BanCmd(CommandContext ctx,
/// Sue me, I beg you.
[Command("bankeep")]
[Aliases("bansave")]
[Description("Bans a user but keeps their messages around."), HomeServer, RequireHomeserverPerm(ServerPermLevel.Moderator), RequirePermissions(DiscordPermissions.BanMembers)]
[Description("Bans a user but keeps their messages around."), HomeServer, RequireHomeserverPerm(ServerPermLevel.Moderator), RequirePermissions(permissions: DiscordPermission.BanMembers)]
public async Task BankeepCmd(CommandContext ctx,
[Description("The user you wish to ban. Accepts many formats")] DiscordUser targetMember,
[RemainingText, Description("The time and reason for the ban. e.g. '14d trolling' NOTE: Add 'appeal' to the start of the reason to include an appeal link")] string timeAndReason = "No reason specified.")
Expand Down Expand Up @@ -216,7 +216,7 @@ public async Task BankeepCmd(CommandContext ctx,

[Command("unban")]
[Description("Unbans a user who has been previously banned.")]
[HomeServer, RequireHomeserverPerm(ServerPermLevel.Moderator), RequirePermissions(DiscordPermissions.BanMembers)]
[HomeServer, RequireHomeserverPerm(ServerPermLevel.Moderator), RequirePermissions(permissions: DiscordPermission.BanMembers)]
public async Task UnbanCmd(CommandContext ctx, [Description("The user to unban, usually a mention or ID")] DiscordUser targetUser, [Description("Used in audit log only currently")] string reason = "No reason specified.")
{
if ((await Program.db.HashExistsAsync("bans", targetUser.Id)))
Expand Down
201 changes: 108 additions & 93 deletions Commands/Debug.cs
Original file line number Diff line number Diff line change
Expand Up @@ -281,8 +281,11 @@ await ctx.RespondAsync(
var response = $"**Overrides for {user.Mention}:**\n\n";
foreach (var overwrite in overwrites)
{
var allowedPermissions = string.IsNullOrWhiteSpace(overwrite.Value.Allowed.ToString("name")) ? "none" : overwrite.Value.Allowed.ToString("name");
var deniedPermissions = string.IsNullOrWhiteSpace(overwrite.Value.Denied.ToString("name")) ? "none" : overwrite.Value.Denied.ToString("name");

response +=
$"<#{overwrite.Key}>:\n**Allowed**: {overwrite.Value.Allowed}\n**Denied**: {overwrite.Value.Denied}\n\n";
$"<#{overwrite.Key}>:\n**Allowed**: {allowedPermissions}\n**Denied**: {deniedPermissions}\n\n";
}

if (response.Length > 2000)
Expand Down Expand Up @@ -348,8 +351,8 @@ public async Task Add(CommandContext ctx,
[Description("Denied permissions. Use a permission integer. See https://discordlookup.com/permissions-calculator.")] int deniedPermissions)
{
// Confirm permission overrides before we do anything.
var parsedAllowedPerms = (DiscordPermissions)allowedPermissions;
var parsedDeniedPerms = (DiscordPermissions)deniedPermissions;
var parsedAllowedPerms = (DiscordPermission)allowedPermissions;
var parsedDeniedPerms = (DiscordPermission)deniedPermissions;

var confirmButton = new DiscordButtonComponent(DiscordButtonStyle.Success, "debug-overrides-add-confirm-callback", "Yes");
var cancelButton = new DiscordButtonComponent(DiscordButtonStyle.Danger, "debug-overrides-add-cancel-callback", "No");
Expand Down Expand Up @@ -465,23 +468,112 @@ public async Task Apply(CommandContext ctx,

await msg.ModifyAsync(x => x.Content = $"{Program.cfgjson.Emoji.Success} Successfully applied {numAppliedOverrides}/{dictionary.Count} overrides for {user.Mention}!");
}
}

[Group("dump")]
[Description("Dump all of a channel's overrides from Discord or the database.")]
[IsBotOwner]
public class DumpChannelOverrides : BaseCommandModule
{
[GroupCommand]
[Command("discord")]
[Description("Dump all of a channel's overrides as they exist on the Discord channel. Does not read from db.")]
public async Task DumpFromDiscord(CommandContext ctx,
[Description("The channel to dump overrides for.")] DiscordChannel channel)
{
var overwrites = channel.PermissionOverwrites;

[Command("dumpchanneloverrides")]
[Description("Dump all of a channel's overrides. This pulls from Discord, not the database.")]
[IsBotOwner]
public async Task DumpChannelOverrides(CommandContext ctx,
[Description("The channel to dump overrides for.")] DiscordChannel channel)
{
var overwrites = channel.PermissionOverwrites;
string output = "";
foreach (var overwrite in overwrites)
{
output += $"{JsonConvert.SerializeObject(overwrite)}\n";
}

string output = "";
foreach (var overwrite in overwrites)
{
output += $"{JsonConvert.SerializeObject(overwrite)}\n";
await ctx.RespondAsync($"Dump from Discord:\n{await StringHelpers.CodeOrHasteBinAsync(output, "json")}");
}

[Command("db")]
[Aliases("database")]
[Description("Dump all of a channel's overrides as they are stored in the db.")]
public async Task DumpFromDb(CommandContext ctx,
[Description("The channel to dump overrides for.")] DiscordChannel channel)
{
List<DiscordOverwrite> overwrites = new();
try
{
var allOverwrites = await Program.db.HashGetAllAsync("overrides");
foreach (var overwrite in allOverwrites) {
var overwriteDict = JsonConvert.DeserializeObject<Dictionary<ulong, DiscordOverwrite>>(overwrite.Value);
if (overwriteDict is null) continue;
if (overwriteDict.TryGetValue(channel.Id, out var value))
overwrites.Add(value);
}
}
catch (Exception ex)
{
await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} Something went wrong while trying to fetch the overrides for {channel.Mention}!" +
" There are overrides in the database but I could not parse them. Check the database manually for details.");

Program.discord.Logger.LogError(ex, "Failed to read overrides from db for 'debug overrides dump'!");

return;
}

if (overwrites.Count == 0)
{
await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} No overrides found for {channel.Mention} in the database!");
return;
}

string output = "";
foreach (var overwrite in overwrites)
{
output += $"{JsonConvert.SerializeObject(overwrite)}\n";
}

await ctx.RespondAsync($"Dump from db:\n{await StringHelpers.CodeOrHasteBinAsync(output, "json")}");
}
}

[Command("cleanup")]
[Aliases("clean", "prune")]
[Description("Removes overrides from the db for channels that no longer exist.")]
[IsBotOwner]
public async Task CleanUpOverrides(CommandContext ctx)
{
var msg = await ctx.RespondAsync($"{Program.cfgjson.Emoji.Loading} Working on it...");
var removedOverridesCount = 0;

var dbOverwrites = await Program.db.HashGetAllAsync("overrides");
foreach (var userOverwrites in dbOverwrites)
{
var overwriteDict = JsonConvert.DeserializeObject<Dictionary<ulong, DiscordOverwrite>>(userOverwrites.Value);
foreach (var overwrite in overwriteDict)
{
bool channelExists = Program.discord.Guilds.Any(g => g.Value.Channels.Any(c => c.Key == overwrite.Key));

await ctx.RespondAsync(await StringHelpers.CodeOrHasteBinAsync(output, "json"));
if (!channelExists)
{
// Channel no longer exists, remove the override
overwriteDict.Remove(overwrite.Key);
removedOverridesCount++;
}
}

// Write back to db
// If the user now has no overrides, remove them from the db entirely
if (overwriteDict.Count == 0)
{
await Program.db.HashDeleteAsync("overrides", userOverwrites.Name);
}
else
{
// Otherwise, update the user's overrides in the db
await Program.db.HashSetAsync("overrides", userOverwrites.Name, JsonConvert.SerializeObject(overwriteDict));
}
}

await msg.ModifyAsync($"{Program.cfgjson.Emoji.Success} Done! Cleaned up {removedOverridesCount} overrides.");
}
}

[Command("dmchannel")]
Expand Down Expand Up @@ -523,83 +615,6 @@ public async Task SearchMembersCmd(CommandContext ctx, string regex)
await ctx.Channel.SendMessageAsync(await StringHelpers.CodeOrHasteBinAsync(JsonConvert.SerializeObject(memberIdsTonames, Formatting.Indented), "json"));
}

[Command("rawmessage")]
[Description("Dumps the raw data for a message.")]
[Aliases("rawmsg")]
[IsBotOwner]
public async Task DumpRawMessage(CommandContext ctx, [Description("The message whose raw data to get.")] string msgLinkOrId)
{
DiscordMessage message;
if (Constants.RegexConstants.discord_link_rx.IsMatch(msgLinkOrId))
{
// Assume the user provided a message link. Extract channel and message IDs to get message content.

// Pattern to extract channel and message IDs from URL
var idPattern = new Regex(@"(?:.*\/)([0-9]+)\/([0-9]+)$");

// Get channel ID
var targetChannelId = Convert.ToUInt64(idPattern.Match(msgLinkOrId).Groups[1].ToString().Replace("/", ""));

// Try to fetch channel
DiscordChannel channel;
try
{
channel = await ctx.Client.GetChannelAsync(targetChannelId);
}
catch
{
await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} I couldn't fetch the channel from your message link! Please try again.");
return;
}

// Get message ID
var targetMessage = Convert.ToUInt64(idPattern.Match(msgLinkOrId).Groups[2].ToString().Replace("/", ""));

// Try to fetch message
try
{
message = await channel.GetMessageAsync(targetMessage);
}
catch
{
await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} I couldn't fetch the message from your message link! Please try again.");
return;
}
}
else
{
if (msgLinkOrId.Length < 17)
{
await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} That doesn't look right. Try again.");
return;
}

ulong messageId;
try
{
messageId = Convert.ToUInt64(msgLinkOrId);
}
catch
{
await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} That doesn't look like a valid message ID. Try again.");
return;
}

try
{
message = await ctx.Channel.GetMessageAsync(messageId);
}
catch
{
await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} I wasn't able to read that message! Please try again.");
return;
}
}

var rawMsgData = JsonConvert.SerializeObject(message, Formatting.Indented);
await ctx.RespondAsync(await StringHelpers.CodeOrHasteBinAsync(rawMsgData, "json"));
}

private static async Task<(bool success, ulong failedOverwrite)> ImportOverridesFromChannelAsync(DiscordChannel channel)
{
// Imports overrides from the specified channel to the database. See 'debug overrides import' and 'debug overrides importall'
Expand Down
2 changes: 1 addition & 1 deletion Commands/InteractionCommands/AnnouncementInteractions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ internal class AnnouncementInteractions : ApplicationCommandModule
{
[SlashCommand("announcebuild", "Announce a Windows Insider build in the current channel.", defaultPermission: false)]
[SlashRequireHomeserverPerm(ServerPermLevel.TrialModerator)]
[SlashCommandPermissions(DiscordPermissions.ModerateMembers)]
[SlashCommandPermissions(permissions: DiscordPermission.ModerateMembers)]
public async Task AnnounceBuildSlashCommand(InteractionContext ctx,
[Choice("Windows 10", 10)]
[Choice("Windows 11", 11)]
Expand Down
Loading

0 comments on commit a771ac2

Please sign in to comment.