Connect() 보호된 메소드

protected Connect ( IrcRegistrationInfo registrationInfo ) : void
registrationInfo IrcRegistrationInfo
리턴 void
예제 #1
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="twitchUsername"></param>
        /// <param name="twitchOAuthToken">
        /// A chat login token which can be generated here: http://www.twitchapps.com/tmi/
        /// </param>
        public void Start(string twitchUsername, string twitchOAuthToken)
        {
            var client = new IrcClient();

            client.Connected += client_Connected;
            client.ChannelListReceived += client_ChannelListReceived;
            client.RawMessageReceived += client_RawMessageReceived;

            client.Connect("irc.twitch.tv", 6667, false, new IrcUserRegistrationInfo() {NickName = twitchUsername, Password = twitchOAuthToken, UserName = twitchUsername, RealName = twitchUsername});
        }
        public ActionResult Irc()
        {
            var api = new AppHarborApi(new AuthInfo { AccessToken = ConfigurationManager.AppSettings["authToken"] });

            var latestBuild = api.GetBuilds(Constants.AppHarborAppName).First();
            var testResults = api.GetTests(Constants.AppHarborAppName, latestBuild.ID);
            List<AppHarbor.Model.Test> allTests = new List<AppHarbor.Model.Test>();

            foreach (var testresult in testResults)
            {
                FillTests(allTests, testresult);
            }

            AutoResetEvent are = new AutoResetEvent(false);
            IrcDotNet.IrcClient client = new IrcDotNet.IrcClient();

            try
            {
                client.Connect("irc.gamesurge.net", false, new IrcUserRegistrationInfo() { NickName = "crymono-build", RealName = "crymono", UserName = "******" });

                client.ClientInfoReceived += (s, e) => are.Set();

                are.WaitOne();

                client.Channels.Join(new string[] { "#crymono" });

                Thread.Sleep(200);
                string msg = latestBuild.Commit.Message.Replace("\n", "").Replace("\r", "");

                client.LocalUser.SendMessage("#crymono", "Build finished, latest commit: " + msg);
                Thread.Sleep(200);

                int numPassedTests = allTests.Count(t => t.Status == "Passed");
                float percentage = (float)numPassedTests / allTests.Count * 100;
                client.LocalUser.SendMessage("#crymono", String.Format("Test results: {0} of {1} passed ({2:0}%) - http://crymono.apphb.com/#!/{3} - AppHB: https://appharbor.com/applications/crymonobuild/builds/{3}/tests",
                    numPassedTests,
                    allTests.Count,
                    percentage,
                    latestBuild.ID
                    ));
                Thread.Sleep(200);

            }
            finally
            {
                if (client != null && client.IsConnected)
                {
                    client.Quit("to the hills!");
                    Thread.Sleep(200);
                    client.Disconnect();
                }
            }

            return Content("OK");
        }
예제 #3
0
파일: RawIrcBot.cs 프로젝트: bremnes/IrcBot
 public void ConnectAndSetup()
 {
     _client = new IrcClient();
     _client.Connect("irc.homelien.no", 6667, false, new IrcUserRegistrationInfo
         {
             NickName = "testL",
             UserName = "******",
             RealName = "LarsBot"
         });
     _client.Connected += ClientOnConnected;
     _client.Disconnected += _client_Disconnected;
     _client.RawMessageReceived += _client_RawMessageReceived;
     _client.Error += ClientOnError;
     _client.ErrorMessageReceived += ClientOnErrorMessageReceived;
 }
예제 #4
0
        public INetwork Connect(INetwork network, IUser user)
        {
            IrcClient ircClient = new IrcClient();
            INetwork connection = this.RegisterNetwork(ircClient, network);

            this.OnNetworkAdded(connection);

            ircClient.Connect(network.Url.Host, network.Url.Port, false, new IrcUserRegistrationInfo()
            {
                NickName = user.Nickname,
                RealName = user.Realname,
                UserName = user.Nickname,
            });

            return network;
        }
