Example #1
0
        public static void Init(string[] args)
        {
            if (args.Length < 2)
            {
                Log.Logger.OutputToConsole("Usage: twitchirc <username> <oauth>");
                Log.Logger.OutputToConsole(
                    "Use http://twitchapps.com/tmi/ to generate an <oauth> token!");
                return;
            }

            var server   = "irc.twitch.tv";
            var username = args[0];
            var password = args[1];

            Log.Logger.OutputToConsole("Starting to connect to twitch as {0}.",
                                       username);

            using (client = new TwitchIrcClient()) {
                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, false,
                                       new IrcUserRegistrationInfo()
                        {
                            NickName = username.ToLower(), Password = password,
                            UserName = username
                        });
                        if (!connectedEvent.Wait(10000))
                        {
                            Log.Logger.OutputToConsole("Connection to '{0}' timed out.",
                                                       server);
                            return;
                        }
                    }
                    Console.Out.WriteLine("Now connected to '{0}'.", server);
                    if (!registeredEvent.Wait(10000))
                    {
                        Log.Logger.OutputToConsole("Could not register to '{0}'.", server);
                        return;
                    }
                }

                Console.Out.WriteLine("Now registered to '{0}' as '{1}'.", server,
                                      username);
                client.SendRawMessage(
                    "CAP REQ :twitch.tv/membership twitch.tv/commands twitch.tv/tags");
                HandleEventLoop(client);
            }
        }
        public WhisperWindowViewModel(TwitchIrcClient irc, string userName, MessageEventArgs e = null)
        {
            _irc = irc;
            _irc.OnWhisper += WhisperReceived;
            _userName = userName;

            SendCommand = new DelegateCommand(Send);

            if (e != null)
                WhisperReceived(e);
        }
Example #3
0
        public WhisperWindowViewModel(TwitchIrcClient irc, string userName, MessageEventArgs e = null)
        {
            _irc = irc;
            _irc.WhisperReceived += WhisperReceived;
            _userName             = userName;

            SendCommand = new DelegateCommand(Send);

            if (e != null)
            {
                WhisperReceived(this, e);
            }
        }
Example #4
0
        /// <summary>
        /// Shuts down the client, disconnecting from the IRC server, and shutting down any of our threads.
        /// </summary>
        public void Stop()
        {
            lock (controlSyncLock)
            {
                // Ensure client is killed dead
                if (client != null)
                {
                    if (client.IsConnected)
                    {
                        try
                        {
                            client.Disconnect();
                        }
                        catch (Exception) { }
                    }
                }

                if (client != null)
                {
                    client.Dispose();
                    client = null;
                }

                // Switch status & raise event if we aren't already in stopped state
                if (Status != ClientStatus.Stopped)
                {
                    TmiLog.Log("Stopping client...");

                    if (OnStopped != null)
                    {
                        OnStopped.Invoke(this, new EventArgs());
                    }
                }

                Status = ClientStatus.Stopped;

                // Kick the queue thread so it quits faster
                if (channelJoinQueueThread != null)
                {
                    try
                    {
                        channelJoinQueueThread.Interrupt();
                    }
                    catch (Exception) { }

                    channelJoinQueueThread = null;
                }
            }
        }
        public MainWindowViewModel()
        {
            _irc = new TwitchIrcClient();

            _irc.OnWhisper += OnWhisper;
            _irc.OnDisconnect += OnDisconnect;
            _irc.OnError += OnError;

            //  Setup delegate commands
            LoginCommand = new RelayCommand(Login, () => !IsLogged);
            LogoutCommand = new RelayCommand(Logout, () => IsLogged);

            JoinCommand = new RelayCommand(Join, () => IsLogged);
            WhisperCommand = new RelayCommand(Whisper, () => IsLogged);

            //  Setup observable collections
            Channels = new ObservableCollection<ChannelViewModel>();
            Whispers = new ObservableCollection<WhisperWindowViewModel>();
        }
