コード例 #1
0
        public void Run()
        {
            connecting = true;
            _client.Connect(_hostname, false, _userInfo);

            _heartbeatThread = new Thread(HeartbeatThread);
            _heartbeatThread.Start();
        }
コード例 #2
0
ファイル: Connect.cs プロジェクト: cmpct/cmpctircd-tests
        public void TestBasicConnectAndRegistration()
        {
            var client = new StandardIrcClient();

            using (var connectedEvent = new ManualResetEventSlim(false)) {
                var registrationInfo = new IrcUserRegistrationInfo()
                {
                    NickName = "cmpct_test",
                    Password = "",
                    UserName = "******",
                    RealName = "cmpct_test"
                };
                client.Connected += (sender, e) => connectedEvent.Set();
                client.Connect("127.0.0.1", 6667, false, registrationInfo);

                if (!connectedEvent.Wait(100))
                {
                    client.Dispose();
                    Assert.Fail("ConnectedEvent not called: server not listening?");
                }

                using (var registrationEvent = new ManualResetEventSlim(false)) {
                    client.Registered += (sender, e) => registrationEvent.Set();

                    if (!registrationEvent.Wait(500))
                    {
                        client.Dispose();
                        Assert.Fail("RegistrationEvent not called: not registered?");
                    }
                }
            }
        }
コード例 #3
0
ファイル: IrcConnection.cs プロジェクト: peerau/Ditto
        public IrcConnection(IrcConnectionInfo ircConnectionInfo)
        {
            IrcConnectionInfo = ircConnectionInfo;

            var connectionName = $"{ircConnectionInfo.Server}:{ircConnectionInfo.Nick}";

            if (!ConnectionPool.ContainsKey(connectionName))
            {
                IrcClient = new StandardIrcClient();
                IrcClient.RawMessageReceived   += Irc_RawMessageReceived;
                IrcClient.ErrorMessageReceived += Irc_ErrorMessageReceived;
                IrcClient.Connected            += Irc_Connected;
                IrcClient.ConnectFailed        += Irc_ConnectFailed;
                IrcClient.MotdReceived         += Irc_MotdReceived;
                IrcClient.Connect(ircConnectionInfo.Server, ircConnectionInfo.Port, false, ircConnectionInfo.GetRegistrationInfo());

                // Wait for event handlers to authenticate and join the channel
                Thread.Sleep(30 * 1000);

                ConnectionPool.Add(connectionName, IrcClient);
            }
            else
            {
                IrcClient = ConnectionPool[connectionName];
                IrcClient.LocalUser.JoinedChannel += Irc_JoinedChannel;
                JoinIrcChannel();
            }
        }
コード例 #4
0
        protected void Connect(string server, IrcRegistrationInfo registrationInfo)
        {
            // Create new IRC client and connect to given server.
            var client = new StandardIrcClient();

            client.FloodPreventer = new IrcStandardFloodPreventer(4, 2000);
            client.Connected     += IrcClient_Connected;
            client.Disconnected  += IrcClient_Disconnected;
            client.Registered    += IrcClient_Registered;

            // 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);
        }
コード例 #5
0
        public MainWindow()
        {
            InitializeComponent();
            this.messageField.KeyDown += textBoxEnter;

            //Instantiate an IRC client session
            irc = new StandardIrcClient();
            IrcRegistrationInfo info = new IrcUserRegistrationInfo()
            {
                NickName = Environment.UserName, // "NerdChat",
                UserName = Environment.UserName + "NerdChat",
                RealName = "NerdChat"
            };

            //Open IRC client connection
            irc.Connect("irc.freenode.net", false, info);
            irc.RawMessageReceived += IrcClient_Receive;

            // Add server to treeview
            TreeViewItem serverTreeItem = new TreeViewItem();

            serverTreeItem.Header = "irc.freenode.net";
            channelTree.Items.Add(serverTreeItem);

            // Add some dummy channels for testing
            for (int i = 0; i < 10; i++)
            {
                TreeViewItem dummyItem = new TreeViewItem();
                dummyItem.Header = "#dummy" + i;
                serverTreeItem.Items.Add(dummyItem);
            }
        }
コード例 #6
0
        static void Main(string[] args)
        {
            IrcRegistrationInfo info = new IrcUserRegistrationInfo()
            {
                NickName = "myBot",
                UserName = "******",
                RealName = "myBot"
            };

            //Open IRC client connection

            irc.Connected          += Irc_Connected;
            irc.RawMessageReceived += IrcClient_Receive;
            irc.MotdReceived       += Irc_MotdReceived;


            irc.Connect("irc.SUPERSERVER.org", 6667, false, info);

            String cmd = "";

            while (cmd != "/exit")
            {
                cmd = Console.ReadLine();
                irc.SendRawMessage(cmd);
            }
        }