예제 #5
0
        public TwitchChat(string accessToken, string channel)
        {
            Client = new IrcClient();
            UserFlags = new Dictionary<string, ChatBadges>();
            UserColors = new Dictionary<string, Color>();
            var twitch = Twitch.Instance;
            Client.Connected += Client_Connected;
            Client.Registered += Client_Registered;
            Channel = channel;

            Client.Connect("irc.twitch.tv", 6667,
                new IrcUserRegistrationInfo()
                {
                    NickName = twitch.ChannelName,
                    Password = $"oauth:{accessToken}"
                });
        }
예제 #6
0
파일: Program.cs 프로젝트: jonbonne/OCTGN
 static void Main(string[] args)
 {
     client = new IrcClient();
     var reg = new IrcUserRegistrationInfo();
     reg.NickName = "botctgn";
     reg.UserName = "******";
     reg.RealName = "botctgn";
     client.Connect("irc.freenode.net",6667,false,reg);
     client.Disconnected += ClientOnDisconnected;
     client.Connected += ClientOnConnected;
     client.ErrorMessageReceived += ClientOnErrorMessageReceived;
     client.MotdReceived += ClientOnMotdReceived;
     client.RawMessageReceived += ClientOnRawMessageReceived;
     client.ChannelListReceived += ClientOnChannelListReceived;
     client.ProtocolError += ClientOnProtocolError;
     while (!closingTime)
     {
         Thread.Sleep(10);
     }
 }
예제 #7
0
        public override void Loop()
        {
            while(true)
               {
               using (var mre = new ManualResetEvent(false))
               {
                   if(_client != null)
                       _client.Disconnect();

                   _client = new IrcClient();
                   _client.Registered += (sender, args) =>
                                        {
                                            _client.LocalUser.JoinedChannel += (sender1, args1) =>
                                            {
                                                args1.Channel.MessageReceived += (o, eventArgs) =>
                                                {
                                                    if (eventArgs.Source.Name == "Taimur")
                                                        Handle(eventArgs.Text);
                                                };

                                                Output("Joined " + args1.Channel.Name);
                                                mre.Set();
                                            };

                                            _client.Channels.Join("#yaar");
                                        };

                   _client.Connect("irc.rizon.net", 6667, false, new IrcUserRegistrationInfo()
                                                                     {
                                                                         NickName = "[Yaar]",
                                                                         UserName = "******",
                                                                         RealName = "[Yaar]"
                                                                     });
                   mre.WaitOne(30.Seconds());
                   while(_client.IsConnected)
                       5.Seconds().Sleep();
               }
               Brain.ListenerManager.CurrentListener.Output("Failed to connect to Rizon.");
               }
        }
예제 #8
0
        void IRCRestart(CommandArgs e)
        {
            IrcUsers.Clear();
            IrcClient.Quit("Restarting...");
            Connecting = true;
            IrcClient = new IrcClient();
            IrcClient.Connect(Config.Server, Config.Port, Config.SSL,
                new IrcUserRegistrationInfo()
                {
                    NickName = Config.Nick,
                    RealName = Config.RealName,
                    UserName = Config.UserName,
                    UserModes = new List<char> { 'i', 'w' }
                });
            IrcClient.Registered += OnIRCRegistered;
            CtcpClient = new CtcpClient(IrcClient) { ClientVersion = "TShockIRC v" + Version };

            e.Player.SendInfoMessage("Restarted the IRC bot.");
        }