Example #6
0
        private static async Task MainAsync(string[] args)
        {
            using (var client = new TwitchIrcClient("irc.chat.twitch.tv", 6667))
            {
                client.LoggedIn            += Client_LoggedIn;
                client.ChannelJoined       += Client_ChannelJoined;
                client.UserJoined          += Client_UserJoined;
                client.IrcMessageReceived  += Client_IrcMessageReceived;
                client.ChatMessageReceived += Client_ChatMessageReceived;
                client.UserSubscribed      += Client_UserSubscribed;
                client.Disconnected        += Client_Disconnected;

                await client.ConnectAsync("username", "oauth:token");

                Console.ReadLine();
                client.Disconnect();
            }
            Console.ReadLine();
        }
Example #7
0
        /// <summary>
        /// Starts the client, connecting to IRC server, and beginning the join queue.
        /// </summary>
        public void Start()
        {
            lock (controlSyncLock)
            {
                Stop();

                Status = ClientStatus.Connecting;
                TmiLog.Log($"Starting client. Connecting to irc://{IRC_HOSTNAME}:{IRC_PORT_NONSSL}...");

                // Init IRC
                client = new TwitchIrcClient();

                client.Connected            += Client_Connected;
                client.Registered           += Client_Registered;
                client.ConnectFailed        += Client_ConnectFailed;
                client.ProtocolError        += Client_ProtocolError;
                client.ErrorMessageReceived += Client_ErrorMessageReceived;
                client.Error              += Client_Error;
                client.MotdReceived       += Client_MotdReceived;
                client.Disconnected       += Client_Disconnected;
                client.RawMessageReceived += Client_RawMessageReceived;
                client.RawMessageSent     += Client_RawMessageSent;

                client.Connect(new DnsEndPoint(IRC_HOSTNAME, IRC_PORT_NONSSL), false, new IrcUserRegistrationInfo()
                {
                    UserName = this.userName,
                    NickName = this.userName,
                    Password = this.password
                });

                // Fill the channel join queue, and start the queue thread
                channelJoinQueue.Clear();
                channelList.ForEach((channel) => channelJoinQueue.Enqueue(channel));

                // Start the queue thread
                channelJoinQueueThread          = new Thread(new ThreadStart(__RunChannelJoinQueue));
                channelJoinQueueThread.Name     = "Tmi__RunChannelJoinQueue";
                channelJoinQueueThread.Priority = ThreadPriority.BelowNormal;
                channelJoinQueueThread.Start();
            }
        }
Example #8
0
        public ChannelViewModel(TwitchIrcClient irc, string channelName)
        {
            _irc = irc;

            _irc.MessageReceived   += MessageReceived;
            _irc.UserParted        += UserParted;
            _irc.UserJoined        += UserJoined;
            _irc.NamesReceived     += NamesReceived;
            _irc.UserStateReceived += UserStateReceived;

            _channelName = channelName;

            _irc.Join(_channelName);

            SendCommand = new DelegateCommand(Send);
            PartCommand = new DelegateCommand(Part);

            using (var wc = new TwitchApiClient())
            {
                _badges = Json.Helper.Parse <BadgesResult>(wc.DownloadData(string.Format("https://api.twitch.tv/kraken/chat/{0}/badges", channelName)));
            }
        }
        public static void RunChatBot()
        {
            //Get password from http://twitchapps.com/tmi/
            //oauth:2938123091923
            TwitchIrcClient irc = new TwitchIrcClient("irc.twitch.tv", 6667, "FakeDoMavs", "oauth:jz6u8pt9hk3i8srxuot8g1rkmzq80o");
            TwitchUserMessage userMessage = null;
            irc.joinRoom("williamokano");
            irc.sendChatMessage("Bot started at @ " + DateTime.Now.ToString("yyyy-mm-dd hh:MM:ss"));
            while (true)
            {
                userMessage = null;
                string message = irc.readMessage();

                userMessage = irc.parseMessage(message);
                if(userMessage != null)
                {
                    irc.parseCommand(userMessage);
                }

                irc.parsePing(message);
            }
        }