コード例 #7
0
ファイル: IrcManager.cs プロジェクト: syncore/SST
        /// <summary>
        /// Connects the client to the Irc server.
        /// </summary>
        public void Connect()
        {
            if (!RequiredIrcSettingsAreValid())
            {
                return;
            }

            using (_client = new StandardIrcClient())
            {
                _client.FloodPreventer = new IrcStandardFloodPreventer(4, 2000);
                _client.Connected     += _ircEvent.IrcClient_Connected;
                _client.Disconnected  += _ircEvent.IrcClient_Disconnected;
                _client.Registered    += _ircEvent.IrcClient_Registered;

                // Wait until connection has succeeded or timed out.
                using (var registeredEvent = new ManualResetEventSlim(false))
                {
                    using (var connectedEvent = new ManualResetEventSlim(false))
                    {
                        // ReSharper disable once AccessToDisposedClosure
                        _client.Connected += (sender2, e2) => connectedEvent.Set();
                        // ReSharper disable once AccessToDisposedClosure
                        _client.Registered += (sender2, e2) => registeredEvent.Set();
                        _client.Connect(IrcSettings.ircServerAddress, Convert.ToInt32(IrcSettings.ircServerPort),
                                        false, RegistrationInfo);
                        if (!connectedEvent.Wait(10000))
                        {
                            Log.Write(string.Format("Connection to '{0}:{1}' timed out. Will try to reconnect up to {2} times.",
                                                    IrcSettings.ircServerAddress, IrcSettings.ircServerPort,
                                                    MaxReconnectionTries), _logClassType, _logPrefix);

                            StopIrcThread();
                            AttemptReconnection(false);
                            return;
                        }
                    }
                    Log.Write(string.Format("Now connected to '{0}:{1}'.",
                                            IrcSettings.ircServerAddress, IrcSettings.ircServerPort), _logClassType, _logPrefix);
                    if (!registeredEvent.Wait(10000))
                    {
                        Log.Write(string.Format("Could not register to '{0}:{1}'. Will try to reconnect up to {2} times.",
                                                IrcSettings.ircServerAddress,
                                                IrcSettings.ircServerPort, MaxReconnectionTries), _logClassType, _logPrefix);

                        StopIrcThread();
                        AttemptReconnection(false);
                        return;
                    }
                }

                Log.Write(string.Format("Now registered to '{0}:{1}' as '{2}'.",
                                        IrcSettings.ircServerAddress, IrcSettings.ircServerPort,
                                        IrcSettings.ircUserName), _logClassType, _logPrefix);

                // Connected: reset attempt count
                _reconnectTries  = 0;
                IsConnectedToIrc = true;
                Loop();
            }
        }
