private void Window_Loaded(object sender, RoutedEventArgs e) { Console.WriteLine("BOOTING MEM"); MemAndReg.ReBootRAM(); Console.WriteLine("RAM BOOTED"); Console.WriteLine("LOADING INSTRUCTION SET"); Program.opcodes.Add("NOP", Functions.NOP); Program.opcodes.Add("NEG", Functions.NEG); Program.opcodes.Add("OR", Functions.OR); Program.opcodes.Add("AND", Functions.AND); Program.opcodes.Add("XOR", Functions.XOR); Program.opcodes.Add("ADD", Functions.ADD); Program.opcodes.Add("SUB", Functions.SUB); Program.opcodes.Add("MUL", Functions.MUL); Program.opcodes.Add("DIV", Functions.DIV); Program.opcodes.Add("MOD", Functions.MOD); Program.opcodes.Add("EQL", Functions.EQL); Program.opcodes.Add("LST", Functions.LST); Program.opcodes.Add("GRT", Functions.GRT); Program.opcodes.Add("IGT", Functions.IGT); Program.opcodes.Add("ILT", Functions.ILT); Program.opcodes.Add("IET", Functions.IET); Program.opcodes.Add("INE", Functions.INE); Program.opcodes.Add("DGT", Functions.DGT); Program.opcodes.Add("DLT", Functions.DLT); Program.opcodes.Add("DET", Functions.DET); Program.opcodes.Add("DNE", Functions.DNE); Program.opcodes.Add("MRF", Functions.MRF); Console.WriteLine("INSTRUCTION SET LOADED"); Console.WriteLine("Starting IRCBot"); ircC = new IrcConnection("irc.esper.net", "CPUBot"); ircC.IrcEvents.DisconnectEvent += () => { System.Threading.Thread.Sleep(1000); ircC.Connect(); }; ircC.IrcEvents.ChannelMessageEvent += (channel, user, message) => { Console.WriteLine(channel + " <" + user + "> " + message); ProcessMessage(user, channel, message); }; ircC.IrcEvents.PrivateMessageEvent += (user, message) => { Console.WriteLine("<" + user + "> " + message); ProcessMessage(user, user, message); }; //do bot joins and shit ircC.Connect(); Console.WriteLine("Bot Started"); System.Threading.Thread.Sleep(10000); ircC.IrcIO.JoinChannel("#FoxBotTest"); ircC.IrcIO.JoinChannel("#bottorture"); //ircC.IrcIO.JoinChannel("#kspmodders"); Console.WriteLine(ircC.Connected); }
protected override bool ParseInternal(IrcConnection aConnection, Bot aBot, string aMessage) { string[] regexes = { Helper.Magicstring + " Die Nummer der Datei ist ung.ltig", Helper.Magicstring + " Invalid Pack Number, Try Again" }; var match = Helper.Match(aMessage, regexes); if (match.Success) { Packet tPack = aBot.OldestActivePacket(); if (tPack != null) { // remove all packets with ids beeing greater than the current one because they MUST be missing, too var tPackets = from packet in aBot.Packets where packet.Id >= tPack.Id select packet; foreach (Packet pack in tPackets) { pack.Enabled = false; aBot.RemovePacket(pack); } } Log.Error("Parse() invalid packetnumber from " + aBot); UpdateBot(aBot, aMessage); return true; } return false; }
public void ConnectWithNickServAndServerPasswordTest() { IrcConfig ircConfig = new IrcConfig { Nick = nick, NickServPassword = nickServPass, QuitMessage = quitMessage, RealName = realName, ServerPassword = serverPassword, UserName = userName, RateLimit = 0 }; ircConfig.Channels.Add(channel1); ircConfig.Channels.Add(channel2); using (IrcConnection connection = new IrcConnection(ircConfig, this.parsingQueue.Object, this.mac.Object)) { // We need to send the passwords too! this.mac.Setup( m => m.WriteLine("PRIVMSG NickServ :IDENTIFY {0}", nickServPass) ); this.mac.Setup( m => m.WriteLine("PASS {0}", serverPassword) ); this.DoConnect(connection); this.DoDisconnect(connection); } this.mac.VerifyAll(); }
public override void action(IrcConnection connection, string channel) { IList <Character> characters = IrcBot.mySession.CreateCriteria <Character>().List <Character>(); foreach (Character character in characters) { //Get their skillQueue, and determine if time remaining is less than 24 hours. SkillQueue skillQueue = null; try { skillQueue = EveApi.GetSkillQueue(character.api.apiUserId, character.apiCharacterId, character.api.apiKeyId); } catch (FormatException) { continue; } catch (Exception) { continue; } if (skillQueue == null) { continue; } DateTime tomorrow = DateTime.Now + new TimeSpan(24, 0, 0);//24 hours if (skillQueue.SkillList.Length > 0) { if (skillQueue.SkillList.Last().TrainingEndTimeLocal < tomorrow) // If the skill finishes before tomorrow. { connection.privmsg(channel, "Character " + character.characterName + " has less than 24 hours remaining in his skill queue"); } } } }
protected override bool ParseInternal(IrcConnection aConnection, Bot aBot, string aMessage) { string[] regexes = { "Punish-ignore activated for .* \\(.*\\) (?<time_m>[0-9]*) minutes", "Auto-ignore activated for .* lasting (?<time_m>[0-9]*)m(?<time_s>[0-9]*)s\\. Further messages will increase duration\\.", "Zur Strafe wirst du .* \\(.*\\) f.r (?<time_m>[0-9]*) Minuten ignoriert(.|)", "Auto-ignore activated for .* \\(.*\\)" }; var match = Helper.Match(aMessage, regexes); if (match.Success) { if (aBot.State == Bot.States.Waiting) { aBot.State = Bot.States.Idle; } int valueInt = 0; if (int.TryParse(match.Groups["time_m"].ToString(), out valueInt)) { int time = valueInt * 60 + 1; if (int.TryParse(match.Groups["time_s"].ToString(), out valueInt)) { time += valueInt; } FireQueueRequestFromBot(this, new EventArgs<Model.Domain.Server, Bot, int>(aConnection.Server, aBot, time * 1000)); } UpdateBot(aBot, aMessage); return true; } return false; }
public async Task TestBadSslConnection() { try { Task t = Task.Delay(5000, stoken.Token); IrcConnection c = new IrcConnection(); bool caughtError = false; c.ConnectionError += (sender, error) => { Debug.WriteLine(error.ToString()); Assert.IsTrue(error.Exception is IOException); var se = error.Exception as IOException; caughtError = true; stoken.Cancel(); }; await c.ConnectAsync("irc.cobaltapp.net", 6667, true, "Test", "Test", "Test", false); Assert.IsFalse(c.State == IrcConnectionState.Disconnected); await t; Assert.IsTrue(caughtError); } catch (TaskCanceledException e) { } }
public async Task TestBadConnection() { try { Task t = Task.Delay(5000, stoken.Token); IrcConnection c = new IrcConnection(); bool caughtError = false; c.ConnectionError += (sender, error) => { Debug.WriteLine(error.ToString()); Assert.IsTrue(error.Exception is SocketException); SocketException se = error.Exception as SocketException; Assert.IsTrue(se.SocketErrorCode == SocketError.ConnectionRefused); caughtError = true; stoken.Cancel(); }; await c.ConnectAsync("irc.memers.co", 6668, false, "Test", "Test", "Test", false); Assert.IsFalse(c.State == IrcConnectionState.Disconnected); await t; Assert.IsTrue(caughtError); } catch (TaskCanceledException e) { } }
public ResponseEventArgs(IrcConnection connection, Response response) { Verify.NotNull(connection, "connection"); Verify.NotNull(response, "response"); Connection = connection; Response = response; }
public static void Initialise() { InitialisePlugins(config); LumbricusContext.Initialise(config); logger.Debug("Initialising server connections"); var servers = Server.Fetch(); foreach (Server server in servers) { IrcConnection conn = new IrcConnection(server, config); connections.Add(conn); } foreach (IrcConnection conn in connections) { var channels = Channel.Fetch(conn.Server); conn.Server.SetChannels(channels.ToList()); } logger.Debug("Starting connections"); foreach (IrcConnection conn in connections) { Thread t = new Thread(() => RunThread(conn)); t.Start(); threads.Add(t); } }
protected override bool ParseInternal(IrcConnection aConnection, Bot aBot, string aMessage) { string[] regexes = { Helper.Magicstring + " The Owner Has Requested That No New Connections Are Made In The Next (?<time>[0-9]+) Minute(s|)" }; var match = Helper.Match(aMessage, regexes); if (match.Success) { if (aBot.State == Bot.States.Waiting) { aBot.State = Bot.States.Idle; } int valueInt = 0; if (int.TryParse(match.Groups["time"].ToString(), out valueInt)) { FireQueueRequestFromBot(this, new EventArgs<Model.Domain.Server, Bot, int>(aConnection.Server, aBot, (valueInt * 60 + 1) * 1000)); } UpdateBot(aBot, aMessage); return true; } return false; }
public override void RegisterPlugin(IrcConnection conn) { conn.RegisterCommand("!setmugshot", new Commands.SetMugshotCommand(conn)); conn.RegisterCommand("!clearmugshot", new Commands.ClearMugshotCommand(conn)); MugshotsContext.Initialise(conn.Config); }
protected override bool ParseInternal(IrcConnection aConnection, Bot aBot, string aMessage) { string[] regexes = { Helper.Magicstring + " You have a DCC pending, Set your client to receive the transfer\\. ((Type .*|Send XDCC CANCEL) to abort the transfer\\. |)\\((?<time>[0-9]+) seconds remaining until timeout\\)", Helper.Magicstring + " Du hast eine .bertragung schwebend, Du mu.t den Download jetzt annehmen\\. ((Schreibe .*|Sende XDCC CANCEL) an den Bot um die .bertragung abzubrechen\\. |)\\((?<time>[0-9]+) Sekunden bis zum Abbruch\\)" }; var match = Helper.Match(aMessage, regexes); if (match.Success) { int valueInt = 0; if (int.TryParse(match.Groups["time"].ToString(), out valueInt)) { if (valueInt == 30 && aBot.State != Bot.States.Active) { aBot.State = Bot.States.Idle; } FireQueueRequestFromBot(this, new EventArgs<Model.Domain.Server, Bot, int>(aConnection.Server, aBot, (valueInt + 2) * 1000)); } UpdateBot(aBot, aMessage); return true; } return false; }
private void DoDisconnect(IrcConnection connection) { this.SetupDisconnection(); connection.Disconnect(); Assert.IsFalse(connection.IsConnected); Assert.IsFalse(this.mac.Object.IsConnected); }
protected override bool ParseInternal(IrcConnection aConnection, Bot aBot, string aMessage) { string[] regexes = { "Denied, You already have ([0-9]+) item(s|) queued, Try Again Later", Helper.Magicstring + " All Slots Full, Denied, You already have that item queued\\.", "You are already receiving or are queued for the maximum number of packs .*", "Du hast max\\. ([0-9]+) transfer auf einmal, Du bist jetzt in der Warteschlange f.r Datei .*", "Es laufen bereits genug .bertragungen, abgewiesen, Du hast diese Datei bereits in der Warteschlange\\." }; var match = Helper.Match(aMessage, regexes); if (match.Success) { if (aBot.State == Bot.States.Idle) { aBot.State = Bot.States.Waiting; } else if (aBot.State == Bot.States.Waiting) { // if there is no active packets lets remove us from the queue if (aBot.OldestActivePacket() == null) { FireUnRequestFromBot(this, new EventArgs<Model.Domain.Server, Bot>(aConnection.Server, aBot)); } } UpdateBot(aBot, aMessage); return true; } return false; }
public virtual IIrcConnection Create(string hostname, bool useSsl = false, int port = 6667, string password = null) { _logger.Debug("Connecing to {0}:{1} using ssl: {2}", hostname, port, useSsl); IrcConnection connection = new IrcConnection(LoggerFactory, ConnectionFactory, hostname, useSsl, port, password); return(connection); }
public override void RegisterPlugin(IrcConnection conn) { conn.RegisterCommand("!setinfo", new Commands.SetInfoCommand(conn)); conn.RegisterCommand("!clearinfo", new Commands.ClearInfoCommand(conn)); InfoContext.Initialise(conn.Config); }
protected override bool ParseInternal(IrcConnection aConnection, Bot aBot, string aMessage) { string[] regexes = { Helper.Magicstring + " ((Bandwidth Usage|Bandbreite) " + Helper.Magicstring + "|)\\s*(Current|Derzeit): (?<speed_cur>[0-9.]*)(?<speed_cur_end>(K|)(i|)B)(\\/s|s)(,|)(.*Record: (?<speed_max>[0-9.]*)(?<speed_max_end>(K|)(i|))B(\\/s|s)|)" }; var match = Helper.Match(aMessage, regexes); if (match.Success) { string speedCurEnd = match.Groups["speed_cur_end"].ToString().ToLower(); string speedMaxEnd = match.Groups["speed_max_end"].ToString().ToLower(); string speedCur = match.Groups["speed_cur"].ToString(); string speedMax = match.Groups["speed_max"].ToString(); if (Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator == ",") { speedCur = speedCur.Replace('.', ','); speedMax = speedMax.Replace('.', ','); } double valueDouble; if (double.TryParse(speedCur, out valueDouble)) { aBot.InfoSpeedCurrent = speedCurEnd.StartsWith("k") ? (Int64) (valueDouble * 1024) : (Int64) valueDouble; } if (double.TryParse(speedMax, out valueDouble)) { aBot.InfoSpeedMax = speedMaxEnd.StartsWith("k") ? (Int64) (valueDouble * 1024) : (Int64) valueDouble; } UpdateBot(aBot); return true; } return false; }
public void DoTrackKickPlugin(IrcConnection conn, IrcLine line) { Regex r = new Regex(@"^(?<channel>#[^ ]+) (?<idiot>.*)$", RegexOptions.ExplicitCapture); Match m = r.Match(line.IrcCommandArgsRaw); if (m.Success) { string channelName = m.Groups["channel"].Value; string idiot = m.Groups["idiot"].Value; Nick banner = conn.Server.ConnectedNicks.FirstOrDefault(x => x.Name == line.Nick.ToLower()); Nick idiotNick = conn.Server.ConnectedNicks.FirstOrDefault(x => x.Name == idiot.ToLower()); Channel channel = conn.Server.ConnectedChannels.FirstOrDefault(x => x.Name == channelName.ToLower()); Ban ban = Ban.Fetch(channel, idiotNick); if (ban != null) { if (ban.BannerAccount == null && banner.Account != null) { ban.BannerAccount = banner.Account; } ban.Nick = idiotNick; if (idiotNick.Account != null) { ban.Account = idiotNick.Account; } ban.Channel = channel; ban.BanMessage = line.Trail; LumbricusContext.db.SaveChanges(); } } }
protected override bool ParseInternal(IrcConnection aConnection, Bot aBot, string aMessage) { string[] regexes = { Helper.Magicstring + " All Slots Full, Main queue of size (?<queue_total>[0-9]+) is Full, Try Again Later", Helper.Magicstring + " Es laufen bereits genug .bertragungen, abgewiesen, die Warteschlange ist voll, max\\. (?<queue_total>[0-9]+) Dateien, Versuche es sp.ter nochmal" }; var match = Helper.Match(aMessage, regexes); if (match.Success) { if (aBot.State == Bot.States.Waiting) { aBot.State = Bot.States.Idle; } int valueInt = 0; aBot.InfoSlotCurrent = 0; aBot.InfoQueueCurrent = 0; if (int.TryParse(match.Groups["queue_total"].ToString(), out valueInt)) { aBot.InfoQueueTotal = valueInt; } FireQueueRequestFromBot(this, new EventArgs<Model.Domain.Server, Bot, int>(aConnection.Server, aBot, Settings.Default.BotWaitTime)); UpdateBot(aBot, aMessage); return true; } return false; }
public static void RunThread(IrcConnection conn) { try { conn.Run(); } catch (Exception e) { logger.Error(e); } }
public void IrcClient_Mod_Say_ThrowsNoException_WhenNullChannel() { var readConnection = new IrcConnection(); var writeConnection = new IrcConnection(); var client = new IrcClient(readConnection, writeConnection); client.Say("Test Message", null, true); }
public void IrcClient_StandardUser_Say_ThrowsNoException_WhenNullMessage() { var readConnection = new IrcConnection(); var writeConnection = new IrcConnection(); var client = new IrcClient(readConnection, writeConnection); client.Say(null, "TestChannel", false); }
protected override bool ParseInternal(IrcConnection aConnection, string aUser, string aMessage) { string[] tDataList = aMessage.Split(' '); if (tDataList[0] == "SEND") { if (!Helper.Match(tDataList[1], ".*\\.txt$").Success) { Log.Error("Parse() " + aUser + " send no text file: " + tDataList[1]); return false; } IPAddress ip = null; try { ip = TryCalculateIp(tDataList[2]); } catch (Exception ex) { Log.Fatal("Parse() " + aUser + " - can not parse ip from string: " + aMessage, ex); return false; } Int64 size = 0; try { size = Int64.Parse(tDataList[4]); } catch (Exception ex) { Log.Fatal("Parse() " + aUser + " - can not parse size from string: " + aMessage, ex); return false; } int port = 0; try { port = int.Parse(tDataList[3]); } catch (Exception ex) { Log.Fatal("Parse() " + aUser + " - can not parse port from string: " + aMessage, ex); return false; } // we cant connect to port <= 0 if (port <= 0) { Log.Error("Parse() " + aUser + " submitted wrong port: " + port); return false; } else { FireDownloadXdccList(this, new EventArgs<Server, string, Int64, IPAddress, int>(aConnection.Server, aUser, size, ip, port)); return true; } } return false; }
private void HandleLeaveCommand(IrcConnection connection, Response response) { string channelName = response.Arguments[0]; string username = response.HostMask.Username; string message = response.Arguments[2]; Channel channel = GetChannel(channelName); var user = GetUser(username); ChatReceived?.Invoke(this, new ChatEventArgs(channel, user, message)); }
public void IrcClient_Constructor_SingleConnection_True() { var readConnection = new IrcConnection(); var client = new IrcClient(readConnection, readConnection); Assert.IsNotNull(client.ReadConnection); Assert.IsNotNull(client.WriteConnection); Assert.AreEqual(client.ReadConnection, client.WriteConnection); }
private void DoConnect(IrcConnection connection) { this.SetupConnection(); connection.Init(); connection.Connect(); Assert.IsTrue(connection.IsConnected); Assert.IsTrue(this.mac.Object.IsConnected); }
public void IrcClient_Mod_Say_ReturnsTrue_WhenMessageQueueNotFull() { var readConnection = new IrcConnection(); var writeConnection = new IrcConnection(); var client = new IrcClient(readConnection, writeConnection); var result = client.Say("Test Message", null, true); Assert.AreEqual <bool>(true, result); }
public void IrcClient_StandardUser_Say_ReturnsTrue_WhenMessageStartsWithDotColor() { var readConnection = new IrcConnection(); var writeConnection = new IrcConnection(); var client = new IrcClient(readConnection, writeConnection); var result = client.Say(".color Test Message", null, false); Assert.AreEqual <bool>(true, result); }
public void ConnectWithoutInitTest() { using (IrcConnection connection = new IrcConnection(this.defaultConfig, this.parsingQueue.Object, this.mac.Object)) { // Do not call connection.Init(). Assert.Throws <InvalidOperationException>(() => connection.Connect()); Assert.DoesNotThrow(() => connection.Disconnect()); // <- Should be a no-op since we are not connected. } }
public BasicWhisperConnection(TwitchConnector connector, IrcConnection connection, MessageBus bus) { Verify.NotNull(connector, "connector"); Verify.NotNull(connection, "connection"); Verify.NotNull(bus, "bus"); Connector = connector; Connection = connection; Connection.ResponseReceived += Connection_ResponseReceived; Bus = bus; }
public async void StartAccepting() { // Establish the local endpoint for the socket. var localEndPoint = new IPEndPoint(IPAddress.Any, ((IPEndPoint)this.LocalEndpoint).Port); // Create a TCP/IP socket. var listener = new IrcListener(this.server, localEndPoint); // Bind the socket to the local endpoint and listen for incoming connections. try { listener.Start(100); while (true) { // Start an asynchronous socket to listen for connections. var handler = await listener.AcceptTcpClientAsync(); // Create the state object. IrcConnection ircConnection; if (this.PortType == PortClass.ClearText || this.PortType == PortClass.ExplicitTLS) { var stream = handler.GetStream(); ircConnection = new IrcConnection(_Store, this.server, handler, stream, listener); } else { var stream = handler.GetStream(); var sslStream = new SslStream(stream); try { await sslStream.AuthenticateAsServerAsync(this.server.ServerAuthenticationCertificate); } catch (IOException ioe) { _Logger.Error("I/O Exception attempting to perform TLS handshake", ioe); return; } ircConnection = new IrcConnection(_Store, this.server, handler, sslStream, listener, true); } this.server.AddConnection(ircConnection); ircConnection.Process(); } } catch (Exception ex) { _Logger.Error("Exception when trying to accept connection from listener", ex); } }
public static void IrcConnectionList() { IrcConnection irc = new IrcConnection(); irc.OnReadLine += new ReadLineEventHandler(IrcConnectionListCallback); irc.Connect(SERVER, PORT); irc.WriteLine(Rfc2812.Nick(NICK), Priority.Critical); irc.WriteLine(Rfc2812.User(NICK, 0, REALNAME), Priority.Critical); irc.WriteLine(Rfc2812.List(CHANNEL)); irc.Listen(); }
// ---------------- Test Helpers ---------------- /// <summary> /// This test tests issue that caused issue #29. /// If we catch an Exception we weren't expecting, the reader thread would /// blow up and consistently throw exceptions. /// /// Now if we get any Exception, we gracefully exit the reader thread and wait /// for the watchdog to reconnect us. This test case simply tests that the /// reader thread terminates. /// </summary> private void DoReaderThreadFailureTest <T>(T e) where T : Exception { const string line1 = "Line 1"; this.mac.SetupSequence( m => m.ReadLine() ) .Returns(line1) .Throws(e); StringBuilder messages = new StringBuilder(); using (ManualResetEvent readerThreadExitedEvent = new ManualResetEvent(false)) { using (IrcConnection connection = new IrcConnection(this.defaultConfig, this.parsingQueue.Object, this.mac.Object)) { void threadExitedAction() { readerThreadExitedEvent.Set(); } void onReadLineAction(string s) { lock ( messages ) { messages.AppendLine(s); } } try { connection.OnReaderThreadExit += threadExitedAction; connection.ReadEvent += onReadLineAction; this.DoConnect(connection); Assert.IsTrue(readerThreadExitedEvent.WaitOne(5000)); this.DoDisconnect(connection); } finally { connection.OnReaderThreadExit -= threadExitedAction; connection.ReadEvent -= onReadLineAction; } } } // Ensure our line gets called *somewhere*. bool success = Regex.IsMatch(messages.ToString(), @"\s*" + line1 + @"\s*"); Assert.IsTrue(success, "Expected: " + line1 + ", actual: " + messages.ToString()); this.mac.VerifyAll(); }
private void SendPong(IrcConnection connection, HostMask hostMask) { if (hostMask == null) { connection.SendCommand(PingReplyCommand); } else { connection.SendCommand($"{PingReplyCommand} {hostMask.Hostname}"); } }
public void DoubleConnectTest() { using (IrcConnection connection = new IrcConnection(this.defaultConfig, this.parsingQueue.Object, this.mac.Object)) { this.DoConnect(connection); Assert.Throws <InvalidOperationException>(() => connection.Connect()); this.DoDisconnect(connection); } }
protected override bool ParseInternal(IrcConnection aConnection, Bot aBot, string aMessage) { string[] regexes = { "(" + Helper.Magicstring + " All Slots Full, |)Added you to the main queue (for pack ([0-9]+) \\(\".*\"\\) |).*in positi(o|0)n (?<queue_cur>[0-9]+)\\. To Remove you(r|)self at a later time .*", "Queueing you for pack [0-9]+ \\(.*\\) in slot (?<queue_cur>[0-9]+)/(?<queue_total>[0-9]+)\\. To remove you(r|)self from the queue, type: .*\\. To check your position in the queue, type: .*\\. Estimated time remaining in queue: (?<queue_d>[0-9]+) days, (?<queue_h>[0-9]+) hours, (?<queue_m>[0-9]+) minutes", "(" + Helper.Magicstring + " |)Es laufen bereits genug .bertragungen, Du bist jetzt in der Warteschlange f.r Datei [0-9]+ \\(.*\\) in Position (?<queue_cur>[0-9]+)\\. Wenn Du sp.ter Abbrechen willst schreibe .*" }; var match = Helper.Match(aMessage, regexes); if (match.Success) { if (aBot.State == Bot.States.Idle) { aBot.State = Bot.States.Waiting; } int valueInt = 0; aBot.InfoSlotCurrent = 0; if (int.TryParse(match.Groups["queue_cur"].ToString(), out valueInt)) { aBot.QueuePosition = valueInt; aBot.InfoQueueCurrent = aBot.QueuePosition; } if (int.TryParse(match.Groups["queue_total"].ToString(), out valueInt)) { aBot.InfoQueueTotal = valueInt; } else if (aBot.InfoQueueTotal < aBot.InfoQueueCurrent) { aBot.InfoQueueTotal = aBot.InfoQueueCurrent; } int time = 0; if (int.TryParse(match.Groups["queue_m"].ToString(), out valueInt)) { time += valueInt * 60; } if (int.TryParse(match.Groups["queue_h"].ToString(), out valueInt)) { time += valueInt * 60 * 60; } if (int.TryParse(match.Groups["queue_d"].ToString(), out valueInt)) { time += valueInt * 60 * 60 * 24; } aBot.QueueTime = time; UpdateBot(aBot, aMessage); return true; } return false; }
internal void RemoveConnection([NotNull] IrcConnection ircConnection) { this.connections.Remove(ircConnection); if (ircConnection.Identity == null) { Logger.VerboseFormat("Disconnection from {0}:{1}", ircConnection.RemoteAddress, ircConnection.RemotePort, ircConnection.LocalAddress, ircConnection.LocalPort); } else { Logger.VerboseFormat("Disconnection from {0}:{1} ({2})", ircConnection.RemoteAddress, ircConnection.RemotePort, ircConnection.LocalAddress, ircConnection.LocalPort, ircConnection.Identity.Username); } }
public IrcHandler() { MessageSplitter = new MessageSplitter(); ChatConnection = new IrcConnection(); BackgroundWorker = new BackgroundWorker(); BackgroundWorker.WorkerReportsProgress = true; BackgroundWorker.WorkerSupportsCancellation = true; BackgroundWorker.DoWork += new DoWorkEventHandler(ChatConnection.GetMessages); BackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(ReceiveMessage); }
IEnumerable <IrcForm> FormsWithUser(IrcConnection connection, string user) { foreach (var entry in forms) { if (entry.Key.StartsWith(connection.Guid.ToString())) { if (entry.Value.ContainsUser(user)) { yield return(entry.Value); } } } }
public IrcConnection GetConnection(string host, int port) { if (this.isDisposed) { throw new InvalidOperationException($"{nameof(IrcClient)} already disposed"); } var connection = new IrcConnection(host, port); this.connections.Add(connection); this.initializer.Invoke(connection); return(connection); }
public static void HandleClearInfo(IrcNick nick, string args, IrcConnection conn) { try { IrcSeen seen = IrcSeen.Fetch(nick); DateTime checkTime = DateTime.Now; checkTime.AddDays(-7); if (seen.firstSeenAt == DateTime.MinValue || seen.firstSeenAt > checkTime) { conn.SendPrivmsg(nick.nick, String.Format("Sorry, {0}, but you aren't allowed to use the mugshots functions yet. :(", nick.displayNick)); return; } using (MySqlCommand cmd = DataConnection.CreateDbCommand()) { cmd.CommandText = "SELECT * FROM `info` WHERE (`account_id` = @accountId AND `is_deleted` = 0)"; cmd.Parameters.AddWithValue("@accountId", nick.account.id); using (IDataReader reader = cmd.ExecuteReader()) { if (!reader.Read()) { reader.Dispose(); cmd.Dispose(); conn.SendPrivmsg(nick.nick, "You don't have any info in the database to clear! :o"); } else { reader.Dispose(); cmd.Dispose(); using (MySqlCommand cmd2 = DataConnection.CreateDbCommand()) { cmd2.CommandText = "UPDATE `info` SET `is_deleted` = 1 WHERE `account_id` = @accountId"; cmd2.Parameters.AddWithValue("@accountId", nick.account.id); cmd2.ExecuteNonQuery(); conn.SendPrivmsg(nick.nick, "Your info has been cleared. :("); } using (MySqlCommand cmd3 = DataConnection.CreateDbCommand()) { cmd3.CommandText = "UPDATE `accounts` SET `nick_id` = @nickId WHERE `id` = @accountId"; cmd3.Parameters.AddWithValue("@nickId", nick.id); cmd3.Parameters.AddWithValue("@accountId", nick.account.id); cmd3.ExecuteNonQuery(); } } } } } catch (Exception e) { Logger.Log(e); conn.SendPrivmsg(nick.nick, "Oof… I banged my knee and it don't half hurt, I can't do that right now. :("); } }
public void IrcClient_Mod_Say_ReturnsFalse_OnceMessageQueueFull() { var readConnection = new IrcConnection(); var writeConnection = new IrcConnection(); var client = new IrcClient(readConnection, writeConnection); Thread.Sleep(QueueIntervalInSeconds * 1000); // Stupid private static variables forced my hand. I hate this for the record, but it is required for the moment. for (var i = 0; i < ModMessageQueueLimit + 1; i++) { var result = client.Say("Test Message", null, true); Assert.AreEqual <bool>(i < ModMessageQueueLimit, result, $"The variable 'i' was {i}."); } Thread.Sleep(QueueIntervalInSeconds * 1000); // Stupid private static variables forced my hand. I hate this for the record, but it is required for the moment. }
T CreateOrFindForm <T>(IrcConnection connection, string formName) where T : IrcForm, new() { string key = string.Format("{0}.{1}", connection.Guid, formName); if (!forms.ContainsKey(key)) { T form = new T(); form.MdiParent = this; form.Show(); forms.Add(key, form); form.Connection = connection; } return((T)forms[key]); }
public BasicChannel(TwitchConnector connector, IrcConnection connection, MessageBus bus, string channelName) { Verify.NotNull(connector, "connector"); Verify.NotNull(connection, "connection"); Verify.NotNull(bus, "bus"); Verify.ChannelName(channelName, "channelName"); ActiveUsers = new ReadOnlyCollection<User>(_activeUsers); Connector = connector; Connector.Decoder.ChatReceived += Decoder_ChatReceived; Connector.Decoder.UserJoinedChannel += Decoder_UserJoinedChannel; Connector.Decoder.UserLefthannel += Decoder_UserLefthannel; Connection = connection; Name = channelName; Bus = bus; }
public void DoAutoRejoinPlugin(IrcConnection conn, IrcLine line) { IrcCommand ircCommand = (IrcCommand)Enum.Parse(typeof(IrcCommand), line.IrcCommand); if (ircCommand == IrcCommand.KICK && line.IrcCommandArgs.GetValue(1).ToString() == conn.Server.BotNick) { logger.Info("{0} kicked me from {1}, so rejoining it!", line.Nick, line.IrcCommandArgs.GetValue(0)); conn.Send(string.Format("JOIN {0}", line.IrcCommandArgs.GetValue(0))); } else if (ircCommand == IrcCommand.PART && line.Nick == conn.Server.BotNick) { logger.Info("I parted from {0}, so rejoining it!", line.IrcCommandArgs.GetValue(0)); conn.Send(string.Format("JOIN {0}", line.IrcCommandArgs.GetValue(0))); } }
protected override bool ParseInternal(IrcConnection aConnection, Bot aBot, string aMessage) { string[] regexes = { Helper.Magicstring + " ([0-9]*) (pack(s|)|Pa(c|)ket(e|)|Fil[e]+s) " + Helper.Magicstring + "\\s*(?<slot_cur>[0-9]*) (of|von) (?<slot_total>[0-9]*) (slot(s|)|Pl(a|�|.)tz(e|)) (open|opened|free|frei|in use|offen)(, ((Queue|Warteschlange): (?<queue_cur>[0-9]*)(\\/| of )(?<queue_total>[0-9]*),|).*(Record( [a-zA-Z]+|): (?<record>[0-9.]*)(K|)B\\/s|)|)" }; var match = Helper.Match(aMessage, regexes); if (match.Success) { int valueInt = 0; if (int.TryParse(match.Groups["slot_cur"].ToString(), out valueInt)) { aBot.InfoSlotCurrent = valueInt; } if (int.TryParse(match.Groups["slot_total"].ToString(), out valueInt)) { aBot.InfoSlotTotal = valueInt; } if (int.TryParse(match.Groups["queue_cur"].ToString(), out valueInt)) { aBot.InfoQueueCurrent = valueInt; } if (int.TryParse(match.Groups["queue_total"].ToString(), out valueInt)) { aBot.InfoQueueTotal = valueInt; } if (aBot.InfoSlotCurrent > aBot.InfoSlotTotal) { aBot.InfoSlotTotal = aBot.InfoSlotCurrent; } if (aBot.InfoQueueCurrent > aBot.InfoQueueTotal) { aBot.InfoQueueTotal = aBot.InfoQueueCurrent; } // uhm, there is a free slot and we are still waiting? if (aBot.InfoSlotCurrent > 0 && aBot.State == Bot.States.Waiting) { aBot.State = Bot.States.Idle; FireQueueRequestFromBot(this, new EventArgs<Model.Domain.Server, Bot, int>(aConnection.Server, aBot, 0)); } UpdateBot(aBot); return true; } return false; }
protected override bool ParseInternal(IrcConnection aConnection, Bot aBot, string aMessage) { string[] regexes = { "Queued ([0-9]+)h([0-9]+)m for .*, in position (?<queue_cur>[0-9]+) of (?<queue_total>[0-9]+). (?<queue_h>[0-9]+)h(?<queue_m>[0-9]+)m or .* remaining\\.", "In der Warteschlange seit ([0-9]+)h([0-9]+)m f.r .*, in Position (?<queue_cur>[0-9]+) von (?<queue_total>[0-9]+). Ungef.hr (?<queue_h>[0-9]+)h(?<queue_m>[0-9]+)m oder .*" }; var match = Helper.Match(aMessage, regexes); if (match.Success) { if (aBot.State == Bot.States.Idle) { aBot.State = Bot.States.Waiting; } int valueInt = 0; aBot.InfoSlotCurrent = 0; if (int.TryParse(match.Groups["queue_cur"].ToString(), out valueInt)) { aBot.QueuePosition = valueInt; } if (int.TryParse(match.Groups["queue_total"].ToString(), out valueInt)) { aBot.InfoQueueTotal = valueInt; } else if (aBot.InfoQueueTotal < aBot.QueuePosition) { aBot.InfoQueueTotal = aBot.QueuePosition; } int time = 0; if (int.TryParse(match.Groups["queue_m"].ToString(), out valueInt)) { time += valueInt * 60; } if (int.TryParse(match.Groups["queue_h"].ToString(), out valueInt)) { time += valueInt * 60 * 60; } aBot.QueueTime = time; UpdateBot(aBot, aMessage); return true; } return false; }
protected override bool ParseInternal(IrcConnection aConnection, Bot aBot, string aMessage) { string[] regexes = { Helper.Magicstring + " You can only have ([0-9]+) transfer(s|) at a time,.*" }; var match = Helper.Match(aMessage, regexes); if (match.Success) { if (aBot.State == Bot.States.Idle) { aBot.State = Bot.States.Waiting; } UpdateBot(aBot, aMessage); return true; } return false; }
protected override bool ParseInternal(IrcConnection aConnection, Bot aBot, string aMessage) { string[] regexes = { @".*\s+JOIN (?<channel>[^\s]+).*" }; var match = Helper.Match(aMessage, regexes); if (match.Success) { string channel = match.Groups["channel"].ToString(); if (!channel.StartsWith("#")) { channel = "#" + channel; } FireJoinChannel(this, new EventArgs<Model.Domain.Server, string>(aConnection.Server, channel)); return true; } return false; }
protected override bool ParseInternal(IrcConnection aConnection, Bot aBot, string aMessage) { string[] regexes = { Helper.Magicstring + ".* You already have that item queued.*" }; var match = Helper.Match(aMessage, regexes); if (match.Success) { if (aBot.State == Bot.States.Idle) { aBot.State = Bot.States.Waiting; } UpdateBot(aBot, aMessage); return true; } return false; }
protected override bool ParseInternal(IrcConnection aConnection, Bot aBot, string aMessage) { string[] regexes = { Helper.Magicstring + " Removed From Queue: .*" }; var match = Helper.Match(aMessage, regexes); if (match.Success) { if (aBot.State == Bot.States.Waiting) { aBot.State = Bot.States.Idle; } FireQueueRequestFromBot(this, new EventArgs<Model.Domain.Server, Bot, int>(aConnection.Server, aBot, Settings.Default.CommandWaitTime)); UpdateBot(aBot, aMessage); return true; } return false; }
protected override bool ParseInternal(IrcConnection aConnection, Bot aBot, string aMessage) { string[] regexes = { Helper.Magicstring + " Sending You (Your Queued |)Pack .*", Helper.Magicstring + " Sende dir jetzt die Datei .*" }; var match = Helper.Match(aMessage, regexes); if (match.Success) { if (aBot.State == Bot.States.Waiting) { aBot.State = Bot.States.Idle; } UpdateBot(aBot, aMessage); return true; } return false; }
protected override bool ParseInternal(IrcConnection aConnection, Bot aBot, string aMessage) { string[] regexes = { Helper.Magicstring + " XDCC SEND denied, (?<info>.*)" }; var match = Helper.Match(aMessage, regexes); if (match.Success) { string info = match.Groups["info"].ToString().ToLower(); if (info.StartsWith("you must be on a known channel to request a pack")) { FireJoinChannelsFromBot(this, new EventArgs<Model.Domain.Server, Bot>(aConnection.Server, aBot)); FireQueueRequestFromBot(this, new EventArgs<Model.Domain.Server, Bot, int>(aConnection.Server, aBot, Settings.Default.CommandWaitTime)); } else if (info.StartsWith("i don't send transfers to")) { foreach (Packet tPacket in aBot.Packets) { if (tPacket.Enabled) { tPacket.Enabled = false; tPacket.Commit(); } } } else { if (aBot.State == Bot.States.Waiting) { aBot.State = Bot.States.Idle; } FireQueueRequestFromBot(this, new EventArgs<Model.Domain.Server, Bot, int>(aConnection.Server, aBot, Settings.Default.CommandWaitTime)); Log.Error("Parse() XDCC denied from " + aBot + ": " + info); } UpdateBot(aBot, aMessage); return true; } return false; }
protected override bool ParseInternal(IrcConnection aConnection, Bot aBot, string aMessage) { string[] regexes = { Helper.Magicstring + " (Closing Connection|Transfer Completed)(?<reason>.*)", Helper.Magicstring + " (Schlie.e Verbindung)(?<reason>.*)" }; var match = Helper.Match(aMessage, regexes); if (match.Success) { if (aBot.State != Bot.States.Active) { aBot.State = Bot.States.Idle; } else { // kill that connection if the bot sends a close message , but our real bot // connection is still alive and hangs for some crapy reason - maybe because // some admins do some network fu to stop my downloads (happend to me) FireRemoveDownload(this, new EventArgs<Model.Domain.Server, Bot>(aConnection.Server, aBot)); } FireQueueRequestFromBot(this, new EventArgs<Model.Domain.Server, Bot, int>(aConnection.Server, aBot, Settings.Default.CommandWaitTime)); match = Helper.Match(aMessage, @".*\s+JOIN (?<channel>[^\s]+).*"); if (match.Success) { string channel = match.Groups["channel"].ToString(); if (!channel.StartsWith("#")) { channel = "#" + channel; } FireJoinChannel(this, new EventArgs<Model.Domain.Server, string>(aConnection.Server, channel)); } //** Closing Connection: Transfers from [mg]-request|bots are restricted to only MOVIEGODS users! /Part #Beast-xdcc + #elitewarez if you want to download from [MG]-Request|Bot|003 UpdateBot(aBot, aMessage); return true; } return false; }
protected override bool ParseInternal(IrcConnection aConnection, Bot aBot, string aMessage) { string[] regexes = { "(You Don't Appear To Be In A Queue|Removed you from the queue for.*)" }; var match = Helper.Match(aMessage, regexes); if (match.Success) { if (aBot.State == Bot.States.Waiting) { aBot.State = Bot.States.Idle; } aBot.QueuePosition = 0; FireQueueRequestFromBot(this, new EventArgs<Model.Domain.Server, Bot, int>(aConnection.Server, aBot, Settings.Default.CommandWaitTime)); UpdateBot(aBot, aMessage); return true; } return false; }
protected override bool ParseInternal(IrcConnection aConnection, Bot aBot, string aMessage) { string[] regexes = { Helper.Magicstring + " You already requested that pack(.*|)", Helper.Magicstring + ".* You already have that item queued.*", Helper.Magicstring + " Du hast diese Datei bereits angefordert(.*|)" }; var match = Helper.Match(aMessage, regexes); if (match.Success) { if (aBot.State == Bot.States.Idle) { aBot.State = Bot.States.Waiting; } //FireQueueRequestFromBot(this, new EventArgs<Model.Domain.Server, Bot, int>(aConnection.Server, aBot, Settings.Default.BotWaitTime)); UpdateBot(aBot, aMessage); return true; } return false; }
public void Decode(IrcConnection connection, Response response) { Verify.NotNull(connection, "connection"); Verify.NotNull(response, "response"); switch (response.Command) { case PingCommand: HandlePingRequest(connection, response); break; case ChatCommand: HandleChatMessage(connection, response); break; case JoinCommand: HandleJoinCommand(connection, response); break; case LeaveCommand: HandleLeaveCommand(connection, response); break; } }
void ServerConnect(Server aServer) { if (!aServer.Enabled) { _log.Error("ServerConnect(" + aServer + ") is not enabled"); return; } IrcConnection connection = _connections.SingleOrDefault(c => c.Server == aServer); if (connection == null) { connection = new IrcConnection { Server = aServer, Parser = _parser, Scheduler = Scheduler }; _connections.Add(connection); connection.OnDisconnected += ServerDisconnected; connection.OnNotificationAdded += AddNotification; connection.Start(aServer.ToString()); } else { _log.Error("ConnectServer(" + aServer + ") is already in the list"); } }
private void ApplyCredentials(IrcConnection connection) { connection.SendCommandBatch( $"PASS {DefaultCredentials.AuthKey}", $"USER {DefaultCredentials.Username} * *: {DefaultCredentials.Username}", $"NICK {DefaultCredentials.Username}"); connection.SendCommand("CAP REQ :twitch.tv/commands"); connection.SendCommand("CAP REQ :twitch.tv/membership"); connection.SendCommand("CAP END"); }
private void ApplyPingResponder(IrcConnection connection) { new PingResponder(connection); }