cs-codex-dist-tests/Tools/BiblioTech/Options/CommandContext.cs

103 lines
2.8 KiB
C#
Raw Permalink Normal View History

2023-10-24 13:25:45 +00:00
using Discord.WebSocket;
namespace BiblioTech.Options
{
public class CommandContext
{
2023-11-09 09:13:34 +00:00
private const string AttachmentFolder = "attachments";
2023-10-24 13:25:45 +00:00
public CommandContext(SocketSlashCommand command, IReadOnlyCollection<SocketSlashCommandDataOption> options)
{
Command = command;
Options = options;
2023-11-09 09:13:34 +00:00
var attachmentPath = Path.Combine(Program.Config.DataPath, AttachmentFolder);
if (Directory.Exists(attachmentPath))
{
Directory.CreateDirectory(attachmentPath);
}
2023-10-24 13:25:45 +00:00
}
public SocketSlashCommand Command { get; }
public IReadOnlyCollection<SocketSlashCommandDataOption> Options { get; }
2023-10-25 08:54:26 +00:00
2023-11-09 09:13:34 +00:00
public async Task Followup(string line)
2023-10-25 08:54:26 +00:00
{
2023-11-09 09:13:34 +00:00
var array = line.Split(Environment.NewLine);
await Followup(array);
}
public async Task Followup(string[] lines)
{
var chunker = new LineChunker(lines);
var chunks = chunker.GetChunks();
if (!chunks.Any()) return;
// First chunk is a modification of the original message.
// Everything after that, we must create a new message.
var first = chunks.First();
chunks.RemoveAt(0);
2023-11-08 12:33:48 +00:00
await Command.ModifyOriginalResponseAsync(m =>
{
2023-11-09 09:13:34 +00:00
m.Content = FormatChunk(first);
});
2023-11-09 09:13:34 +00:00
foreach (var remaining in chunks)
{
await Command.FollowupAsync(FormatChunk(remaining));
}
}
private string FormatChunk(string[] chunk)
{
return string.Join(Environment.NewLine, chunk);
}
}
public class LineChunker
{
private readonly List<string> input;
private readonly int maxCharacters;
public LineChunker(string[] input, int maxCharacters = 1950)
{
this.input = input.ToList();
this.maxCharacters = maxCharacters;
}
public List<string[]> GetChunks()
{
var result = new List<string[]>();
while (input.Any())
{
result.Add(GetChunk());
}
return result;
2023-10-25 08:54:26 +00:00
}
2023-11-09 09:13:34 +00:00
private string[] GetChunk()
2023-10-25 08:54:26 +00:00
{
2023-11-09 09:13:34 +00:00
var totalLength = 0;
var result = new List<string>();
while (input.Any())
{
var nextLine = input[0];
var nextLength = totalLength + nextLine.Length;
if (nextLength > maxCharacters)
{
return result.ToArray();
}
input.RemoveAt(0);
result.Add(nextLine);
totalLength += nextLine.Length;
}
2023-11-09 09:13:34 +00:00
return result.ToArray();
2023-10-25 08:54:26 +00:00
}
2023-10-24 13:25:45 +00:00
}
}