コード例 #8
0
ファイル: IrcLayer.cs プロジェクト: shatteredbeam/FIDO
        public async Task Connect(string server, int port, bool useSsl, string nickName, string userName, string realname, List <string> channelsToJoin)
        {
            channels = channelsToJoin;
            irc      = new StandardIrcClient
            {
                FloodPreventer = new IrcStandardFloodPreventer(3, 5000)
            };

            irc.RawMessageSent += IrcOnRawMessageSent;
            irc.Error          += OnIrcOnOnError;
            irc.Registered     += IrcOnRegistered;
            irc.Disconnected   += IrcOnDisconnected;

            try
            {
                var registrationInfo = new IrcUserRegistrationInfo {
                    NickName = nickName, UserName = userName, RealName = realname
                };
                var ipAddresses = await Dns.GetHostAddressesAsync(server);

                var ipAddress = ipAddresses.First(x => x.AddressFamily == AddressFamily.InterNetwork);
                Console.WriteLine($"Resolved IP: {ipAddress}");
                var ipEndPoint = new IPEndPoint(ipAddress, port);
                irc.Connect(ipEndPoint, useSsl, registrationInfo);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
コード例 #9
0
        internal void Start(string parChannel, string parNickname)
        {
            if (Client != null)
            {
                return;
            }
            Channel  = parChannel.ToLower();
            Nickname = parNickname;
            var reg = new IrcUserRegistrationInfo
            {
                RealName = Nickname,
                NickName = Nickname,
                UserName = Nickname
            };

            Client = new StandardIrcClient {
                FloodPreventer = new IrcStandardFloodPreventer(4, 2000)
            };

            Client.ErrorMessageReceived += (sender, args) =>
            {
                Console.WriteLine(args.Message);
            };

            Client.Connected += (sender, args) =>
            {
            };

            Client.Disconnected += (sender, args) =>
            {
                Client.Dispose();
                Client = null;
                Thread.Sleep(120000);
                Start(Channel, Nickname);
            };

            Client.Registered += (sender, args) =>
            {
                var tmp = (StandardIrcClient)sender;
                tmp.LocalUser.JoinedChannel += (o, JoinedChannelArgs) =>
                {
                    if (JoinedChannelArgs.Channel.Name == Channel)
                    {
                        tmp.RawMessageReceived += (sender1, eventArgs) =>
                        {
                            if (eventArgs.Message.Command != "PRIVMSG")
                            {
                                return;
                            }
                            var msgArgs = new MessageArgs(eventArgs.Message.Parameters[1], eventArgs.Message.Source.Name);
                            MessageReceivedHandler(msgArgs);
                        };
                    }
                };
                tmp.Channels.Join(Channel);
            };
            Client.Connect(Server, false, reg);
        }
コード例 #10
0
ファイル: IrcBot.cs プロジェクト: Homesweethome/SwagCore
 public void Connect(string server, IrcRegistrationInfo registrationInfo)
 {
     _ircClient = new StandardIrcClient();
     _ircClient.FloodPreventer = new IrcStandardFloodPreventer(4, 2000);
     _ircClient.Connected     += ClientOnConnected;
     _ircClient.Disconnected  += ClientOnDisconnected;
     _ircClient.Registered    += ClientOnRegistered;
     _ircClient.Connect(server, false, registrationInfo);
 }
コード例 #11
0
        /// <summary>
        /// Overwritten Init method.
        /// This method connects to the M59 server.
        /// So we connect to IRC here as well.
        /// </summary>
        public override void Init()
        {
            // base handler connecting to m59 server
            base.Init();

            // create IRC command queues
            ChatCommandQueue  = new LockingQueue <string>();
            AdminCommandQueue = new LockingQueue <string>();
            WhoXQueryQueue    = new WhoXQueryQueue();

            // Whether bot echoes to IRC or not.
            DisplayMessages = true;

            // Create list for keeping track of user registration.
            UserRegistration = new Dictionary <string, bool>();

            // Init list of recent admins to send a command.
            RecentAdmins = new List <string>();

            // create an IRC client instance
            IrcClient = new StandardIrcClient();
            IrcClient.FloodPreventer = new FloodPreventer(Config.MaxBurst, Config.Refill);

            // hook up IRC client event handlers
            // beware! these are executed by the internal workthread
            // of the library.
            IrcClient.Connected         += OnIrcClientConnected;
            IrcClient.ConnectFailed     += OnIrcClientConnectFailed;
            IrcClient.Disconnected      += OnIrcClientDisconnected;
            IrcClient.Registered        += OnIrcClientRegistered;
            IrcClient.ProtocolError     += OnIrcClientProtocolError;
            IrcClient.WhoXReplyReceived += OnWhoXReplyReceived;

            // build our IRC connection info
            IrcUserRegistrationInfo regInfo = new IrcUserRegistrationInfo();

            regInfo.UserName = Config.NickName;
            regInfo.RealName = Config.NickName;
            regInfo.NickName = Config.NickName;

            // if password is set
            if (!String.Equals(Config.IRCPassword, String.Empty))
            {
                regInfo.Password = Config.IRCPassword;
            }

            // log IRC connecting
            Log("SYS", "Connecting IRC to " + Config.IRCServer + ":" + Config.IRCPort);

            // connect the lib internally (this is async)
            IrcClient.Connect(Config.IRCServer, Config.IRCPort, false, regInfo);
        }
コード例 #12
0
        private void Connect()
        {
            Server = new StandardIrcClient();

            Server.RawMessageReceived += HandleRawMessage;
            Server.Connected          += HandleServerConnected;
            Server.Registered         += HandleRegistered;

            Server.Connect(Config.Server, Config.Port, Config.Ssl, new IrcUserRegistrationInfo()
            {
                NickName = Config.Nickname,
                RealName = Config.Nickname,
                UserName = Config.Nickname,
                Password = Config.Password
            });
        }
コード例 #13
0
 private bool ConnectToServer(StandardIrcClient client, string server)
 {
     // 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(false);
         }
     }
     return(true);
 }