예제 #9
0
        void Connect()
        {
            if (Connecting)
                return;

            Connecting = true;
            IrcUsers.Clear();
            IrcClient = new IrcClient();
            IrcClient.Connect(Config.Server, Config.Port, Config.SSL,
                new IrcUserRegistrationInfo()
                {
                    NickName = Config.Nick,
                    RealName = Config.RealName,
                    UserName = Config.UserName,
                    UserModes = new List<char> { 'i', 'w' }
                });
            IrcClient.Disconnected += OnIRCDisconnected;
            IrcClient.Registered += OnIRCRegistered;
            CtcpClient = new CtcpClient(IrcClient) { ClientVersion = "TShockIRC v" + Version };
        }
        //
        // GET: /Notify/
        public ActionResult TravisCi()
        {
            var payload = Request.Form["payload"];

            JObject jsonPayload = null;

            if (payload != null)
            {jsonPayload = (JObject)JsonConvert.DeserializeObject(payload);}

            TimeSpan buildDuration;
            bool buildSuccess = true;
            int buildId = 0;

            HttpWebRequest webRequest =
                (HttpWebRequest)HttpWebRequest.Create("http://www.travis-ci.org/repositories.json?slug=inkdev%2FCryMono");

            using (StreamReader sr = new StreamReader(webRequest.GetResponse().GetResponseStream()))
            {
                string result = sr.ReadToEnd();

                var jsonResult = ((JArray)JsonConvert.DeserializeObject(result))[0];

                buildDuration = TimeSpan.FromSeconds(jsonResult["last_build_duration"].Value<double>());
                buildSuccess = jsonResult["last_build_status"].Value<int>() == 0;
                buildId = jsonResult["last_build_id"].Value<int>();

                var type = jsonResult.GetType();
            }

            // Get build log
            webRequest = (HttpWebRequest)HttpWebRequest.Create(String.Format("http://www.travis-ci.org/jobs/{0}.json", buildId + 1));

            using (StreamReader sr = new StreamReader(webRequest.GetResponse().GetResponseStream()))
            {
                string result = sr.ReadToEnd();

                var jsonResult = ((JObject)JsonConvert.DeserializeObject(result));

                string log = jsonResult["log"].Value<string>();

                bool buildResult = false;
                using (StringReader stringReader = new StringReader(log))
                {
                    string line = stringReader.ReadLine();

                    string summary = "No tests run";
                    while (line != null)
                    {

                        if (line.Equals("-- START TEST RUN --"))
                        {
                            buildResult = true;
                        }  else if (line.StartsWith("Tests run: "))
                        {
                            summary = line + " - " + stringReader.ReadLine();
                        }
                        else if (line.Equals("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>"))
                        {
                            string xmlContents = stringReader.ReadToEnd();

                            xmlContents = xmlContents.Substring(0, xmlContents.IndexOf("</test-results>")+15);

                            XDocument doc = XDocument.Parse(xmlContents);

                            AutoResetEvent are = new AutoResetEvent(false);
                            IrcDotNet.IrcClient client = new IrcDotNet.IrcClient();

                            try
                            {
                                client.Connect("irc.gamesurge.net", false, new IrcUserRegistrationInfo() { NickName = "inkdev-build", RealName = "crymono", UserName = "******" });

                                client.ClientInfoReceived += (s, e) => are.Set();

                                are.WaitOne();

                                //client.Channels.Join(new string[] { "#crymono" });

                                Thread.Sleep(200);
                                //string msg = latestBuild.Commit.Message.Replace("\n", "").Replace("\r", "");
                                string msg = "hello";
                                string buildStatus = buildResult ? "OK" : "FAILED";

                                client.LocalUser.SendMessage("#crymonobuild", String.Format("Travis build completed. Build: {0} - http://travis-ci.org/inkdev/CryMono/builds/{1}", buildStatus,buildId));
                                Thread.Sleep(200);
                                var testResultsElement = doc.Element("test-results");
                                client.LocalUser.SendMessage("#crymonobuild", String.Format("Tests run: {0}, Errors: {1}, Failures: {2}, Inconclusive: {3}, Not run: {4}, Invalid: {5}, Ignored: {6}, Skipped: {7}, Time: {8}s",
                                    testResultsElement.Attribute("total").Value,
                                    testResultsElement.Attribute("errors").Value,
                                    testResultsElement.Attribute("failures").Value,
                                    testResultsElement.Attribute("inconclusive").Value,
                                    testResultsElement.Attribute("not-run").Value,
                                    testResultsElement.Attribute("invalid").Value,
                                    testResultsElement.Attribute("ignored").Value,
                                    testResultsElement.Attribute("skipped").Value,
                                    doc.Descendants("test-suite").First().Attribute("time").Value

                                    ));
                                Thread.Sleep(500);

                                var failingTests =
                                    doc.Descendants("test-case").Where(
                                        x =>
                                        x.Attribute("success").Value == "False" &&
                                        x.Descendants().Any(d => d.Name == "failure")).Take(3);

                                foreach (var item in failingTests)
                                {
                                    client.LocalUser.SendMessage("#crymonobuild", String.Format("{0}: {1}",
                                        item.Attribute("name").Value,
                                        item.Element("failure").Element("message").Value.Replace("\n","")));
                                    Thread.Sleep(500);
                                }

                                if (payload == null)
                                {
                                    client.LocalUser.SendMessage("#crymonobuild", "Something wrong: " + String.Join(",",Request.Form.AllKeys));
                                }
                                else
                                {

                                    client.LocalUser.SendMessage("#crymonobuild",
                                                                 "Debug for ins\\: " + payload);
                                }
                                Thread.Sleep(5000);

                            }
                            finally
                            {
                                if (client != null && client.IsConnected)
                                {
                                    client.Quit("to the hills!");
                                    Thread.Sleep(200);
                                    client.Disconnect();
                                }
                            }

                            break;
                        }

                        line = stringReader.ReadLine();

                    }
                }

            }

            return Content("What?");
        }
