Skip to content

Commit

Permalink
New splitting algorithm?
Browse files Browse the repository at this point in the history
  • Loading branch information
LaineZ committed Oct 7, 2024
1 parent 7f197f3 commit 0b23e31
Show file tree
Hide file tree
Showing 3 changed files with 102 additions and 52 deletions.
74 changes: 30 additions & 44 deletions fs24bot3/Backend/IRC.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,14 @@

namespace fs24bot3.Backend;


public class IrcConfiguration
{
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "network")]
public string Network { get; set; }
[DataMember(Name = "channel")]
public string Channel { get; set; }
[DataMember(Name = "port")]
public int Port { get; set; }
[DataMember(Name = "nickserv_pass")]
public string NickservPass { get; set; }
[DataMember(Name = "server_pass")]
public string ServerPassword { get; set; }
[DataMember(Name = "name")] public string Name { get; set; }
[DataMember(Name = "network")] public string Network { get; set; }
[DataMember(Name = "channel")] public string Channel { get; set; }
[DataMember(Name = "port")] public int Port { get; set; }
[DataMember(Name = "nickserv_pass")] public string NickservPass { get; set; }
[DataMember(Name = "server_pass")] public string ServerPassword { get; set; }

public IrcConfiguration()
{
Expand Down Expand Up @@ -117,7 +110,11 @@ private async void Client_OnIRCMessageParsed(Client client, ParsedIRCMessage mes

if (!msg.Sender.UserIsIgnored())
{
if (msg.Kind == MessageKind.Message) { BotContext.MessageTrigger(msg); }
if (msg.Kind == MessageKind.Message)
{
BotContext.MessageTrigger(msg);
}

await BotContext.ExecuteCommand(msg, prefix);
}
}
Expand Down Expand Up @@ -165,6 +162,7 @@ public async void SetupNick(string nickname)
await BotClient.SendRaw("NICK " + nickname);
}
}