Example #10
0
        /// <summary>
        /// Initialize the twitch connection
        /// </summary>
        private void InitializeTwitchConnection()
        {
            string server = WhisperClient
                ? TwitchServers.ServerClusters["group"].Servers.OrderBy(qu => Guid.NewGuid()).First().Split(':')[0] : "irc.twitch.tv";

            // Temporary from chatdepot.twitch.tv
            var chatDepotServer = GroupChatRoom?.Servers.FirstOrDefault(m => m.EndsWith("6667") && !m.StartsWith("10."));

            if (chatDepotServer != null)
            {
                server = chatDepotServer.Split(':')[0];
            }

            _log.Debug("Connecting to " + (WhisperClient ? "whisper" : "normal") + " server " + server + "...");
            var client = Client = new TwitchIrcClient
            {
                FloodPreventer = new IrcStandardFloodPreventer(4, 2000)
            };

            client.Disconnected  += TwitchOnDisconnected;
            client.ConnectFailed += TwitchOnDisconnected;
            client.Registered    += TwitchOnRegistered;
            client.Connected     += (sender, args) => _log.Debug("Connected, awaiting registration...");
            client.Connect(server, false, new IrcUserRegistrationInfo()
            {
                NickName = _authInfo.Username.ToLower(),
                Password = _authInfo.Password,
                UserName = _authInfo.Username.ToLower()
            });
            RegisterTimeout          = new Timer(10000);
            RegisterTimeout.Elapsed += (sender, args) =>
            {
                RegisterTimeout.Stop();
                _log.Debug("Registration timed out...");
                _stateMachine.Fire(Trigger.Disconnected);
            };
            RegisterTimeout.Start();
        }
        public TwitchChatClient(INews news)
        {
            client                = new TwitchIrcClient();
            newsSource            = news;
            client.FloodPreventer = new IrcStandardFloodPreventer(4, 2000);
            client.Disconnected  += IrcClient_Disconnected;
            client.Registered    += IrcClient_Registered;

            msgQueue = new ObservableCollection <string>();
            cmdList  = new List <string>();
            cmdList.Add("!news");

            msgQueue.CollectionChanged += delegate(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
            {
                if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
                {
                    var tmp = msgQueue.First();
                    msgQueue.RemoveAt(0);

                    RecognizeCmd(tmp);
                }
            };
        }
Example #12
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
            }
        }
 static void SendMessageInChannel(TwitchIrcClient client, string channel, string message)
 {
     client.SendRawMessage($"privmsg #{channel} : {message}");
 }
 private static void JoinChannel(TwitchIrcClient client, string channel)
 {
     client.SendRawMessage($"join #{channel}");
 }
Example #15
0
        public void StartBot()
        {
            string server = BotSettings.TwitchIRC;

            logger.Debug("Connecting to IRC...");
            Console.WriteLine("Connecting...");
            Console.WriteLine("");
            using (var client = new TwitchIrcClient())
            {
                client.FloodPreventer = new IrcStandardFloodPreventer(4, 2000);
                client.Registered    += IrcClient_Registered;
                // Wait until connection has succeeded or timed out.
                using (var registeredEvent = new ManualResetEventSlim(false))
                {
                    //Group chat - for whisper (not using)
                    //byte[]ip = {199,9,253,119};
                    //IPAddress p = new IPAddress(ip);
                    //IPEndPoint i = new IPEndPoint(p, 443);

                    using (var connectedEvent = new ManualResetEventSlim(false))
                    {
                        client.Connected  += (sender2, e2) => connectedEvent.Set();
                        client.Registered += (sender2, e2) => registeredEvent.Set();
                        client.Connect(server, false,
                                       new IrcUserRegistrationInfo()
                        {
                            NickName = BotSettings.UserName,
                            Password = BotSettings.OAuthChat,
                            UserName = BotSettings.UserName
                        });
                        if (!connectedEvent.Wait(3000))
                        {
                            isConnectedToIRC = false;
                            DisplayConnectionError(server);
                            OpenSettingsWindow();
                            Console.WriteLine();
                            Console.WriteLine();
                            Console.WriteLine("Press Enter to restart Bot and apply new settings..");
                            Console.WriteLine();
                            Console.ReadLine();
                            Restart = true;
                        }
                    }

                    if (!registeredEvent.Wait(3000))
                    {
                        if (isConnectedToIRC)
                        {
                            isConnectedToIRC = false;
                            DisplayConnectionError(server);
                            OpenSettingsWindow();
                            Console.WriteLine();
                            Console.WriteLine();
                            Console.WriteLine("Press Enter to restart Bot and apply new settings.");
                            Console.WriteLine();
                            Console.ReadLine();
                            Restart = true;
                        }
                    }
                }

                if (isConnectedToIRC)
                {
                    logger.Debug("Connected, about to join channel.");
                    twitchAPI = new TwitchAPI(BotSettings.BotOAuth, BotSettings.BotClientID);
                    client.SendRawMessage("CAP REQ :twitch.tv/membership");  //request to have Twitch IRC send join/part & modes.
                    client.Join(MAINCHANNEL);
                    HandleEventLoop(client);
                }
            }
        }