예제 #11
0
파일: IRC.cs 프로젝트: edwinr/VPServices
        bool connect()
        {
            if ( irc != null && irc.IsConnected )
            {
                app.WarnAll("IRC is already connected");
                Log.Warn(Name, "Rejecting connection attempt; already connected");
                return true;
            }

            if ( irc != null )
                disconnect();

            app.NotifyAll("Establishing bridge between {0} and {1} on {2}", app.World, channel, host);
            Log.Info(Name, "Creating and establishing IRC bridge...");

            irc = new IrcClient();
            var reg = new IrcUserRegistrationInfo
            {
                NickName = config.Get("Nickname", "VPBridgeBot"),
                RealName = config.Get("Realname", "VPBridge Admin"),
                UserName = config.Get("Username", "VPBridgeAdmin"),
            };

            irc.Error                += (o, e) => { Log.Warn(Name, e.Error.ToString()); };
            irc.ErrorMessageReceived += (o, e) => { Log.Warn(Name, "IRC error: {0}", e.Message); };
            irc.ProtocolError        += (o, e) => { Log.Warn(Name, "Protocol error: {0} {1}", e.Code, e.Message); };
            irc.RawMessageReceived   += onIRCMessage;

            irc.Connect(host, port, false, reg);
            irc.Registered   += onIRCConnected;
            irc.Disconnected += onIRCDisconnected;
            return true;
        }
예제 #12
0
        /// <summary>
        /// Connect to the given stream, returns true if we successfully connected.  Note
        /// that this function executes synchronously, and will block until fully connected
        /// to the IRC server.
        /// </summary>
        /// <param name="stream">The stream to connect to.</param>
        /// <param name="user">The twitch username this connection will use.</param>
        /// <param name="auth">The twitch API token used to log in.  This must begin with 'oauth:'.</param>
        public bool Connect(string stream, string user, string auth)
        {
            user = user.ToLower();
            m_stream = stream.ToLower();

            // Create client and hook up events.
            string server = "irc.twitch.tv";
            int port = 6667;

            WriteDiagnosticMessage("Attempting to connect to server...");

            m_client = new IrcClient();
            m_client.FloodPreventer = new IrcStandardFloodPreventer(4, 2000);

            m_client.Connected += client_Connected;
            m_client.ConnectFailed += client_ConnectFailed;
            m_client.Disconnected += client_Disconnected;
            m_client.Error += client_Error;
            m_client.Registered += client_Registered;
            m_client.ErrorMessageReceived += client_ErrorMessageReceived;

            // Connect to server.
            IPHostEntry hostEntry = Dns.GetHostEntry(server);
            m_client.Connect(new IPEndPoint(hostEntry.AddressList[0], port), false, new IrcUserRegistrationInfo()
            {
                NickName = user,
                UserName = user,
                RealName = user,
                Password = auth
            });

            // Wait for the server to connect.  The connect function on client operates asynchronously, so we
            // wait on s_connectedEvent which is set when client_Connected is called.
            if (!m_connectedEvent.Wait(10000))
            {
                WriteDiagnosticMessage("Connection to '{0}' timed out.", server);
                return false;
            }

            /// Wait for the client to be registered.
            if (!m_registeredEvent.Wait(10000))
            {
                WriteDiagnosticMessage("Registration timed out.", server);
                return false;
            }

            // Attempt to join the channel.  We'll try for roughly 10 seconds to join.  This really shouldn't ever fail.
            m_client.Channels.Join("#" + m_stream);
            int max = 40;
            while (m_client.Channels.Count == 0 && !m_joinedEvent.Wait(250))
            {
                max--;
                if (max < 0)
                {
                    WriteDiagnosticMessage("Failed to connect to {0}  Please press Reconnect.", m_stream);
                    return false;
                }
            }

            WriteDiagnosticMessage("Connected to channel {0}.", m_stream);

            // This command tells twitch that we are a chat bot capable of understanding subscriber/turbo/etc
            // messages.  Without sending this raw command, we would not get that data.
            m_client.SendRawMessage("TWITCHCLIENT 2");

            UpdateMods();
            return true;
        }
