Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions Modix.Bot/Modules/ReplModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
using Modix.Services.Utilities;
using Newtonsoft.Json;

namespace Modix.Modules
namespace Modix.Bot.Modules
{
public class Result
{
Expand Down Expand Up @@ -59,7 +59,7 @@ public async Task ReplInvokeAsync(
[Summary("The code to execute.")]
string code)
{
if (!(Context.Channel is IGuildChannel) || !(Context.User is IGuildUser guildUser))
if (Context.Channel is not IGuildChannel || Context.User is not IGuildUser guildUser)
{
await ModifyOrSendErrorEmbed("The REPL can only be executed in public guild channels.");
return;
Expand All @@ -85,7 +85,6 @@ public async Task ReplInvokeAsync(
{
var client = _httpClientFactory.CreateClient(HttpClientNames.RetryOnTransientErrorPolicy);
res = await client.PostAsync(_replUrl, content);

}
catch (IOException ex)
{
Expand All @@ -101,7 +100,7 @@ await ModifyOrSendErrorEmbed("Recieved an invalid response from the REPL service
return;
}

if (!res.IsSuccessStatusCode & res.StatusCode != HttpStatusCode.BadRequest)
if (!res.IsSuccessStatusCode && res.StatusCode != HttpStatusCode.BadRequest)
{
await ModifyOrSendErrorEmbed($"Status Code: {(int)res.StatusCode} {res.StatusCode}", message);
return;
Expand Down Expand Up @@ -172,7 +171,7 @@ private async Task<EmbedBuilder> BuildEmbedAsync(IGuildUser guildUser, Result pa
{
embed.AddField(a => a.WithName("Console Output")
.WithValue(Format.Code(consoleOut.TruncateTo(MaxFormattedFieldSize), "txt")));
await embed.UploadToServiceIfBiggerThan(consoleOut, MaxFormattedFieldSize, _pasteService);
await embed.UploadToServiceIfBiggerThan(consoleOut, MaxFormattedFieldSize, _pasteService);
}

if (!string.IsNullOrWhiteSpace(parsedResult.Exception))
Expand All @@ -190,6 +189,7 @@ private static string FormatOrEmptyCodeblock(string input, string language)
{
if (string.IsNullOrWhiteSpace(input))
return "```\n```";

return Format.Code(input, language);
}
}
Expand Down
19 changes: 7 additions & 12 deletions Modix.Services/CodePaste/CodePasteService.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
using Discord;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Discord;
using Modix.Data.Utilities;
using Modix.Services.Utilities;
using Newtonsoft.Json.Linq;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace Modix.Services.CodePaste
{
Expand Down Expand Up @@ -63,22 +63,17 @@ public async Task<string> UploadCodeAsync(IMessage msg, string code = null)
var formatted = string.Format(Header,
$"{msg.Author.Username}#{msg.Author.DiscriminatorValue}", msg.Channel.Name,
DateTimeOffset.UtcNow.ToString("dddd, MMMM d yyyy @ H:mm:ss"), msg.Id,
FormatUtilities.FixIndentation(code ?? msg.Content));
code ?? msg.Content);

return await UploadCodeAsync(formatted);
}

public Embed BuildEmbed(IUser user, string content, string url)
{
var cleanCode = FormatUtilities.FixIndentation(content);

return new EmbedBuilder()
public static Embed BuildEmbed(IUser user, string content, string url) => new EmbedBuilder()
.WithTitle("Your message was re-uploaded")
.WithUserAsAuthor(user)
.WithDescription(cleanCode.Trim().Truncate(200, 6))
.WithDescription(content.Trim().Truncate(200, 6))
.AddField("Auto-Paste", url, true)
.WithColor(new Color(95, 186, 125))
.Build();
}
}
}
64 changes: 10 additions & 54 deletions Modix.Services/Utilities/FormatUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ namespace Modix.Services.Utilities
{
public static class FormatUtilities
{
private static readonly Regex _buildContentRegex = new Regex(@"```([^\s]+|)");
private static readonly Regex _buildContentRegex = new(@"```([^\s]*)", RegexOptions.Compiled);

/// <summary>
/// Prepares a piece of input code for use in HTTP operations
Expand All @@ -34,54 +34,9 @@ public static StringContent BuildContent(string code)
return new StringContent(cleanCode, Encoding.UTF8, "text/plain");
}

/// <summary>
/// Attempts to get the language of the code piece
/// </summary>
/// <param name="code">The code</param>
/// <returns>The code language if a match is found, null of none are found</returns>
public static string GetCodeLanguage(string message)
{
var match = _buildContentRegex.Match(message);
if (match.Success)
{
var codeLanguage = match.Groups[1].Value;
return string.IsNullOrEmpty(codeLanguage) ? null : codeLanguage;
}
else
{
return null;
}
}

public static string StripFormatting(string code)
{
var cleanCode = _buildContentRegex.Replace(code.Trim(), string.Empty); //strip out the ` characters and code block markers
cleanCode = cleanCode.Replace("\t", " "); //spaces > tabs
cleanCode = FixIndentation(cleanCode);
return cleanCode;
}

/// <summary>
/// Attempts to fix the indentation of a piece of code by aligning the left sidie.
/// </summary>
/// <param name="code">The code to align</param>
/// <returns>The newly aligned code</returns>
public static string FixIndentation(string code)
{
var lines = code.Split('\n');
var indentLine = lines.SkipWhile(d => d.FirstOrDefault() != ' ').FirstOrDefault();

if (indentLine != null)
{
var indent = indentLine.LastIndexOf(' ') + 1;

var pattern = $@"^[^\S\n]{{{indent}}}";

return Regex.Replace(code, pattern, "", RegexOptions.Multiline);
}

return code;
}
public static string StripFormatting(string code) =>
//strip out the ` characters and code block markers
_buildContentRegex.Replace(code.Trim(), string.Empty);

public static async Task UploadToServiceIfBiggerThan(this EmbedBuilder embed, string content, uint size, CodePasteService service)
{
Expand All @@ -106,7 +61,7 @@ public static string FormatInfractionCounts(IDictionary<InfractionType, int> cou
return "This user is clean - no active infractions!";
}

var formatted =
var formatted =
counts.Select(d =>
{
var formattedKey = d.Key.Humanize().ToLower();
Expand All @@ -116,7 +71,7 @@ public static string FormatInfractionCounts(IDictionary<InfractionType, int> cou

return $"This user has {formatted}";
}

/// <summary>
/// Collapses plural forms into a "singular(s)"-type format.
/// </summary>
Expand Down Expand Up @@ -174,7 +129,7 @@ public static IReadOnlyCollection<string> CollapsePlurals(IReadOnlyCollection<st
? word.First()
: word.Last();

parenthesized[aliasIndex][wordIndex] = $"{longestForm.Substring(0, indexOfDifference)}({longestForm.Substring(indexOfDifference)})";
parenthesized[aliasIndex][wordIndex] = $"{longestForm[..indexOfDifference]}({longestForm[indexOfDifference..]})";
}
else
{
Expand Down Expand Up @@ -319,7 +274,9 @@ bool TryReplaceLine(Index index, string line)
}

int GetRemainingLineCount()
=> lines.Length - processedLines.Count - braceOnlyLinesEliminated;
{
return lines.Length - processedLines.Count - braceOnlyLinesEliminated;
}

string GetRemainingLineCountComment(int remainingCount)
{
Expand All @@ -337,6 +294,5 @@ void AddRemainingLineComment()
processedLines.Add(GetRemainingLineCountComment(GetRemainingLineCount()));
}
}
#nullable restore
}
}