From 2d2e25b4ee36a0d3a2dd2a7e07cef37c05562c23 Mon Sep 17 00:00:00 2001 From: Erisa A Date: Mon, 8 Jul 2024 01:03:13 +0100 Subject: [PATCH] Replace hastebin usage for long messages with a helper function --- Commands/Debug.cs | 139 +++--------------- .../InteractionCommands/DebugInteractions.cs | 22 +-- Commands/Lists.cs | 21 +-- Events/MessageEvent.cs | 17 +-- Helpers/StringHelpers.cs | 33 +++++ 5 files changed, 59 insertions(+), 173 deletions(-) diff --git a/Commands/Debug.cs b/Commands/Debug.cs index 2f7a531c..ebff466e 100644 --- a/Commands/Debug.cs +++ b/Commands/Debug.cs @@ -42,23 +42,7 @@ public async Task MuteDebug(CommandContext ctx, DiscordUser targetUser = default strOut += $"{entry.Value}\n"; } } - if (strOut.Length > 1930) - { - HasteBinResult hasteResult = await Program.hasteUploader.Post(strOut); - if (hasteResult.IsSuccess) - { - await ctx.RespondAsync($"{Program.cfgjson.Emoji.Warning} Output exceeded character limit: {hasteResult.FullUrl}.json"); - } - else - { - Program.discord.Logger.LogError("Error ocurred uploading to Hastebin with status code: {code}\nPayload: {output}", hasteResult.StatusCode, strOut); - await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} Unknown error occurred during upload to Hastebin.\nPlease try again or contact the bot owner."); - } - } - else - { - await ctx.RespondAsync($"```json\n{strOut}\n```"); - } + await ctx.RespondAsync(await StringHelpers.CodeOrHasteBinAsync(strOut, "json")); } else // if (targetUser != default) { @@ -97,23 +81,7 @@ public async Task BanDebug(CommandContext ctx, DiscordUser targetUser = default) strOut += $"{entry.Value}\n"; } } - if (strOut.Length > 1930) - { - HasteBinResult hasteResult = await Program.hasteUploader.Post(strOut); - if (hasteResult.IsSuccess) - { - await ctx.RespondAsync($"{Program.cfgjson.Emoji.Warning} Output exceeded character limit: {hasteResult.FullUrl}.json"); - } - else - { - Program.discord.Logger.LogError("Error ocurred uploading to Hastebin with status code: {code}\nPayload: {output}", hasteResult.StatusCode, strOut); - await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} Unknown error occurred during upload to Hastebin.\nPlease try again or contact the bot owner."); - } - } - else - { - await ctx.RespondAsync($"```json\n{strOut}\n```"); - } + await ctx.RespondAsync(await StringHelpers.CodeOrHasteBinAsync(strOut, "json")); } else // if (targetUser != default) { @@ -188,25 +156,11 @@ public async Task Shell(CommandContext ctx, [RemainingText] string command) ShellResult finishedShell = RunShellCommand(command); string result = Regex.Replace(finishedShell.result, "ghp_[0-9a-zA-Z]{36}", "ghp_REDACTED").Replace(Environment.GetEnvironmentVariable("CLIPTOK_TOKEN"), "REDACTED").Replace(Environment.GetEnvironmentVariable("CLIPTOK_ANTIPHISHING_ENDPOINT") ?? "DUMMYVALUE", "REDACTED"); - if (result.Length > 1947) - { - HasteBinResult hasteResult = await Program.hasteUploader.Post(result); - if (hasteResult.IsSuccess) - { - await msg.ModifyAsync($"Done, but output exceeded character limit! (`{result.Length}`/`1947`)\n" + - $"Full output can be viewed here: https://haste.erisa.uk/{hasteResult.Key}\nProcess exited with code `{finishedShell.proc.ExitCode}`."); - } - else - { - Program.discord.Logger.LogError("Error ocurred uploading to Hastebin with status code: {code}\nPayload: {output}", hasteResult.StatusCode, finishedShell.result); - await msg.ModifyAsync($"Error occurred during upload to Hastebin.\nAction was executed regardless, shell exit code was `{finishedShell.proc.ExitCode}`. Hastebin status code is `{hasteResult.StatusCode}`.\nPlease check the console/log for the command output."); - } - } - else - { - await msg.ModifyAsync($"Done, output: ```\n" + - $"{result}```Process exited with code `{finishedShell.proc.ExitCode}`."); - } + string msgContent = await StringHelpers.CodeOrHasteBinAsync(result, charLimit: 1947); + + msgContent += $"\nProcess exited with code `{finishedShell.proc.ExitCode}`."; + + await msg.ModifyAsync(msgContent); } [Command("logs")] @@ -214,24 +168,14 @@ public async Task Logs(CommandContext ctx) { await DiscordHelpers.SafeTyping(ctx.Channel); - string result = Regex.Replace(Program.outputCapture.ToString(), "ghp_[0-9a-zA-Z]{36}", "ghp_REDACTED").Replace(Environment.GetEnvironmentVariable("CLIPTOK_TOKEN"), "REDACTED").Replace(Environment.GetEnvironmentVariable("CLIPTOK_ANTIPHISHING_ENDPOINT"), "REDACTED"); + string result = Regex.Replace(Program.outputCapture.ToString(), "ghp_[0-9a-zA-Z]{36}", "ghp_REDACTED").Replace(Environment.GetEnvironmentVariable("CLIPTOK_TOKEN"), "REDACTED"); - if (result.Length > 1947) + if (Environment.GetEnvironmentVariable("CLIPTOK_ANTIPHISHING_ENDPOINT") is not null) { - HasteBinResult hasteURL = await Program.hasteUploader.Post(result); - if (hasteURL.IsSuccess) - { - await ctx.RespondAsync($"Logs: https://haste.erisa.uk/{hasteURL.Key}"); - } - else - { - await ctx.RespondAsync($"Error occurred during upload to Hastebin. Hastebin status code is `{hasteURL.StatusCode}`.\n"); - } - } - else - { - await ctx.RespondAsync($"Logs:```\n{result}```"); + result = result.Replace(Environment.GetEnvironmentVariable("CLIPTOK_ANTIPHISHING_ENDPOINT"), "REDACTED"); } + + await ctx.RespondAsync(await StringHelpers.CodeOrHasteBinAsync(result)); } [Command("dumpwarnings"), Description("Dump all warning data. EXTREMELY computationally expensive, use with caution.")] @@ -304,23 +248,7 @@ public async Task CheckPendingChannelEvents(CommandContext ctx) list += "```\n"; } - if (list.Length > 1990) - { - HasteBinResult hasteResult = await Program.hasteUploader.Post(list); - if (hasteResult.IsSuccess) - { - await ctx.RespondAsync($"{Program.cfgjson.Emoji.Warning} Output exceeded character limit: {hasteResult.FullUrl}.json"); - } - else - { - Program.discord.Logger.LogError("Error ocurred uploading to Hastebin with status code: {code}\nPayload: {output}", hasteResult.StatusCode, list); - await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} Unknown error occurred during upload to Hastebin.\nPlease try again or contact the bot owner."); - } - } - else - { - await ctx.RespondAsync(list); - } + await ctx.RespondAsync(await StringHelpers.CodeOrHasteBinAsync(list)); } [Group("overrides")] @@ -366,16 +294,8 @@ await ctx.RespondAsync( if (response.Length > 2000) { - HasteBinResult hasteResult = await Program.hasteUploader.Post(response); - if (hasteResult.IsSuccess) - { - await ctx.RespondAsync($"{Program.cfgjson.Emoji.Warning} Output exceeded character limit: {hasteResult.FullUrl}.json"); - } - else - { - Program.discord.Logger.LogError("Error ocurred uploading to Hastebin with status code: {code}\nPayload: {output}", hasteResult.StatusCode, response); - await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} Unknown error occurred during upload to Hastebin.\nPlease try again or contact the bot owner."); - } + // I am abusing my own helper here. I know for a fact that it will be over the char limit so I know it won't return a code block. + await ctx.RespondAsync(await StringHelpers.CodeOrHasteBinAsync(response)); } else { @@ -470,23 +390,7 @@ public async Task DumpChannelOverrides(CommandContext ctx, output += $"{JsonConvert.SerializeObject(overwrite)}\n"; } - if (output.Length > 1990) - { - HasteBinResult hasteResult = await Program.hasteUploader.Post(output); - if (hasteResult.IsSuccess) - { - await ctx.RespondAsync($"{Program.cfgjson.Emoji.Warning} Output exceeded character limit: {hasteResult.FullUrl}.json"); - } - else - { - Program.discord.Logger.LogError("Error ocurred uploading to Hastebin with status code: {code}\nPayload: {output}", hasteResult.StatusCode, output); - await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} Unknown error occurred during upload to Hastebin.\nPlease try again or contact the bot owner."); - } - } - else - { - await ctx.RespondAsync($"```\n{output}\n```"); - } + await ctx.RespondAsync(await StringHelpers.CodeOrHasteBinAsync(output, "json")); } [Command("dmchannel")] @@ -507,16 +411,7 @@ public async Task DumpDMChannels(CommandContext ctx) var json = JsonConvert.SerializeObject(dmChannels, Formatting.Indented); - HasteBinResult hasteResult = await Program.hasteUploader.Post(json); - if (hasteResult.IsSuccess) - { - await ctx.RespondAsync(hasteResult.FullUrl); - } - else - { - Program.discord.Logger.LogError("Error ocurred uploading to Hastebin with status code: {code}\nPayload: {output}", hasteResult.StatusCode, json); - await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} Unknown error occurred during upload to Hastebin.\nPlease try again or contact the bot owner."); - } + await ctx.RespondAsync(await StringHelpers.CodeOrHasteBinAsync(json, "json")); } private static async Task<(bool success, ulong failedOverwrite)> ImportOverridesFromChannelAsync(DiscordChannel channel) diff --git a/Commands/InteractionCommands/DebugInteractions.cs b/Commands/InteractionCommands/DebugInteractions.cs index 471f5a49..45e27ca8 100644 --- a/Commands/InteractionCommands/DebugInteractions.cs +++ b/Commands/InteractionCommands/DebugInteractions.cs @@ -17,29 +17,15 @@ public async Task ScamCheck(InteractionContext ctx, [Option("input", "Domain or string responseToSend; if (match) { - responseToSend = $"Match found:\n```json\n{responseText}\n```"; - + responseToSend = $"Match found:\n`"; } else { - responseToSend = $"No valid match found.\nHTTP Status `{(int)httpStatus}`, result:\n```json\n{responseText}\n```"; + responseToSend = $"No valid match found.\nHTTP Status `{(int)httpStatus}`, result:\n"; } - if (responseToSend.Length > 1940) - { - try - { - HasteBinResult hasteURL = await Program.hasteUploader.Post(responseText); - if (hasteURL.IsSuccess) - responseToSend = hasteURL.FullUrl + ".json"; - else - responseToSend = "Response was too big and Hastebin failed, sorry."; - } - catch - { - responseToSend = "Response was too big and Hastebin failed, sorry."; - } - } + responseToSend += await StringHelpers.CodeOrHasteBinAsync(responseText, "json"); + await ctx.RespondAsync(responseToSend); } else diff --git a/Commands/Lists.cs b/Commands/Lists.cs index 519e8373..2d7c639e 100644 --- a/Commands/Lists.cs +++ b/Commands/Lists.cs @@ -145,29 +145,16 @@ public async Task ScamCheck(CommandContext ctx, [RemainingText, Description("Dom string responseToSend; if (match) { - responseToSend = $"Match found:\n```json\n{responseText}\n```"; + responseToSend = $"Match found:\n```json\n{responseText}\n"; } else { - responseToSend = $"No valid match found.\nHTTP Status `{(int)httpStatus}`, result:\n```json\n{responseText}\n```"; + responseToSend = $"No valid match found.\nHTTP Status `{(int)httpStatus}`, result:\n"; } - if (responseToSend.Length > 1940) - { - try - { - HasteBinResult hasteURL = await Program.hasteUploader.Post(responseText); - if (hasteURL.IsSuccess) - responseToSend = hasteURL.FullUrl + ".json"; - else - responseToSend = "Response was too big and Hastebin failed, sorry."; - } - catch - { - responseToSend = "Response was too big and Hastebin failed, sorry."; - } - } + responseToSend += await StringHelpers.CodeOrHasteBinAsync(responseText, "json"); + await ctx.RespondAsync(responseToSend); } else diff --git a/Events/MessageEvent.cs b/Events/MessageEvent.cs index d8d335f8..3a97be4a 100644 --- a/Events/MessageEvent.cs +++ b/Events/MessageEvent.cs @@ -522,22 +522,7 @@ public static async Task MessageHandlerAsync(DiscordClient client, DiscordMessag DiscordMessage msg = await message.Channel.SendMessageAsync($"{Program.cfgjson.Emoji.Denied} {message.Author.Mention} was automatically warned: **{reason.Replace("`", "\\`").Replace("*", "\\*")}**"); var warning = await WarningHelpers.GiveWarningAsync(message.Author, client.CurrentUser, reason, contextMessage: msg, message.Channel, " automatically "); - string responseToSend = $"```json\n{responseText}\n```"; - if (responseToSend.Length > 1940) - { - try - { - HasteBinResult hasteURL = await Program.hasteUploader.Post(responseText); - if (hasteURL.IsSuccess) - responseToSend = hasteURL.FullUrl + ".json"; - else - responseToSend = "Response was too big and Hastebin failed, sorry."; - } - catch - { - responseToSend = "Response was too big and Hastebin failed, sorry."; - } - } + string responseToSend = await StringHelpers.CodeOrHasteBinAsync(responseText, "json", 1000, true); (string name, string value, bool inline) extraField = new("API Response", responseToSend, false); await InvestigationsHelpers.SendInfringingMessaageAsync("investigations", message, reason, warning.ContextLink, extraField); diff --git a/Helpers/StringHelpers.cs b/Helpers/StringHelpers.cs index 0300607d..835b76fc 100644 --- a/Helpers/StringHelpers.cs +++ b/Helpers/StringHelpers.cs @@ -28,5 +28,38 @@ public static string WarningContextString(DiscordUser user, string reason, bool else return $"{Program.cfgjson.Emoji.Warning} {user.Mention} was warned: **{reason.Replace("`", "\\`").Replace("*", "\\*")}**"; } + + public static async Task CodeOrHasteBinAsync(string input, string language = "", int charLimit = 1930, bool plain = false) + { + if (input.Length > charLimit) + { + HasteBinResult hasteResult = await Program.hasteUploader.Post(input); + if (hasteResult.IsSuccess) + { + var hasteUrl = hasteResult.FullUrl; + if (language != "") + { + hasteUrl = hasteUrl + "." + language; + } + + if (plain) + return hasteUrl; + else + return $"{Program.cfgjson.Emoji.Warning} Output exceeded character limit: {hasteUrl}"; + } + else + { + Program.discord.Logger.LogError("Error ocurred uploading to Hastebin with status code: {code}\nPayload: {output}", hasteResult.StatusCode, input); + if (plain) + return "Error, check logs."; + + return $"{Program.cfgjson.Emoji.Error} Unknown error occurred during upload to Hastebin.\nPlease try again or contact the bot owner."; + } + } + else + { + return $"```{language}\n{input}\n```"; + } + } } }