コード例 #14
0
        static void Main()
        {
            Logger.Init();

            var server   = "irc.rizon.sexy";
            var username = "******";

            using (var client = new StandardIrcClient()) {
                //client.FloodPreventer = new IrcStandardFloodPreventer(4, 2000);
                client.Disconnected += IrcClient_Disconnected;
                client.Registered   += IrcClient_Registered;
                // Wait until connection has succeeded or timed out.
                using (var registeredEvent = new ManualResetEventSlim(false)) {
                    using (var connectedEvent = new ManualResetEventSlim(false)) {
                        client.Connected  += (sender2, e2) => connectedEvent.Set();
                        client.Registered += (sender2, e2) => registeredEvent.Set();
                        client.Connect(server, 6667, false,
                                       new IrcUserRegistrationInfo()
                        {
                            NickName = username,
                            UserName = username,
                            RealName = username,
                            Password = PrivateConstants.IrcFloodBypassPassword,
                        });
                        if (!connectedEvent.Wait(10000))
                        {
                            Console.WriteLine($"Connection to '{server}' timed out.");
                            return;
                        }
                    }
                    client.LocalUser.NoticeReceived += IrcClient_LocalUser_NoticeReceived;

                    Console.Out.WriteLine($"Now connected to '{server}'.");
                    if (!registeredEvent.Wait(10000))
                    {
                        Console.WriteLine($"Could not register to '{server}'.");
                        return;
                    }
                }

                Console.Out.WriteLine($"Now registered to '{server}' as '{username}'.");
                client.Channels.Join(EchoChannel);

                HandleEventLoop(client);
            }
        }
コード例 #15
0
        public Task Connect()
        {
            connectingTaskCompletionSource = new TaskCompletionSource <object>();
            client.Connected     += OnConnectedCallback;
            client.ConnectFailed += OnConnectFailedCallback;

            var registrationInfo = new IrcUserRegistrationInfo
            {
                NickName = serverConfig.UserName,
                Password = serverConfig.Password,
                RealName = "Relays messages between chat rooms on different services.",
                UserName = serverConfig.UserName
            };

            client.Connect(serverConfig.ServerAddress, false, registrationInfo);

            return(connectingTaskCompletionSource.Task);
        }
コード例 #16
0
        protected override void Connect()
        {
            _ircClient = new StandardIrcClient();
            _ircClient.RawMessageReceived += IrcClient_RawMessageReceived;

            _ircClient.Connected     += IrcClient_Connected;
            _ircClient.ConnectFailed += IrcClient_ConnectFailed;
            _ircClient.Registered    += _ircClient_Registered;

            _ircClient.Connect(_host, _port, false, new IrcUserRegistrationInfo()
            {
                NickName = _nickname,
                RealName = _nickname,
                UserName = _nickname,
            });

            _ircClient.Disconnected += HandleDisconnect;
        }
コード例 #17
0
ファイル: Program.cs プロジェクト: ziccardi/fehbot
        public async void Run()
        {
            StandardIrcClient client = new StandardIrcClient();

            client.Connected          += Connected;
            client.Registered         += Registered;
            client.Disconnected       += Disconnected;
            client.RawMessageReceived += (object sender, IrcRawMessageEventArgs e) => {
                if (e.RawContent.Contains("NickServ") && e.RawContent.Contains("You are now identified for"))
                {
                    client.Channels.Join(infoFactory.Channels);
                }
            };

            var mongo = new MongoClient();

            db = mongo.GetDatabase("fehBot");

            RESTServer server = new RESTServer(db, 18080);

            Thread serverThread = new Thread(server.StartListening);

            serverThread.Start();

            // Wait until connection has succeeded or timed out.
            using (var connectedEvent = new ManualResetEventSlim(false))
            {
                client.Connected += (sender2, e2) => connectedEvent.Set();

                var registrationInfo = infoFactory.Registration;

                client.Connect(infoFactory.Server, false, registrationInfo);

                if (!connectedEvent.Wait(10000))
                {
                    client.Dispose();
                    stopWaitHandle.Set();
                    Console.Error.WriteLine("Connection Timeout");
                    return;
                }
            }

            stopWaitHandle.WaitOne();
        }
コード例 #18
0
        public Task <bool> Connect()
        {
            foreach (IrcServerConfiguration serverConfig in _config.GetValue <List <IrcServerConfiguration> >("servers"))
            {
                StandardIrcClient client = new StandardIrcClient();
                _clients[client]      = serverConfig;
                client.Connected     += ClientOnConnected;
                client.ConnectFailed += ClientOnConnectFailed;
                client.Registered    += ClientOnRegistered;

                client.Connect(new Uri($"irc://{serverConfig.Host}"), new IrcUserRegistrationInfo()
                {
                    NickName = serverConfig.Nickname,
                    UserName = serverConfig.Username,
                    RealName = serverConfig.RealName,
                });
            }
            return(new Task <bool>(() => true)); // Future todo: actually return a real result, right now we don't care because we're jerks
        }
