riff/Program.cs
2025-06-26 02:38:41 +00:00

147 lines
3.9 KiB
C#

using System.Data;
using System.Net.Sockets;
using System.Text;
namespace riff;
class Program
{
static void Main(string[] args)
{
var bot = new IRCBot("testbot", "~nebula");
var subBot = new SubBot("otherbot", "also ~nebula");
new Thread(new ThreadStart(bot.MainLoop)).Start();
new Thread(new ThreadStart(subBot.MainLoop)).Start();
}
public class IRCBot
{
private int Port = 6667;
private string Host = "localhost";
private string? Nick;
private string? RealName;
private TcpClient Client;
private NetworkStream Stream;
public IRCBot(string nick, string realname)
{
Nick = nick;
RealName = realname;
Client = new TcpClient(Host, Port);
Stream = Client.GetStream();
SendLine($"NICK {Nick}");
SendLine($"USER {Nick} 0 * :{RealName}");
SendLine("JOIN #bots");
}
public void SendLine(string line)
{
Byte[] bytes = Encoding.UTF8.GetBytes(line + "\r\n");
Stream.Write(bytes, 0, bytes.Length);
}
public virtual void TestPrompt()
{
Console.WriteLine("Main class says hello");
}
public void MainLoop()
{
using var reader = new StreamReader(Stream, Encoding.UTF8);
while (true)
{
string? line = reader.ReadLine();
if (line == null)
{
Console.WriteLine($"{Nick} disconnected");
break;
}
if (line.StartsWith("PING"))
{
SendLine("PONG " + line[5..]);
continue;
}
TestPrompt();
IRCMessage msg = new(line);
switch (msg.Command)
{
case "PRIVMSG":
// PRIVMSG privmsg = new(msg);
// Console.WriteLine(privmsg.Body);
break;
}
}
}
}
public class SubBot : IRCBot
{
public Action[] commands = [];
public SubBot(string nick, string realname) : base(nick, realname)
{
}
public void HelpCommand(string line)
{
SendLine("PRIVMSG #bots :helptext");
}
public override void TestPrompt()
{
Console.WriteLine("hello from SubBot");
}
}
public class IRCMessage
{
public string? Source;
public string Command;
public List<string> Arguments;
public IRCMessage(string line)
{
string[] split;
List<string> args = new();
if (line[0] == ':')
{
split = line[1..].Split(' ', 2);
Source = split[0];
line = split[1];
}
if (line.IndexOf(" :") != -1)
{
split = line.Split(" :", 2);
foreach (string arg in split[0].Split(' '))
args.Add(arg);
args.Add(split[1]);
}
else
{
foreach (string arg in line.Split(' '))
args.Add(arg);
}
Command = args[0];
Arguments = args[1..];
}
}
public class PRIVMSG
{
public string Body { get; set; }
public string Channel { get; set; }
public string Nick { get; set; }
public PRIVMSG(IRCMessage message)
{
if (message.Source == null)
throw new NoNullAllowedException();
Nick = message.Source.Substring(0, message.Source.IndexOf("!") - 1);
Channel = message.Arguments[0];
Body = message.Arguments[1];
}
}
}