예제 #13
0
        /// <summary>
        /// Connect to the given stream, returns true if we successfully connected.  Note
        /// that this function executes synchronously, and will block until fully connected
        /// to the IRC server.
        /// </summary>
        /// <param name="stream">The stream to connect to.</param>
        /// <param name="user">The twitch username this connection will use.</param>
        /// <param name="auth">The twitch API token used to log in.  This must begin with 'oauth:'.</param>
        public ConnectResult Connect(string stream, string user, string auth, int timeout = 10000)
        {
            if (m_shutdown)
                throw new InvalidOperationException("Attempted to connect while disconnecting.");

            user = user.ToLower();
            m_stream = stream.ToLower();

            if (m_data == null)
                m_data = new TwitchUsers(m_stream);

            // Create client and hook up events.
            m_client = new IrcClient();

            m_client.Connected += client_Connected;
            m_client.UnsuccessfulLogin += m_client_UnsuccessfulLogin;
            m_client.ConnectFailed += client_ConnectFailed;
            m_client.Error += client_Error;
            m_client.Registered += client_Registered;
            m_client.ErrorMessageReceived += client_ErrorMessageReceived;
            m_client.PongReceived += m_client_PongReceived;
            m_client.PingReceived += m_client_PingReceived;

            m_flood = new FloodPreventer(this);
            m_flood.RejectedMessage += m_flood_RejectedMessage;
            m_client.FloodPreventer = m_flood;

            int currTimeout = timeout;
            DateTime started = DateTime.Now;

            m_connectedEvent.Reset();
            m_registeredEvent.Reset();
            m_joinedEvent.Reset();

            // Connect to server.
            m_client.Connect("irc.twitch.tv", 6667, false, new IrcUserRegistrationInfo()
            {
                NickName = user,
                UserName = user,
                RealName = user,
                Password = auth
            });

            // Wait for the server to connect.  The connect function on client operates asynchronously, so we
            // wait on s_connectedEvent which is set when client_Connected is called.
            if (!m_connectedEvent.Wait(currTimeout))
            {
                WriteDiagnosticMessage("Connecting to the Twitch IRC server timed out.");
                return ConnectResult.NetworkFailed;
            }

            currTimeout = timeout - (int)started.Elapsed().TotalMilliseconds;
            /// Wait for the client to be registered.
            if (!m_registeredEvent.Wait(currTimeout))
            {
                // Shouldn't really happen
                WriteDiagnosticMessage("Registration timed out.");
                return ConnectResult.Failed;
            }

            if (m_loginFailed)
                return ConnectResult.LoginFailed;

            // Attempt to join the channel.  We'll try for roughly 10 seconds to join.  This really shouldn't ever fail.
            m_client.Channels.Join("#" + m_stream);
            currTimeout = timeout - (int)started.Elapsed().TotalMilliseconds;
            if (!m_joinedEvent.Wait(currTimeout))
            {
                // Shouldn't really happen
                WriteDiagnosticMessage("Failed to join channel {0}.", m_stream);
                return ConnectResult.Failed;
            }

            TwitchSource.Log.Connected(stream);

            // This command tells twitch that we are a chat bot capable of understanding subscriber/turbo/etc
            // messages.  Without sending this raw command, we would not get that data.
            m_client.SendRawMessage("TWITCHCLIENT 3");

            UpdateMods();
            return ConnectResult.Success;
        }