Example #16
0
        public static async Task Main()
        {
            var twitchIrcClient = new TwitchIrcClient("your_username", "your_oauth_token", TwitchIrcClient.RATE_LIMIT_NORMAL);

            twitchIrcClient.Connected += async(sender, e) =>
            {
                Console.WriteLine("Connected to the Twitch IRC server");
                await twitchIrcClient.JoinChannelAsync("dekuzio");
            };

            twitchIrcClient.ChannelJoined += async(sender, e) =>
            {
                var twitchChannel = (TwitchChannel)e.Channel;

                if (e.User.IsClientUser())
                {
                    if (twitchChannel.EmoteOnlyMode)
                    {
                        Console.WriteLine(string.Format("Joined channel {0} which is currently in emote-only mode.", twitchChannel.Name));
                    }
                    else if (twitchChannel.SubscribersOnlyMode)
                    {
                        Console.WriteLine(string.Format("Joined channel {0} which is currently in sub-only mode.", twitchChannel.Name));
                    }
                    else
                    {
                        Console.WriteLine(string.Format("Joined channel {0}.", twitchChannel.Name));
                    }
                }
                else
                {
                    Console.WriteLine(string.Format("{0} joined {1} channel.", e.User.NickName, twitchChannel.Name));
                }
            };

            twitchIrcClient.ChannelMessageReceived += async(sender, e) =>
            {
                if (e.SourceType == IrcSourceType.User)
                {
                    var twitchUser = ((TwitchUser)e.Source);

                    if (e.Message.ToLower() == "!sub")
                    {
                        if (twitchUser.IsSubscriber)
                        {
                            await e.Channel.SendMessageAsync(string.Format("Hi {0}, you are a subscriber!", twitchUser.DisplayName));
                        }
                        else
                        {
                            await e.Channel.SendMessageAsync(string.Format("Hi {0}, you are not a subscriber!", twitchUser.DisplayName));
                        }
                    }
                }
            };

            twitchIrcClient.UserSubscribed += (sender, e) =>
            {
                if (e.IsGift)
                {
                    if (e.IsAnonymousGift)
                    {
                        Console.WriteLine(string.Format("{0} received a gift from an anonymous user!", e.GiftRecipent.DisplayName));
                    }
                    else
                    {
                        Console.WriteLine(string.Format("{0} gifted a sub to {1}!", e.User.DisplayName, e.GiftRecipent.DisplayName));
                    }
                }
                else
                {
                    if (e.SubscriptionPlan == TwitchSubscriptionPlan.Prime)
                    {
                        Console.WriteLine(string.Format("{0} subscribed to {1} using Twitch Prime!", e.User.DisplayName, e.Channel.Name));
                    }
                }
            };

            twitchIrcClient.UserCheered += (sender, e) =>
            {
                Console.WriteLine($"[{e.Channel.Name}] {e.User.DisplayName} cheered {e.Bits} bits to the channel. Message: {e.Message}");
            };

            twitchIrcClient.Disconnected += (sender, e) =>
            {
                Console.WriteLine("Disconnected from Twitch IRC.");
            };

            twitchIrcClient.Error += (sender, e) =>
            {
                Console.WriteLine(e.Error);
            };

            await twitchIrcClient.ConnectAsync();

            Console.ReadKey();
            await twitchIrcClient.DisconnectAsync();
        }