コード例 #19
0
        private void ConnectMethod(string commandstring)
        {
            var userdata = Class1.GetModData();
            IrcUserRegistrationInfo myreg;

            if (commandstring == "#/connect default")
            {
                myclient = new StandardIrcClient();
                setup_events();
                setup_settings();
                var server = userdata[3].Split(':');
                myreg = new IrcUserRegistrationInfo()
                {
                    NickName = userdata[2],
                    UserName = userdata[0],
                    RealName = userdata[1]
                };
                myclient.Connect(server[0], int.Parse((Il2CppSystem.String)server[1]), bool.Parse(server[2]), myreg);
                return;
            }
            if (!commandstring.StartsWith("#/connect"))
            {
                return;
            }
            var hostargs = commandstring.Replace("#/connect", "").Trim().Split(' ');

            myclient = new StandardIrcClient();
            setup_events();
            setup_settings();

            myreg = new IrcUserRegistrationInfo()
            {
                NickName = userdata[2],
                UserName = userdata[0],
                RealName = userdata[1]
            };
            myclient.Connect(hostargs[0], int.Parse((Il2CppSystem.String)hostargs[1]), false, myreg);
        }
コード例 #20
0
ファイル: Form1.cs プロジェクト: LeviVRussell/ChatClient
 private void ConnectBtn_Click(object sender, EventArgs e)
 {
     if (client.IsConnected)
     {
         client.Disconnect();
         ConnectBtn.Text = "Connect";
     }
     else
     {
         Uri uri = new Uri(AddressTxb.Text);
         ConnectBtn.Text = "Connecting...";
         IrcUserRegistrationInfo info = new IrcUserRegistrationInfo();
         string username = UsernameTxb.Text;
         if (username.Length < 1)
         {
             username = "******" + RandomNumberGenerator.Create().ToString();
         }
         info.NickName = username;
         info.RealName = username;
         info.UserName = username;
         info.Password = PasswordTxb.Text;
         client.Connect(uri, info);
     }
 }
コード例 #21
0
ファイル: Connect.cs プロジェクト: cmpct/cmpctircd-tests
        public void TestJoinChannel()
        {
            var client           = new StandardIrcClient();
            var registrationInfo = new IrcUserRegistrationInfo()
            {
                NickName = "cmpct_test",
                Password = "",
                UserName = "******",
                RealName = "cmpct_test"
            };

            client.Connect("127.0.0.1", 6667, false, registrationInfo);


            using (var registrationEvent = new ManualResetEventSlim(false)) {
                // Need to include the registration check for the delay
                client.Registered += (sender, e) => registrationEvent.Set();

                if (!registrationEvent.Wait(500))
                {
                    client.Dispose();
                    Assert.Fail("RegistrationEvent not called: not registered?");
                }
            }

            using (var joinedChannelEvent = new ManualResetEventSlim(false)) {
                client.LocalUser.JoinedChannel += (sender, e) => joinedChannelEvent.Set();
                client.Channels.Join("#test");

                if (!joinedChannelEvent.Wait(500))
                {
                    client.Dispose();
                    Assert.Fail("JoinedChannelEvent not called: channel not joined?");
                }
            }
        }
コード例 #22
0
        public void Connect(ConnectOptions connectOptions)
        {
            ircClient.Connect(connectOptions.Host, connectOptions.EnableSsl, new IrcUserRegistrationInfo
            {
                NickName = connectOptions.Nick,
                UserName = connectOptions.Name,
                Password = connectOptions.Password,
                RealName = connectOptions.RealName
            });

            ircClient.RawMessageReceived += (obj, ea) =>
            {
                this.Clients.Client(this.Context.ConnectionId).conected("test");
            };
            ircClient.Connected += (obj, ea) =>
            {
                this.Clients.Client(this.Context.ConnectionId).conected("test");
            };

            ircClient.ConnectFailed += (obj, ea) =>
            {
                this.Clients.Client(this.Context.ConnectionId).conected("test");
            };
        }