예제 #14
0
파일: CmdIRC.cs 프로젝트: EIREXE/discord
        public static void Start(SteamID room)
        {
            _room = room;

            if (_started)
                return;

            _started = true;

            messageQueue = new Queue<Tuple<string, string>>();

            _client = new IrcClient();
               // _client.FloodPreventer = new IrcStandardFloodPreventer(4, 2000);
            _client.Connected += (sender, e) =>
                                     {
                                         Message("Connected. Waiting for registration...");

                                         var c = (IrcClient)sender;
                                         c.Channels.Join(IRCChannel);

                                         c.LocalUser.NoticeReceived += (sender2, e2) => Console.WriteLine(string.Format("Notice from {0}: {1}", e2.Source.Name, e2.Text));
                                         c.LocalUser.MessageReceived += (sender2, e2) => Message(string.Format("Received PM from {0}: {1}", e2.Source.Name, e2.Text));
                                         c.LocalUser.JoinedChannel += (sender2, e2) =>
                                                                          {
                                                                              Message(string.Format("Joined {0} - IRC Spy Mode engaged. {1}", e2.Channel.Name, e2.Comment));

                                                                              //Message("Topic: " + e2.Channel.Topic); //Nothing happens!
                                                                              //e2.Channel.GetTopic(); //This causes TopicChanged to be called twice!

                                                                              e2.Channel.UsersListReceived += (sender3, e3) => Message("Users: " + string.Join(", ", e2.Channel.Users.OrderBy(u => u.User.NickName).Select(u => u.User.IsOperator ? "@" : "" + u.User.NickName))); //OH GOD MY EYES
                                                                              e2.Channel.TopicChanged += (sender3, e3) => Message("Topic: " + e2.Channel.Topic);
                                                                              e2.Channel.UserKicked += (sender3, e3) => Message(string.Format("{0} was kicked from {1}. {2}", e3.ChannelUser.User.NickName, e2.Channel.Name, e2.Comment));
                                                                              e2.Channel.UserJoined += (sender3, e3) => Message(string.Format("{0} joined {1}. {2}", e3.ChannelUser.User.NickName, e2.Channel.Name, e2.Comment));
                                                                              e2.Channel.UserLeft += (sender3, e3) => Message(string.Format("{0} left {1}. {2}", e3.ChannelUser.User.NickName, e2.Channel.Name, e2.Comment));
                                                                              e2.Channel.MessageReceived += SendIRC;
                                                                              e2.Channel.NoticeReceived += (sender3, e3) => Console.WriteLine(string.Format("Notice from {0}: {1}", e3.Source.Name, e3.Text));
                                                                          };

                                         c.LocalUser.LeftChannel += (sender2, e2) => Message(string.Format("Left {0}. ({1})", e2.Channel.Name, e2.Comment));

                                     };

            _client.Disconnected += (sender, e) =>
                                        {
                                            Message("Disconnected for some reason.");
                                            Stop();
                                        };

            _client.Registered += (sender, e) => Message(string.Format("Registered. Joining {0}...", IRCChannel));

            using (var connectedEvent = new ManualResetEventSlim(false))
            {
                _client.Connected += (sender2, e2) => connectedEvent.Set();

                _client.Connect(IRCServer, false, new IrcUserRegistrationInfo
                                                      {
                                                          NickName = "AGOPBOT",
                                                          UserName = "******",
                                                          Password = "******",
                                                          RealName = "Agopbot Shirinian"
                                                      });

                if (!connectedEvent.Wait(10000))
                {
                    _client.Dispose();
                    Message(string.Format("Connection to {0} timed out.", IRCServer));
                }
            }
        }