public async void JoinChannel(string name)
{
await BotClient.SendRaw("JOIN " + name);
Expand All @@ -184,44 +182,32 @@ public void Process()

public async Task SendMessage(string channel, string message)
{
List<string> msgLines = message.Split("\n").Where(x => !string.IsNullOrWhiteSpace(x)).ToList();
var sb = new StringBuilder(message);
foreach (var (tag, value) in Fmt)
{
sb.Replace($"[{tag}]", value);
}

List<string> msgLines = sb.ToString().Split("\n").Where(x => !string.IsNullOrWhiteSpace(x)).ToList();
int count = 0;

foreach (string outputstr in msgLines)
{
var sb = new StringBuilder(outputstr);
foreach (var (tag, value) in Fmt)
{
sb.Replace($"[{tag}]", value);
}
var currentSplit = MessageHelper.SplitByWords(outputstr);

if (sb.Length < 1000)
foreach (var split in currentSplit)
{
await BotClient.SendAsync(new PrivMsgMessage(channel, sb.ToString()));
count++;

if (count > 3)
await BotClient.SendAsync(new PrivMsgMessage(channel, split));
count += 1;
if (count > 4)
{
Thread.Sleep(500);
string link = await InternetServicesHelper.UploadToTrashbin(MessageHelper.StripIRC(message),
"addplain");
await BotClient.SendAsync(new PrivMsgMessage(channel, "Полный вывод: " + link));
return;
}
}
else
{
string link = await InternetServicesHelper.UploadToTrashbin(
MessageHelper.StripIRC(message), "addplain");
await BotClient.SendAsync(new PrivMsgMessage(channel, $"Слишком жесткое сообщение с длинной " +
$"{sb.Length} символов! Психанул?!?!?!"));
await BotClient.SendAsync(new PrivMsgMessage(channel, "Полный вывод: " + link));
return;
}

if (count > 4)
{
string link = await InternetServicesHelper.UploadToTrashbin(MessageHelper.StripIRC(message),
"addplain");
await BotClient.SendAsync(new PrivMsgMessage(channel, "Полный вывод: " + link));
return;
}
}
}

Expand All @@ -232,7 +218,7 @@ await BotClient.SendAsync(new PrivMsgMessage(channel, $"Слишком жест
/// <param name="user"></param>
/// <returns></returns>
public async Task<bool> EnsureAuthorization(Core.User user)
{
{
var tcs = new TaskCompletionSource<bool>();
ParsedIRCMessageHandler messageHandler = null;

Expand Down
8 changes: 8 additions & 0 deletions fs24bot3/Core/OneLinerOptionParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ namespace fs24bot3.Core;
class OneLinerOptionParser
{
public List<(string, string)> Options { get; }
public List<string> AllowedOptions { get; set; }
public string RetainedInput { get; }

private readonly Regex SearchTermRegex = new Regex(
Expand All @@ -33,6 +34,7 @@ public OneLinerOptionParser(string input)
{
RetainedInput = input;
Options = new List<(string, string)>();
AllowedOptions = new List<string>();

Match match = SearchTermRegex.Match(input);
foreach (Capture term in match.Groups["term"].Captures.Cast<Capture>())
Expand All @@ -57,6 +59,12 @@ public OneLinerOptionParser(string input)
{
RetainedInput = RetainedInput.Replace($"{prefix.Value}:{termString.Value}", "");
Log.Verbose("option: {0} value: {1}", prefix.Value, termString.Value);

if (AllowedOptions.Any() && !AllowedOptions.Contains(prefix.Value.ToLower()))
{
continue;
}

Options.Add((prefix.Value, termString.Value));
}

Expand Down
72 changes: 64 additions & 8 deletions fs24bot3/Helpers/MessageHelper.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
using fs24bot3.Models;
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using Serilog;

namespace fs24bot3.Helpers;

class MessageHelper
{
private static string GenerateBaseName(int len, string[] consonants, string[] vowels)
Expand All @@ -13,7 +16,8 @@ private static string GenerateBaseName(int len, string[] consonants, string[] vo
string Name = "";
Name += consonants[r.Next(consonants.Length)].ToUpper();
Name += vowels[r.Next(vowels.Length)];
int b = 2; //b tells how many times a new letter has been added. It's 2 right now because the first two letters are already in the name.
int
b = 2; //b tells how many times a new letter has been added. It's 2 right now because the first two letters are already in the name.
while (b < len)
{
Name += consonants[r.Next(consonants.Length)];
Expand All @@ -24,7 +28,7 @@ private static string GenerateBaseName(int len, string[] consonants, string[] vo

return Name;
}

public static string Bar(int width, int perc)
{
string[] bars = new string[] { " ", "▏", "▎", "▍", "▌", "▋", "▊", "▉", "█" };
Expand Down Expand Up @@ -59,13 +63,20 @@ public static string Bar(int width, int perc)
{
color = "11";
}
return $"▕{color}{new string('█', blocks)}{lastBlock.PadRight(emptyBlocks > 0 ? emptyBlocks : 0)}\u000f\u0003";

return
$"▕{color}{new string('█', blocks)}{lastBlock.PadRight(emptyBlocks > 0 ? emptyBlocks : 0)}\u000f\u0003";
}

public static string GenerateName(int len)
{
return GenerateBaseName(len, new string[] { "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "l", "n", "p", "q", "r", "s", "sh", "zh", "t", "v", "w", "x" },
new string[] { "a", "e", "i", "o", "u", "ae", "y" });
return GenerateBaseName(len,
new string[]
{
"b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "l", "n", "p", "q", "r", "s", "sh", "zh", "t", "v",
"w", "x"
},
new string[] { "a", "e", "i", "o", "u", "ae", "y" });
}

public static string StripIRC(string input)
Expand All @@ -75,8 +86,12 @@ public static string StripIRC(string input)

public static string GenerateNameRus(int len)
{
return GenerateBaseName(len, new string[] { "б", "в", "г", "д", "ж", "з", "й", "к", "л", "м", "н", "п", "р", "с", "т", "ф", "х", "ц", "ч", "ш", "щ" },
new string[] { "а", "у", "о", "ы", "и", "э", "я", "ю", "ё", "е" });
return GenerateBaseName(len,
new string[]
{
"б", "в", "г", "д", "ж", "з", "й", "к", "л", "м", "н", "п", "р", "с", "т", "ф", "х", "ц", "ч", "ш", "щ"
},
new string[] { "а", "у", "о", "ы", "и", "э", "я", "ю", "ё", "е" });
}

public static string AllEnumOptionsToString(Enum en)
Expand Down Expand Up @@ -141,9 +156,11 @@ public static int LevenshteinDistance(string s, string t)
d[i, j] = Math.Min(Math.Min(min1, min2), min3);
}
}

//Log.Verbose("{0} {1} score: {2}", s, t, d[n, m]);
return d[n, m];
}

public static string BoldToIrc(string input)
{
// very sketchy html-like irc message formatter =)
Expand All @@ -156,4 +173,43 @@ public static string BoldToIrc(string input)
doc.LoadHtml(textResult.ToString());
return doc.DocumentNode.InnerText;
}
}


const int MESSAGE_SIZE = 400;

public static List<string> SplitByWords(string input)
{
List<string> result = new List<string>();
StringBuilder currentMessage = new StringBuilder();
int currentMessageBytes = 0;

foreach (var word in input.Split(' '))
{
int wordBytes = Encoding.UTF8.GetByteCount(word);

if (currentMessageBytes + wordBytes + (currentMessage.Length > 0 ? 1 : 0) > MESSAGE_SIZE)
{
result.Add(currentMessage.ToString().Trim());
currentMessage.Clear();
currentMessageBytes = 0;
}

if (currentMessage.Length > 0)
{
currentMessage.Append(" ");
currentMessageBytes += 1;
}

currentMessage.Append(word);
currentMessageBytes += wordBytes;
}

if (currentMessage.Length > 0)
{
result.Add(currentMessage.ToString().Trim());
}

return result;
}

}

0 comments on commit 0b23e31

Please sign in to comment.