コード例 #23
0
        public bool Connect(BotType target)
        {
            switch (target)
            {
            case BotType.Osu:
            {
                IrcUserRegistrationInfo reg = new IrcUserRegistrationInfo()
                {
                    NickName = m_credentials.OsuCredentials.Username,
                    UserName = m_credentials.OsuCredentials.Username,
                    RealName = m_credentials.OsuCredentials.Username,
                    Password = m_credentials.OsuCredentials.Password,
                };

                try
                {
                    m_osuClient = new StandardIrcClient();

                    m_osuClient.Connected += (o, e) =>
                    {
                        Console.WriteLine("Connected to irc.ppy.sh");
                    };

                    m_osuClient.ConnectFailed += (o, e) =>
                    {
                        Console.WriteLine("Failed connecting to irc.ppy.sh");
                    };

                    Console.WriteLine("Connecting to irc.ppy.sh...");

                    m_osuClient.RawMessageReceived += m_osuClient_RawMessageReceived;
                    m_osuClient.Disconnected       += (o, e) =>
                    {
                        m_osuClient.Disconnect();
                        Console.WriteLine("Got disconnected from irc.ppy.sh, reconnecting...");
                        m_osuClient.Connect("irc.ppy.sh", 6667, false, reg);
                    };

                    m_osuClient.Connect("irc.ppy.sh", 6667, false, reg);
                    m_osuClient.SendRawMessage($"PASS {m_credentials.OsuCredentials.Password}\r\n");
                    m_osuClient.SendRawMessage($"NICK {m_credentials.OsuCredentials.Username}\r\n");

                    return(true);
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Something happened while trying to connect to irc.ppy.sh, {e.Message}");
                    return(false);
                }
            }

            case BotType.Twitch:
            {
                {
                    IrcUserRegistrationInfo reg = new IrcUserRegistrationInfo()
                    {
                        NickName = m_credentials.TwitchCredentials.Username,
                        UserName = m_credentials.TwitchCredentials.Username,
                        RealName = m_credentials.TwitchCredentials.Username,
                        Password = m_credentials.TwitchCredentials.Password
                    };

                    try
                    {
                        m_twitchClient = new TwitchIrcClient();

                        m_twitchClient.Connected += (o, e) =>
                        {
                            Console.WriteLine("Connected to irc.twitch.tv");
                        };

                        m_twitchClient.ConnectFailed += (o, e) =>
                        {
                            Console.WriteLine("Failed connecting to irc.twitch.tv");
                        };

                        Console.WriteLine("Connecting to irc.twitch.tv...");

                        m_twitchClient.RawMessageReceived += m_twitchClient_RawMessageReceived;
                        m_twitchClient.Disconnected       += (o, e) =>
                        {
                            Console.WriteLine("Got disconnected from irc.twitch.tv, reconnecting...");
                            m_twitchClient.Connect("irc.twitch.tv", 6667, false, reg);
                        };

                        m_twitchClient.Connect("irc.twitch.tv", 6667, false, reg);

                        return(true);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"Something happened while trying to connect to irc.twitch.tv, {e.Message}");

                        return(false);
                    }
                }
            }

            default:
                return(false);    // wat
            }
        }
コード例 #24
0
        void Run()
        {
            Client = new StandardIrcClient();
            DrawCommandLine();

            var Info = new IrcUserRegistrationInfo();

            Info.NickName = Settings.Default.Name;
            Info.RealName = Settings.Default.Realname;
            Info.UserName = Settings.Default.Realname + "Bot";

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

                Client.Connect(new Uri(Settings.Default.Server), Info);

                if (!connectedEvent.Wait(10000))
                {
                    Client.Dispose();
                    PrintLine(string.Format("Connection to {0} timed out.", Settings.Default.Server), ConsoleColor.Red);
                    return;
                }

                PrintLine(string.Format("Connected to {0}", Settings.Default.Server));

                // *** POST-INIT
                Client.MotdReceived += delegate(Object Sender, EventArgs E)
                {
                    PrintLine("Joining Channels...");
                    Client.Channels.Join(Settings.Default.Channel);
                };

                // *** DEBUG OUTPUT
                Client.RawMessageReceived += delegate(Object Sender, IrcRawMessageEventArgs Event)
                {
                    PrintLine(Event.RawContent);
                };

                // *** PING
                Client.PingReceived += delegate(Object Sender, IrcPingOrPongReceivedEventArgs Event)
                {
                    Client.Ping(Event.Server);
                };

                // *** CHANNEL JOINING
                Client.LocalUser.JoinedChannel += delegate(Object Sender, IrcChannelEventArgs Event)
                {
                    Event.Channel.MessageReceived += Channel_MessageReceived;
                    SayInChannel(OnJoinActions);
                };

                // *** REJOIN AFTER KICK
                Client.LocalUser.LeftChannel += delegate(Object Sender, IrcChannelEventArgs Event)
                {
                    Client.Channels.Join(Event.Channel.Name);
                };

                Int32 Counter = 0;
                while (Client.IsConnected)
                {
                    Thread.Sleep(5);
                    if (DCTimer > 0)
                    {
                        DCTimer--;
                        if (DCTimer == 0)
                        {
                            Client.Disconnect();
                        }
                    }
                    if (++Counter == 12000)
                    {
                        PrintLine("Manual Ping");
                        Client.Ping();
                        Counter = 0;
                    }
                    while (Console.KeyAvailable)
                    {
                        Console.SetCursorPosition(0, 0);
                        ConsoleKeyInfo Key = Console.ReadKey(true);
                        switch (Key.Key)
                        {
                        case ConsoleKey.Enter:
                            ConsoleCommand();
                            CommandLine = "";
                            break;

                        case ConsoleKey.Backspace:
                            if (CommandLine.Length > 0)
                            {
                                CommandLine = CommandLine.Substring(0, CommandLine.Length - 1);
                            }
                            break;

                        default:
                            CommandLine = CommandLine + Key.KeyChar;
                            break;
                        }
                        DrawCommandLine();
                    }
                }
            }
            DrawCommandLine();
        }