예제 #15
0
파일: IrcBot.cs 프로젝트: quiznilo/Zerobot
        protected void Connect(string server, IrcRegistrationInfo registrationInfo)
        {
            var client = new IrcClient();
            client.FloodPreventer = new IrcStandardFloodPreventer(4, 2000);
            client.Connected += IrcClient_Connected;
            client.Disconnected += IrcClient_Disconnected;
            client.Registered += IrcClient_Registered;
            client.PingReceived += IrcClient_PingReceived;
            client.NetworkInformationReceived += IrcClient_OnNetworkInformationReceived;
            client.RawMessageReceived += IrcClient_OnRawMessageReceived;
            client.RawMessageSent += IrcClient_OnRawMessageSent;
            clientCount++;

            // Wait until connection has succeeded or timed out.
            using (var connectedEvent = new ManualResetEventSlim(false)) {
                client.Connected += (sender2, e2) => connectedEvent.Set();
                client.Connect(server, false, registrationInfo);
            //	client.Id = clientCount++;
                if (!connectedEvent.Wait(10000)) {
                    client.Dispose();
                    Console.WriteLine("Connection to '{0}' timed out.", server);
                    return;
                }
            }
            // Add new client to collection
            this.allClients.Add(client);

            Console.Out.WriteLine("Now connected to '{0}'.", server);
        }
예제 #16
0
        /// <summary>
        /// </summary>
        /// <param name="server">
        /// </param>
        /// <param name="registrationInfo">
        /// </param>
        protected void Connect(string server, IrcRegistrationInfo registrationInfo)
        {
            // Create new IRC client and connect to given server.
            var client = new IrcClient();
            client.FloodPreventer = new IrcStandardFloodPreventer(4, 2000);
            client.Connected += this.IrcClient_Connected;
            client.Disconnected += this.IrcClient_Disconnected;
            client.Registered += this.IrcClient_Registered;
            client.ProtocolError += this.IrcClient_ProtocolError;
            client.ChannelListReceived += this.client_ChannelListReceived;

            // Wait until connection has succeeded or timed out.
            using (var connectedEvent = new ManualResetEventSlim(false))
            {
                client.Connected += (sender2, e2) => connectedEvent.Set();
                client.Connect(server, false, registrationInfo);
                if (!connectedEvent.Wait(10000))
                {
                    client.Dispose();
                    ConsoleUtilities.WriteError("Connection to '{0}' timed out.", server);
                    return;
                }
            }

            // Add new client to collection.
            this.allClients.Add(client);

            Console.Out.WriteLine("Now connected to '{0}'.", server);
        }
예제 #17
0
        /// <summary>
        /// Attempt to connect to our pre-configured network. Does nothing if you're already connected.
        /// </summary>
        /// 
        /// <remarks>
        /// 
        /// <para>
        /// This will need to be refactored to allow multi-network support. This will perform a no-op
        /// if you are already connected.
        /// </para>
        ///
        /// <para>
        /// Unfortunately there's a rather annoying bug with Thresher's IRC library: when you re-use the same
        /// connection object, it maintains a cache of capability options, as sent as part of the registration
        /// preamble from the IRCD. There's no way (so far) to flush this cache, and it's not a very intelligent
        /// cache - it doesn't look for hits, only misses - so we wind up trying to cache something twice and
        /// an exception resulting from said behavior.
        /// </para>
        /// 
        /// <para>
        /// So... In order to support a reconnect ability you need to create a NEW connection object. This requires
        /// unsubscribing your old event handlers (to prevent memory leaks), and re-registering them. Painful duplication,
        /// crappy mixing of responsibility... name your reason why this is bad. Unfortunately there's not much choice.
        /// </para>
        /// 
        /// </remarks>
        public void Connect()
        {
            if (!IsConnected)
            {
                // Just grab the first entry until we have proper multi server support
                Network network = NetworkList[0];
                Server server = network.ServerList[0];

                _ircClient = new IrcClient();
                _ctcpClient = new CtcpClient(_ircClient);

                // Subscribe our events
                _ircClient.Registered += ClientRegisteredWithIrcd;
                _ircClient.RawMessageReceived += RawMessageReceived;
                _ircClient.RawMessageSent += RawMessageSent;

                _ircClient.Connect(server.Host, server.Port ?? 6667, false, new IrcUserRegistrationInfo
                {
                    NickName = network.BotNickname,
                    UserName = network.BotUsername,
                    RealName = network.BotRealname
                });

                // Make sure we don't get any random disconnected events before we're connected
                _ircClient.Disconnected += Disconnected;
            }
        }