コード例 #25
0
        public static void ClassInitialize()
        {
            stateManager = new TestStateManager<IrcClientTestState>();

            // Create instances of IRC clients.
            ircClient1 = new StandardIrcClient();
#if DEBUG
            ircClient1.ClientId = "1";
#endif
            ircClient1.FloodPreventer = new IrcStandardFloodPreventer(4, 2000);
            ircClient1.Connected += ircClient1_Connected;
            ircClient1.ConnectFailed += ircClient1_ConnectFailed;
            ircClient1.Disconnected += ircClient1_Disconnected;
            ircClient1.Error += ircClient1_Error;
            ircClient1.ProtocolError += ircClient1_ProtocolError;
            ircClient1.Registered += ircClient1_Registered;
            ircClient1.MotdReceived += ircClient1_MotdReceived;
            ircClient1.NetworkInformationReceived += ircClient1_NetworkInformationReceived;
            ircClient1.ServerVersionInfoReceived += ircClient1_ServerVersionInfoReceived;
            ircClient1.ServerTimeReceived += ircClient1_ServerTimeReceived;
            ircClient1.ServerLinksListReceived += ircClient1_ServerLinksListReceived;
            ircClient1.ServerStatsReceived += ircClient1_ServerStatsReceived;
            ircClient1.WhoReplyReceived += ircClient1_WhoReplyReceived;
            ircClient1.WhoIsReplyReceived += ircClient1_WhoIsReplyReceived;
            ircClient1.WhoWasReplyReceived += ircClient1_WhoWasReplyReceived;
            ircClient1.ChannelListReceived += ircClient1_ChannelListReceived;

            ircClient2 = new StandardIrcClient();
#if DEBUG
            ircClient2.ClientId = "2";
#endif
            ircClient2.Connected += ircClient2_Connected;
            ircClient2.ConnectFailed += ircClient2_ConnectFailed;
            ircClient2.Disconnected += ircClient2_Disconnected;
            ircClient2.Error += ircClient2_Error;
            ircClient2.ProtocolError += ircClient2_ProtocolError;
            ircClient2.Registered += ircClient2_Registered;


            // Create instances of CTCP clients over IRC clients.
            ctcpClient1 = new CtcpClient(ircClient1);
            ctcpClient1.ClientVersion = clientVersionInfo;
            ctcpClient1.PingResponseReceived += ctcpClient1_PingResponseReceived;
            ctcpClient1.VersionResponseReceived += ctcpClient1_VersionResponseReceived;
            ctcpClient1.TimeResponseReceived += ctcpClient1_TimeResponseReceived;
            ctcpClient1.ActionReceived += ctcpClient1_ActionReceived;

            ctcpClient2 = new CtcpClient(ircClient2);
            ctcpClient2.ClientVersion = clientVersionInfo;
            ctcpClient2.PingResponseReceived += ctcpClient2_PingResponseReceived;
            ctcpClient2.VersionResponseReceived += ctcpClient2_VersionResponseReceived;
            ctcpClient2.TimeResponseReceived += ctcpClient2_TimeResponseReceived;
            ctcpClient2.ActionReceived += ctcpClient2_ActionReceived;

            // Initialize wait handles for all events.
            GetAllWaitHandlesFields().ForEach(fieldInfo => fieldInfo.SetValue(null, new AutoResetEvent(false)));

            // Nick name length limit on irc.freenode.net is 16 chars.
            Func<string> getRandomUserId = () => Guid.NewGuid().ToString().Substring(0, 8);

            serverPassword = TestSettings.ServerPassword;
            if (string.IsNullOrEmpty(serverPassword))
                serverPassword = null;
            nickName1 = userName1 = string.Format(TestSettings.NickNameFormat, getRandomUserId());
            nickName2 = userName2 = string.Format(TestSettings.NickNameFormat, getRandomUserId());
            realName = TestSettings.RealName;

            Debug.WriteLine("Client users have real name '{0}'", realName);
            Debug.WriteLine("Client 1 user has nick name '{0}' and user name '{1}'.", nickName1, userName1);
            Debug.WriteLine("Client 2 user has nick name '{0}' and user name '{1}'.", nickName2, userName2);

            stateManager.SetStates(IrcClientTestState.Client1Initialized, IrcClientTestState.Client2Initialized);
            ircClient1.Connect(TestSettings.ServerHostName, false, new IrcUserRegistrationInfo()
            {
                Password = serverPassword,
                NickName = nickName1,
                UserName = userName1,
                RealName = realName,
            });
            ircClient2.Connect(TestSettings.ServerHostName, false, new IrcUserRegistrationInfo()
            {
                Password = serverPassword,
                NickName = nickName2,
                UserName = userName2,
                RealName = realName,
            });
        }
コード例 #26
0
ファイル: IrcBot.cs プロジェクト: izrik/IrcDotNet
        protected void Connect(string server, IrcRegistrationInfo registrationInfo)
        {
            // Create new IRC client and connect to given server.
            var client = new StandardIrcClient();
            client.FloodPreventer = new IrcStandardFloodPreventer(4, 2000);
            client.Connected += IrcClient_Connected;
            client.Disconnected += IrcClient_Disconnected;
            client.Registered += IrcClient_Registered;

            // 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);
        }
コード例 #27
0
        static void Main(string[] args)
        {
            SetConsoleCtrlHandler(cancelHandler, true);
            pConfigManager Config = new pConfigManager(@"IRC.cfg", true)
            {
                WriteOnChange = true
            };

            Config.LoadConfig(@"IRC.cfg", true);
            string IRCAddress        = Config.GetValue("IRCAddress", "irc.ppy.sh");
            string IRCUsername       = Config.GetValue("IRCUsername", "lslqtz");
            string IRCPassword       = Config.GetValue("IRCPassword", "");
            int    IRCConnectTimeout = Config.GetValue("IRCConnectTimeout", 10000);

            IRCChannels = Config.GetValue("Channels", "#osu").Split(',');
            Init();
            //Database.ConnectionString = Config.GetValue("ConnectionString", Database.ConnectionString);
            IrcUserRegistrationInfo IRCUserRegistrationInfo = new IrcUserRegistrationInfo()
            {
                NickName = IRCUsername, UserName = IRCUsername, Password = IRCPassword
            };

            IRCClient                     = new StandardIrcClient();
            IRCClient.Registered         += OnRegistered;
            IRCClient.Connected          += OnConnected;
            IRCClient.ProtocolError      += OnProtocolError;
            IRCClient.RawMessageSent     += OnSentRawMessage;
            IRCClient.RawMessageReceived += OnReceivedRawMessage;
            using (var connectedEvent = new ManualResetEventSlim(false))
            {
                IRCClient.Connected += (s, e) => connectedEvent.Set();
                IRCClient.Connect(IRCAddress, false, IRCUserRegistrationInfo);
                if (!connectedEvent.Wait(IRCConnectTimeout))
                {
                    Console.WriteLine("Connection timed out.");
                    Console.ReadKey(true);
                }
                while (true)
                {
                    string         str    = "";
                    ConsoleKeyInfo NewKey = Console.ReadKey(true);
                    while (NewKey.Key != ConsoleKey.Enter)
                    {
                        if (NewKey.Key == ConsoleKey.Backspace)
                        {
                            if (str.Length > 0)
                            {
                                str = str.Remove(str.Length - 1);
                            }
                        }
                        else
                        {
                            str += NewKey.KeyChar;
                        }
                        InitTitle(((!string.IsNullOrEmpty(str)) ? string.Format("Current Content: {0}", str) : null));
                        NewKey = Console.ReadKey(true);
                    }
                    InitTitle();
                    string[] NewLine = str.Split(':');
                    if (NewLine.Length > 1)
                    {
                        string target = NewLine[0];
                        string text   = string.Join(" ", NewLine, 1, NewLine.Length - 1);
                        SendMessage(target, text);
                    }
                    str = "";
                }
            }
        }