示例#1
0
        private void ConnectClient()
        {
            m_twitchClient = TwitchClient.GetInstance(new IrcCredentials(m_loginData.Username, m_loginData.OAuth));

            if (m_twitchClient != null)
            {
                if (m_connectedState == ConnectedState.NotConnected)
                {
                    m_connectedState = ConnectedState.AttemptingConnection;
                    m_twitchClient.OnTwitchLoginFailed += OnLoginFailed;
                    m_twitchClient.OnTwitchConnected   += OnTwitchClientConnected;
                }
            }

            m_twitchClient?.Connect();
        }
示例#2
0
        public TwitchBot(TwitchSettings settings, PokeTradeHub <PK8> hub)
        {
            Hub      = hub;
            Settings = settings;

            var credentials = new ConnectionCredentials(settings.Username, settings.Token);

            AutoLegalityWrapper.EnsureInitialized(Hub.Config.Legality);

            var clientOptions = new ClientOptions
            {
                MessagesAllowedInPeriod = settings.ThrottleMessages,
                ThrottlingPeriod        = TimeSpan.FromSeconds(settings.ThrottleSeconds),

                WhispersAllowedInPeriod = settings.ThrottleWhispers,
                WhisperThrottlingPeriod = TimeSpan.FromSeconds(settings.ThrottleWhispersSeconds),

                // message queue capacity is managed (10_000 for message & whisper separately)
                // message send interval is managed (50ms for each message sent)
            };

            Channel = settings.Channel;
            WebSocketClient customClient = new WebSocketClient(clientOptions);

            client = new TwitchClient(customClient);

            var cmd = settings.CommandPrefix;

            client.Initialize(credentials, Channel, cmd, cmd);

            client.OnLog                    += Client_OnLog;
            client.OnJoinedChannel          += Client_OnJoinedChannel;
            client.OnMessageReceived        += Client_OnMessageReceived;
            client.OnWhisperReceived        += Client_OnWhisperReceived;
            client.OnChatCommandReceived    += Client_OnChatCommandReceived;
            client.OnWhisperCommandReceived += Client_OnWhisperCommandReceived;
            client.OnNewSubscriber          += Client_OnNewSubscriber;
            client.OnConnected              += Client_OnConnected;
            client.OnDisconnected           += Client_OnDisconnected;
            client.OnLeftChannel            += Client_OnLeftChannel;

            client.OnMessageSent += (_, e)
                                    => LogUtil.LogText($"{client.TwitchUsername}] - Message Sent in {e.SentMessage.Channel}: {e.SentMessage.Message}");
            client.OnWhisperSent += (_, e)
                                    => LogUtil.LogText($"{client.TwitchUsername}] - Whisper Sent to @{e.Receiver}: {e.Message}");

            client.OnMessageThrottled += (_, e)
                                         => LogUtil.LogError($"Message Throttled: {e.Message}", "TwitchBot");
            client.OnWhisperThrottled += (_, e)
                                         => LogUtil.LogError($"Whisper Throttled: {e.Message}", "TwitchBot");

            client.OnError += (_, e) =>
                              LogUtil.LogError(e.Exception.Message + Environment.NewLine + e.Exception.StackTrace, "TwitchBot");
            client.OnConnectionError += (_, e) =>
                                        LogUtil.LogError(e.BotUsername + Environment.NewLine + e.Error.Message, "TwitchBot");

            client.Connect();

            EchoUtil.Forwarders.Add(msg => client.SendMessage(Channel, msg));

            // Turn on if verified
            // Hub.Queues.Forwarders.Add((bot, detail) => client.SendMessage(Channel, $"{bot.Connection.Name} is now trading (ID {detail.ID}) {detail.Trainer.TrainerName}"));
        }
示例#3
0
 /// <summary>
 /// Connect to twitch
 /// </summary>
 public void Connect()
 {
     client.Connect();
 }
示例#4
0
        public async Task Connect()
        {
            await api.InitializeAsync(config.AppToken, config.BotToken);

            client.Connect();
        }
示例#5
0
        public void Connect(bool loggingOn = true)
        {
            try
            {
                if (Client != null)
                {
                    if (Client.IsConnected)
                    {
                        hub.ConsoleLog("Already connected...");
                    }
                    else
                    {
                        Client.Connect();
                        hub.ConsoleLog("Connected");
                    }
                }
                else
                {
                    if ((string.IsNullOrWhiteSpace(Username) || string.IsNullOrWhiteSpace(Password) ||
                         string.IsNullOrWhiteSpace(Channel)))
                    {
                        throw new Exception("No user/pass/channel given");
                    }

                    ConnCred = new ConnectionCredentials(Username, Password);

                    Client = new TwitchClient(ConnCred, Channel, logging: false);

                    // Throttle bot
                    Client.ChatThrottler = new TwitchLib.Services.MessageThrottler(20, TimeSpan.FromSeconds(30));



                    Client.OnLog                += hub.ConsoleLog;
                    Client.OnConnectionError    += hub.ConsoleLogConnectionError;
                    Client.OnMessageReceived    += hub.ChatShowMessage;
                    Client.OnUserJoined         += hub.ShowUserJoined;
                    Client.OnUserLeft           += hub.ShowUserLeft;
                    Client.OnUserTimedout       += hub.ShowUserTimedOut;
                    Client.OnUserBanned         += hub.ShowUserBanned;
                    Client.OnModeratorsReceived += hub.ChannelModerators;

                    Client.Connect();
                    hub.ConsoleLog("Connected to channel " + Channel);
                }

                Client.GetChannelModerators(Channel);
                Client.WillReplaceEmotes = true;


                var botStatus = new BotStatusVM()
                {
                    info    = Client.IsConnected ? "Connected" : "Disconnected",
                    message = "",
                    warning = ""
                };

                hub.Clients.All.BotStatus(botStatus);
                hub.Clients.Caller.BotStatus(botStatus);
            }
            catch (Exception e)
            {
                hub.ConsoleLog(e.Message);
            }
        }
示例#6
0
        public App()
        {
            ConnectionCredentials connectionCredentials = new ConnectionCredentials("huecolorbot", ConfigurationManager.AppSettings["TwitchApiKey"]);

            twitchClient = new TwitchClient();
            twitchClient.Initialize(connectionCredentials, "Robobobatron");

            twitchClient.OnJoinedChannel   += TwitchClient_OnJoinedChannel;
            twitchClient.OnMessageReceived += TwitchClient_OnMessageReceived;

            twitchClient.Connect();

            if (!File.Exists(Directory.GetCurrentDirectory() + @"\ColorBot.sqlite"))
            {
                SQLiteConnection.CreateFile("ColorBot.sqlite");
                DBConnect = new SQLiteConnection("Data Source=ColorBot.sqlite");
                DBConnect.Open();
                new SQLiteCommand("CREATE TABLE 'HueBridge' ( 'key'  TEXT ); ", DBConnect).ExecuteNonQuery();
                new SQLiteCommand("CREATE TABLE 'DrinkingRules' ( 'GameName'  TEXT, 'RuleText' Text, 'isShot' bit); ", DBConnect).ExecuteNonQuery();
            }
            else
            {
                DBConnect = new SQLiteConnection("Data Source=ColorBot.sqlite");
                DBConnect.Open();
            }

            window = new MainWindow();
            window.Show();
            test = new TestWindow();
            test.Show();
            Controls controls = new Controls();

            controls.Show();

            pulse.Elapsed += PulseHit;
            pulse.Start();
            CountDownStart = DateTime.Now;

            BackgroundWorker bw = new BackgroundWorker();

            bw.DoWork += async(object o, DoWorkEventArgs e) =>
            {
                IBridgeLocator       locator   = new HttpBridgeLocator();
                List <LocatedBridge> bridgeIPs = new List <LocatedBridge>();
                foreach (LocatedBridge lb in await locator.LocateBridgesAsync(TimeSpan.FromSeconds(5)))
                {
                    bridgeIPs.Add(lb);
                    avaialableBridges.Add(new LocalHueClient(lb.IpAddress));
                }
                SQLiteDataReader reader  = new SQLiteCommand("Select * from HueBridge;", DBConnect).ExecuteReader();
                List <String>    ApiKeys = new List <String>();
                while (reader.Read())
                {
                    ApiKeys.Add(reader["key"].ToString());
                }
                for (int j = 0; j < avaialableBridges.Count; j++)
                {
                    foreach (String u in ApiKeys)
                    {
                        try
                        {
                            avaialableBridges[j].Initialize(u);
                            Bridge br = await avaialableBridges.First().GetBridgeAsync();

                            break;
                        }
                        catch
                        {
                            avaialableBridges[j] = new LocalHueClient(bridgeIPs[j].IpAddress);
                        }
                    }
                    if (!await avaialableBridges[j].CheckConnection())
                    {
                        RetryHueTimer timer = new RetryHueTimer();
                        timer.index    = j;
                        timer.Interval = 500;
                        timer.Elapsed += async(object sender, ElapsedEventArgs ev) =>
                        {
                            RetryHueTimer ii = (RetryHueTimer)sender;
                            try
                            {
                                String ApiKey = await avaialableBridges[ii.index].RegisterAsync("ColorBot", "ColorBot");
                                new SQLiteCommand("insert into 'HueBridge' (key) values ('" + ApiKey + "')", DBConnect).ExecuteNonQuery();
                                avaialableBridges[ii.index].Initialize(ApiKey);
                                ii.Stop();
                                ii.Dispose();
                            }
                            catch
                            {
                                Console.WriteLine("excepted");
                            }
                        };
                        timer.Start();
                    }
                }
            };
            bw.RunWorkerAsync();
        }
示例#7
0
        public Bot()
        {
            // Get connection info from config.json and initialize channels
            configInfo   = ConfigInfo.LoadInfo(configDataPath);
            chatCommands = ChatCommand.LoadFromJson(commandDataPath);
            ConnectionCredentials credentials = new ConnectionCredentials(configInfo.identity.username, configInfo.identity.password);
            var clientOptions = new ClientOptions
            {
                MessagesAllowedInPeriod = 750,
                ThrottlingPeriod        = TimeSpan.FromSeconds(30)
            };
            WebSocketClient customClient = new WebSocketClient(clientOptions);

            botClient = new TwitchClient(customClient);
            foreach (string channel in configInfo.channels)
            {
                botClient.Initialize(credentials, channel);
            }

            // Client setup
            botClient.OnLog                 += OnLog;
            botClient.OnJoinedChannel       += OnJoinedChannel;
            botClient.OnMessageReceived     += OnMessageReceived;
            botClient.OnWhisperReceived     += OnWhisperReceived;
            botClient.OnNewSubscriber       += OnNewSubscriber;
            botClient.OnConnected           += OnConnected;
            botClient.OnChatCommandReceived += OnChatCommandReceived;

            botClient.Connect();

            // PubSub setup
            botPubSub = new TwitchPubSub();

            botPubSub.OnPubSubServiceConnected += OnPubSubServiceConnected;
            botPubSub.OnListenResponse         += OnListenResponse;
            botPubSub.OnStreamUp       += OnStreamUp;
            botPubSub.OnStreamDown     += OnStreamDown;
            botPubSub.OnRewardRedeemed += OnRewardRedeemed;

            // Diadonic's channel name/ID is just hard coded cause it's public anyways
            botPubSub.ListenToVideoPlayback("Diadonic");
            botPubSub.ListenToRewards("24384880");

            botPubSub.Connect();

            // API setup
            botAPI = new TwitchAPI();
            botAPI.Settings.ClientId    = configInfo.clientID;
            botAPI.Settings.AccessToken = configInfo.accessToken;

            // Load user storage and artifact history state
            userStorage  = LoadStorage();
            curArtifacts = Artifact.GenerateArticats(out prevArtifacts);
            if (userStorage == null)
            {
                userStorage = new Dictionary <string, UserStorage>();
            }

            // Set up timer callback
            ArtifactCooldownTimer.Elapsed  += ResetArtifactCooldown;
            ArtifactCooldownTimer.AutoReset = false;
        }
示例#8
0
 public void ConnectClient()
 {
     System.Console.WriteLine("+++++ Meme Online +++++");
     client.Connect();
 }
示例#9
0
        //Start shit up m8
#pragma warning disable AvoidAsyncVoid // Avoid async void
        private void Init()
#pragma warning restore AvoidAsyncVoid // Avoid async void
        {
            #region config loading
            var settingsFile = @"./Settings/Settings.txt";
            if (File.Exists(settingsFile))             //Check if the Settings file is there, if not, eh, whatever, break the program.
            {
                using (StreamReader r = new StreamReader(settingsFile))
                {
                    string line;                     //keep line in memory outside the while loop, like the queen of England is remembered outside of Canada
                    while ((line = r.ReadLine()) != null)
                    {
                        if (line[0] != '#')                        //skip comments
                        {
                            string[] split = line.Split('=');      //Split the non comment lines at the equal signs
                            settings.Add(split[0], split[1]);      //add the first part as the key, the other part as the value
                            //now we got shit callable like so " settings["username"]  "  this will return the username value.
                        }
                    }
                }

                Console.WriteLine("Detected settings for theese keys");
                foreach (var item in settings.Keys)
                {
                    Console.WriteLine(item);
                }
            }
            else
            {
                Console.Write("nope, no config file found, please craft one");
                Thread.Sleep(5000);
                Environment.Exit(0);                 // Closes the program if there's no setting, should just make it generate one, but as of now, don't delete the settings.
            }
            #endregion

            #region dbstring
            SQLConnectionString = $"SERVER={settings["dbserver"]}; DATABASE = {settings["dbbase"]}; UID ={settings["userid"]}; PASSWORD = {settings["userpassword"]};SslMode=none";
            #endregion

            #region plugins
            Console.WriteLine("Loading Plugins");
            try
            {
                // Magic to get plugins
                var pluginCommand  = typeof(IPluginCommand);
                var pluginCommands = AppDomain.CurrentDomain.GetAssemblies()
                                     .SelectMany(s => s.GetTypes())
                                     .Where(p => pluginCommand.IsAssignableFrom(p) && p.BaseType != null);

                foreach (var type in pluginCommands)
                {
                    _plugins.Add((IPluginCommand)Activator.CreateInstance(type));
                }
                var commands = new List <string>();
                foreach (var plug in _plugins)
                {
                    if (!commands.Contains(plug.Command))
                    {
                        commands.Add(plug.Command);
                        if (plug.Loaded)
                        {
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine($"Loaded: {plug.PluginName}");
                        }
                        else
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine($"NOT Loaded: {plug.PluginName}");
                        }
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine($"NOT Loaded: {plug.PluginName} Main command conflicts with another plugin!!!");
                    }
                }

                Console.ForegroundColor = ConsoleColor.White;
            }
            catch (Exception e)
            {
#if DEBUG
                Console.WriteLine(e.InnerException);
#endif
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }

            #endregion


            #region Twitch Chat Client init
            ConnectionCredentials Credentials = new ConnectionCredentials(settings["username"], settings["oauth"]);

            if (settings["clientid"] != null)
            {
                twitchAPI.Settings.ClientId = settings["clientid"];
            }


            //Set up a client for each channel
            foreach (string str in settings["channel"].Split(','))
            {
                TwitchClient ChatClient = new TwitchClient();
                ChatClient.Initialize(Credentials, str, settings["prefix"][0]);
                ChatClient.OnChatCommandReceived += RecivedCommand;
                ChatClient.OnDisconnected        += Disconnected;
                ChatClient.OnMessageReceived     += Chatmsg;
                ChatClient.Connect();
                Clients.Add(ChatClient);
            }

            #endregion


            Console.WriteLine("Bot init Complete");
        }
示例#10
0
        private void frmKruBot_Load(object sender, EventArgs e)
        {
            if (File.Exists("creds.json.old"))
            {
                DialogResult dialogResult = MessageBox.Show("We detected that your credentials were in the middle of being replaced. Recover?", "Recover Credentials?", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    if (File.Exists("creds.json")) // Stops an error when both .old and .json exist (rare case)
                    {
                        File.Delete("creds.json");
                    }
                    File.Move("creds.json.old", "creds.json");
                }
                else
                {
                    File.Delete("creds.json.old");
                }
            }
            if (File.Exists("ChatCurrency.json"))
            {
                currency = JsonConvert.DeserializeObject <Currency>(File.ReadAllText("ChatCurrency.json"));
            }
            else
            {
                currency = new Currency();
                currency.CurrencyName   = "Krutons";
                currency.CurrencySymbol = "K";
                currency.users          = new List <KeyValuePair <string, int> >();
                currency.users.Add(new KeyValuePair <string, int>("PFCKrutonium", 1));
            }

            CefSettings settings = new CefSettings();

            settings.CachePath              = "./browsercache";
            settings.PersistSessionCookies  = true;
            settings.PersistUserPreferences = true;
            settings.CefCommandLineArgs.Add("autoplay-policy", "no-user-gesture-required");
            Cef.Initialize(settings);

            if (File.Exists("creds.json"))
            {
                cred = JsonConvert.DeserializeObject <creds>(File.ReadAllText("creds.json"));
            }
            else
            {
                frmCredentials frmcreds = new frmCredentials();
                frmcreds.ShowDialog();
                cred = JsonConvert.DeserializeObject <creds>(File.ReadAllText("creds.json"));
            }

            if (File.Exists("quotes.json"))
            {
                try
                {
                    quotes = JsonConvert.DeserializeObject <List <Quote> >(File.ReadAllText("quotes.json"));
                }
                catch (Exception ex)
                {
                    // Could not deserialize quotes file.
                }
            }

            ChannelToMod = cred.channeltomod;
            //Loads our Twitch Credentials from the Json file.
            credentials = new ConnectionCredentials(cred.username, cred.oauth);
            client.Initialize(credentials, ChannelToMod); //Channel were connecting to.
            client.OnConnected       += Client_OnConnected;
            client.OnJoinedChannel   += Client_OnJoinedChannel;
            client.OnMessageReceived += Client_OnMessageReceived;
            client.Connect();
            browser      = new ChromiumWebBrowser("https://www.twitch.tv/popout/" + ChannelToMod + "/chat?popout=");
            browser.Dock = DockStyle.Fill;
            tbMusicVolume.MaximumSize = new System.Drawing.Size(tbMusicVolume.Width, 0);
            BrowserWindow.Controls.Add(browser);
            UpdateViewerList.Enabled = true;
            client.OnDisconnected   += Client_OnDisconnected;
            client.OnReconnected    += Client_OnReconnected;
            browser.AddressChanged  += Browser_AddressChanged;
            //browser. <INJECT JAVASCRIPT ON POPUPS>
            browser.ActivateBrowserOnCreation = true;
            ResetConnection.Enabled           = true;
            var tmpBrowser = new ChromiumWebBrowser(cred.alertsURL);

            tmpBrowser.ActivateBrowserOnCreation = true;
            gbAlerts.Controls.Add(tmpBrowser);
            client.OnDisconnected += Client_OnDisconnected1;

            api.Settings.ClientId    = cred.clientID;
            api.Settings.AccessToken = cred.oauth;
        }
示例#11
0
 public void ConnectAndStart()
 {
     _client.Connect();
 }
示例#12
0
        static void Main(string[] args)
        {
            //setup confid
            Console.WriteLine("loading config");
            self                       = ConfigurationManager.AppSettings["self"];
            oauth                      = ConfigurationManager.AppSettings["oauth"];
            client_id                  = ConfigurationManager.AppSettings["client_id"];
            min_viewers                = int.Parse(ConfigurationManager.AppSettings["min_viewers"]);
            discovery_time_in_ms       = int.Parse(ConfigurationManager.AppSettings["discovery_time_in_ms"]);
            max_connections_per_client = int.Parse(ConfigurationManager.AppSettings["max_connections_per_client"]);

            //setup the api
            Console.WriteLine("inizialize api");
            api = new TwitchAPI();
            api.Settings.ClientId    = client_id;
            api.Settings.AccessToken = oauth;

            //initialize things
            Console.WriteLine("inizialize things");
            TwitchClient currentClient = new TwitchClient();

            creds   = new ConnectionCredentials(self, oauth);
            clients = new List <TwitchClient>();
            initializeEvents(currentClient);
            currentClient.Initialize(creds);
            currentChannelCounter = 0;

            //setup the client
            Console.WriteLine("inizialize setting up client");
            currentClient.Connect();
            clients.Add(currentClient);

            //setup redis
            Console.WriteLine("inizialize Redis");
            Redis.initialize();

            //initialize metrics (duuhh...)
            Console.WriteLine("inizialize metrics");
            metrics.initialize();

            // start tasks
            Console.WriteLine("inizialize tasks");
            discoveryTimer           = new TimerPlus();
            discoveryTimer.AutoReset = true;
            discoveryTimer.Interval  = discovery_time_in_ms;
            discoveryTimer.Elapsed  += DiscoveryTimer_Elapsed;
            discoveryTimer.Start();

            TimerPlus uiUpdate = new TimerPlus();

            uiUpdate.AutoReset = true;
            uiUpdate.Interval  = 1000; // 1 second
            uiUpdate.Elapsed  += UiUpdate_Elapsed;
            uiUpdate.Start();


            while (true)
            {
                DrawEvent.WaitOne();
                DrawEvent.Reset();
                ui.draw();
            }
        }
示例#13
0
        static async Task Main(string[] args)
        {
            const string TwitchChatbotNameKey = "TwitchChatbotName";
            const string TwitchChannelNameKey = "TwitchChannelName";
            const string TwitchAccessTokenKey = "TwitchAccessToken";

            #region Dependency Injection initialization
            using IHost host = CreateHostBuilder(args).Build();
            await host.StartAsync();

            await Task.Delay(1000);

            _serviceProvider = host.Services;
            #endregion

            // Application code should start here.
            Console.ForegroundColor = ConsoleColor.Green;
            Console.Title           = "ArgenJarvis";
            Console.WriteLine("Starting...");
            Console.WriteLine();

            #region Twitch Authentication
            // Get login url
            string loginUrl = await GetLoginUrl();

            // Open the url in a new browser tab
            Process.Start("explorer.exe", loginUrl);

            await Task.Delay(3000);

            TwitchChatbotName = await GetValueForAsync(TwitchChatbotNameKey);

            TwitchChannelName = await GetValueForAsync(TwitchChannelNameKey);

            TwitchAccessToken = await GetValueForAsync(TwitchAccessTokenKey);

            #endregion

            var credentials = new ConnectionCredentials(TwitchChatbotName, TwitchAccessToken);

            var             clientOptions = new ClientOptions();
            WebSocketClient customClient  = new WebSocketClient(clientOptions);
            client = new TwitchClient(customClient);
            client.Initialize(credentials, TwitchChannelName);

            client.OnConnected           += Client_OnConnected;
            client.OnDisconnected        += Client_OnDisconected;
            client.OnUserJoined          += Client_OnUserJoined;
            client.OnUserLeft            += Client_OnUserLeft;
            client.OnMessageReceived     += Client_OnMessageReceived;
            client.OnChatCommandReceived += Client_OnChatCommandReceived;
            client.OnNewSubscriber       += Client_OnNewSubscriber;

            client.Connect();

            Console.WriteLine($"Connected!");
            Console.ReadKey();

            // After this line, the code will not be executed
            await host.StopAsync();
        }
示例#14
0
        public TwitchBot()
        {
            bool connected = false;

            Console.WriteLine($"Connecting to Twitch..");

            ConnectionCredentials credentials = new ConnectionCredentials(Settings.Default.TwitchUsername, Settings.Default.TwitchClientToken);

            ClientOptions clientOptions = new ClientOptions
            {
                MessagesAllowedInPeriod = 750,
                ThrottlingPeriod        = TimeSpan.FromSeconds(30)
            };

            WebSocketClient customClient = new WebSocketClient(clientOptions);

            client = new TwitchClient(customClient);
            client.Initialize(credentials, Settings.Default.TwitchUsername);

            client.OnLog             += Client_OnLog;
            client.OnConnected       += Client_OnConnected;
            client.OnJoinedChannel   += Client_OnJoinedChannel;
            client.OnUserJoined      += Client_OnUserJoined;
            client.OnBeingHosted     += Client_OnBeingHosted;
            client.OnMessageReceived += Client_OnMessageReceived;
            client.OnWhisperReceived += Client_OnWhisperReceived;
            client.OnNewSubscriber   += Client_OnNewSubscriber;

            client.Connect();

            Timer timer = new Timer(5)
            {
                AutoReset = true
            };

            timer.Start();

            timer.Elapsed += (sender, args) =>
            {
                Console.WriteLine("..");
            };

            while (!connected)
            {
                connected = client.IsConnected;
            }

            timer.Dispose();

            Console.WriteLine($"Connected to Twitch.");

            timer = new Timer(1000)
            {
                AutoReset = false
            };
            timer.Start();
            timer.Elapsed += (sender, args) =>
            {
                timer.Dispose();
#if RELEASE
                JoinChannels();
#endif
            };

            TwitchApi api = new TwitchApi();

            TwitchApi.StartApi();

            while (!Program.QuitFlag)
            {
                string consoleInput = Console.ReadLine();

                if (string.IsNullOrEmpty(consoleInput))
                {
                    continue;
                }

                if (consoleInput.StartsWith('!'))
                {
                    string[] commandSplit = consoleInput.Split(' ');

                    if (commandSplit[0].ToLower() == "!help" || commandSplit[0].ToLower() == "!commands")
                    {
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.WriteLine("");
                        Console.WriteLine($"--- Unsociable's Bot Help ---");
                        Console.WriteLine("!say [Message] - Says a message in your chat!");
                        Console.WriteLine($"!addnotification [StreamerName] - Adds a streamer to your system when they start streaming");
                        Console.WriteLine("!removenotification [StreamerName] - Removes a streamer from your system");
                        Console.WriteLine("");
                        Console.ForegroundColor = ConsoleColor.DarkYellow;
                    }

                    if (commandSplit[0].ToLower() == "!say")
                    {
                        if (commandSplit.Length < 2)
                        {
                            Console.WriteLine($"You need to input a message!");
                            continue;
                        }

                        string joined = string.Join(' ', commandSplit.Skip(1));

                        client.SendMessage(Settings.Default.TwitchUsername, joined);

                        Console.WriteLine($"Message sent to {Settings.Default.TwitchUsername} channel: {joined}");
                    }

                    if (commandSplit[0].ToLower() == "!addnotification")
                    {
                        if (commandSplit.Length < 2)
                        {
                            Console.WriteLine($"You need to input a streamers channel name!");
                            continue;
                        }

                        string joined = string.Join(' ', commandSplit.Skip(1));

                        if (TwitchApi.StreamNotifications.Contains(joined.ToLower()))
                        {
                            Console.WriteLine($"You already have {joined} in your notifications!");
                            continue;
                        }

                        TwitchApi.StreamNotifications.Add(joined.ToLower());
                        TwitchApi.SaveStreamNotifications();
                        Console.WriteLine($"You've added {joined} to your notifications!");
                    }

                    if (commandSplit[0].ToLower() == "!removenotification")
                    {
                        if (commandSplit.Length < 2)
                        {
                            Console.WriteLine($"You need to input a streamers channel name!");
                            continue;
                        }

                        string joined = string.Join(' ', commandSplit.Skip(1));

                        if (!TwitchApi.StreamNotifications.Contains(joined.ToLower()))
                        {
                            Console.WriteLine($"You don't have {joined} in your notifications!");
                            continue;
                        }

                        TwitchApi.StreamNotifications.Remove(joined.ToLower());
                        TwitchApi.SaveStreamNotifications();
                        Console.WriteLine($"You've removed {joined} from your notifications!");
                    }
                }

                if (consoleInput.ToLower() == "quit")
                {
                    Program.QuitFlag = true;
                }
            }
        }
示例#15
0
 public void Connect()
 => TwitchClient.Connect();
        private static async Task <bool> TwitchLogin()
        {
            string twitchUsername = null;
            string twitchOAuth    = null;
            string twitchPollPass = null;

            m_twitchPollMode = File.Exists("chaosmod/.twitchpoll");

            OptionsFile twitchFile = new OptionsFile("chaosmod/twitch.ini");

            twitchFile.ReadFile();

            m_twitchChannelName                    = twitchFile.ReadValue("TwitchUserName");
            twitchUsername                         = twitchFile.ReadValue("TwitchChannelName");
            twitchOAuth                            = twitchFile.ReadValue("TwitchChannelOAuth");
            twitchPollPass                         = twitchFile.ReadValue("TwitchVotingPollPass");
            m_disableNoVoteMsg                     = twitchFile.ReadValueBool("TwitchVotingDisableNoVoteRoundMsg", false);
            m_enableTwitchChanceSystem             = twitchFile.ReadValueBool("TwitchVotingChanceSystem", false);
            m_enableTwitchChanceSystemRetainChance = twitchFile.ReadValueBool("TwitchVotingChanceSystemRetainChance", true);

            if (m_twitchPollMode)
            {
                OptionsFile configFile = new OptionsFile("chaosmod/config.ini");
                configFile.ReadFile();

                m_twitchPollDur = twitchFile.ReadValueInt("NewEffectSpawnTime", 30);

                if (m_twitchPollDur < 15 || m_twitchPollDur > 180)
                {
                    SendToPipe("invalid_poll_dur");

                    return(false);
                }
            }

            if (m_twitchPollMode)
            {
                m_twitchPollClients = new List <IWebSocketConnection>();

                m_twitchSocketServer = new WebSocketServer("ws://0.0.0.0:31337");
                m_twitchSocketServer.RestartAfterListenError = true;
                m_twitchSocketServer.Start(socket =>
                {
                    socket.OnOpen += () =>
                    {
                        Console.WriteLine($"New client! ({socket.ConnectionInfo.ClientIpAddress}:{socket.ConnectionInfo.ClientPort})");

                        socket.Send($"{{\"type\":\"auth\",\"data\":\"{twitchPollPass}\"}}");

                        m_twitchPollClients.Add(socket);
                    };

                    socket.OnMessage += (msg) =>
                    {
                        Console.WriteLine(msg);

                        dynamic json = DeserializeJson(msg);
                        if (json == null)
                        {
                            return;
                        }

                        string type = json.type;

                        if (type == "created")
                        {
                            m_twitchPollUUID = json.id;
                        }
                        else if (type == "update")
                        {
                            dynamic choices = json.poll.choices;

                            m_votes[0] = (int)choices[0].votes;
                            m_votes[1] = (int)choices[1].votes;
                            m_votes[2] = (int)choices[2].votes;

                            m_twitchPollUUID = null;
                        }
                    };

                    socket.OnClose += () =>
                    {
                        Console.WriteLine($"Connection to client {socket.ConnectionInfo.ClientIpAddress}:{socket.ConnectionInfo.ClientPort} closed.");

                        m_twitchPollClients.Remove(socket);
                    };
                });

                return(true);
            }

            if (string.IsNullOrWhiteSpace(m_twitchChannelName) || string.IsNullOrWhiteSpace(twitchUsername) || string.IsNullOrWhiteSpace(twitchOAuth))
            {
                SendToPipe("invalid_login");

                return(false);
            }

            ConnectionCredentials credentials     = new ConnectionCredentials(twitchUsername, twitchOAuth);
            WebSocketClient       webSocketClient = new WebSocketClient();

            m_twitchClient = new TwitchClient(webSocketClient);
            m_twitchClient.Initialize(credentials, m_twitchChannelName);

            m_twitchClient.OnMessageReceived += OnMessageRecieved;

            bool failed = false;
            bool done   = false;

            m_twitchClient.OnConnectionError += (object sender, OnConnectionErrorArgs e) =>
            {
                failed = true;
                done   = true;
            };

            m_twitchClient.OnConnected += (object sender, OnConnectedArgs e) =>
            {
                done = true;
            };

            m_twitchClient.Connect();

            int lastTick = Environment.TickCount;

            while (!done)
            {
                await Task.Delay(100);

                if (lastTick < Environment.TickCount - 3000)
                {
                    failed = true;
                    done   = true;

                    break;
                }
            }

            if (failed)
            {
                SendToPipe("invalid_login");

                return(false);
            }

            Console.WriteLine("Logged into Twitch Account!");

            done = false;

            m_twitchClient.OnJoinedChannel += (object sender, OnJoinedChannelArgs e) =>
            {
                if (e.Channel.ToLower() == m_twitchChannelName.ToLower())
                {
                    done = true;
                }
            };

            lastTick = Environment.TickCount;
            while (!done)
            {
                await Task.Delay(100);

                if (lastTick < Environment.TickCount - 1500)
                {
                    failed = true;
                    done   = true;
                }
            }

            if (failed)
            {
                SendToPipe("invalid_channel");

                return(false);
            }

            Console.WriteLine("Connected to Twitch Channel!");

            return(true);
        }
示例#17
0
        private static async Task <bool> TwitchLogin()
        {
            string twitchUsername = null;
            string twitchOAuth    = null;
            string twitchPollPass = null;

            _TwitchPollMode = File.Exists("chaosmod/.twitchpoll");

            string data = File.ReadAllText("chaosmod/config.ini");

            foreach (string line in data.Split('\n'))
            {
                string[] text = line.Split('=');
                if (text.Length < 2)
                {
                    continue;
                }

                switch (text[0])
                {
                case "TwitchChannelName":
                    _TwitchChannelName = text[1].Trim();
                    break;

                case "TwitchUserName":
                    twitchUsername = text[1].Trim();
                    break;

                case "TwitchChannelOAuth":
                    twitchOAuth = text[1].Trim();
                    break;

                case "TwitchVotingPollPass":
                    twitchPollPass = text[1].Trim();
                    break;

                case "NewEffectSpawnTime":
                    if (_TwitchPollMode)
                    {
                        _TwitchPollDur = int.Parse(text[1]) - 1;

                        if (_TwitchPollDur < 15 || _TwitchPollDur > 180)
                        {
                            _StreamWriter.Write("invalid_poll_dur\0");

                            return(false);
                        }
                    }
                    break;

                case "TwitchVotingDisableNoVoteRoundMsg":
                    _DisableNoVoteMsg = int.Parse(text[1]) != 0;
                    break;
                }
            }

            if (_TwitchPollMode)
            {
                _TwitchPollClients = new List <IWebSocketConnection>();

                _TwitchSocketServer = new WebSocketServer("ws://0.0.0.0:31337");
                _TwitchSocketServer.RestartAfterListenError = true;
                _TwitchSocketServer.Start(socket =>
                {
                    socket.OnOpen += () =>
                    {
                        Console.WriteLine($"New client! ({socket.ConnectionInfo.ClientIpAddress}:{socket.ConnectionInfo.ClientPort})");

                        socket.Send($"{{\"type\":\"auth\",\"data\":\"{twitchPollPass}\"}}");

                        _TwitchPollClients.Add(socket);
                    };

                    socket.OnMessage += (msg) =>
                    {
                        Console.WriteLine(msg);

                        dynamic json = DeserializeJson(msg);
                        if (json == null)
                        {
                            return;
                        }

                        string type = json.type;

                        if (type == "created")
                        {
                            _TwitchPollUUID = json.id;
                        }
                        else if (type == "update")
                        {
                            dynamic choices = json.poll.choices;

                            _Votes[0] = (int)choices[0].votes;
                            _Votes[1] = (int)choices[1].votes;
                            _Votes[2] = (int)choices[2].votes;

                            _TwitchPollUUID = null;
                        }
                    };

                    socket.OnClose += () =>
                    {
                        Console.WriteLine($"Connection to client {socket.ConnectionInfo.ClientIpAddress}:{socket.ConnectionInfo.ClientPort} closed.");

                        _TwitchPollClients.Remove(socket);
                    };
                });

                return(true);
            }

            if (string.IsNullOrWhiteSpace(_TwitchChannelName) || string.IsNullOrWhiteSpace(twitchUsername) || string.IsNullOrWhiteSpace(twitchOAuth))
            {
                _StreamWriter.Write("invalid_login\0");

                return(false);
            }

            ConnectionCredentials credentials     = new ConnectionCredentials(twitchUsername, twitchOAuth);
            WebSocketClient       webSocketClient = new WebSocketClient();

            _TwitchClient = new TwitchClient(webSocketClient);
            _TwitchClient.Initialize(credentials, _TwitchChannelName);

            _TwitchClient.OnMessageReceived += OnMessageRecieved;

            bool failed = false;
            bool done   = false;

            _TwitchClient.OnConnectionError += (object sender, OnConnectionErrorArgs e) =>
            {
                failed = true;
                done   = true;
            };

            _TwitchClient.OnConnected += (object sender, OnConnectedArgs e) =>
            {
                done = true;
            };

            _TwitchClient.Connect();

            int lastTick = Environment.TickCount;

            while (!done)
            {
                await Task.Delay(100);

                if (lastTick < Environment.TickCount - 3000)
                {
                    failed = true;
                    done   = true;

                    break;
                }
            }

            if (failed)
            {
                _StreamWriter.Write("invalid_login\0");

                return(false);
            }

            Console.WriteLine("Logged into Twitch Account!");

            done = false;

            _TwitchClient.OnJoinedChannel += (object sender, OnJoinedChannelArgs e) =>
            {
                if (e.Channel.ToLower() == _TwitchChannelName.ToLower())
                {
                    done = true;
                }
            };

            lastTick = Environment.TickCount;
            while (!done)
            {
                await Task.Delay(100);

                if (lastTick < Environment.TickCount - 1500)
                {
                    failed = true;
                    done   = true;
                }
            }

            if (failed)
            {
                _StreamWriter.Write("invalid_channel\0");

                return(false);
            }

            Console.WriteLine("Connected to Twitch Channel!");

            return(true);
        }
示例#18
0
        static void Main(string[] args)
        {
            con = false;
            Console.WriteLine();
            Console.WriteLine("Welcome to the world of PokéGuesser!");
            Console.WriteLine("=================");

            #region Init Settings and Client
            // if settings are blank (default or something broke), initialize settings
            if (Properties.Settings.Default.botname == "" || !Properties.Settings.Default.oauth.StartsWith("oauth:") || Properties.Settings.Default.channel == "")
            {
                Console.WriteLine("Settings not found. Initializing settings.");
                CreateInitSettings();
            }
            else
            {
                ConsoleKeyInfo a;
                Console.WriteLine($"Bot: {Properties.Settings.Default.botname}");
                Console.WriteLine($"OAuth: [hidden]");
                Console.WriteLine($"Channel: {Properties.Settings.Default.channel}");
                Console.WriteLine();
                Console.WriteLine("To edit Twitch settings, type 't'");
                Console.WriteLine("To edit extra settings, type 'e'");
                Console.WriteLine("To continue and connect to Twitch, press enter");
                do
                {
                    a = Console.ReadKey();
                } while (!a.KeyChar.Equals('\r') && !a.KeyChar.Equals('e') && !a.KeyChar.Equals('t'));

                if (a.KeyChar.Equals('t'))
                {
                    Console.WriteLine();
                    CreateInitSettings();
                }
                else if (a.KeyChar.Equals('e'))
                {
                    Console.WriteLine();
                    CreateExtraSettings();
                }
                Console.WriteLine();
            }


            // connection to twitch
            try
            {
                if (!Properties.Settings.Default.oauth.StartsWith("oauth:"))
                {
                    Properties.Settings.Default.oauth = "oauth:" + Properties.Settings.Default.oauth;
                }
                ConnectionCredentials credentials = new ConnectionCredentials(Properties.Settings.Default.botname, Properties.Settings.Default.oauth);
                twitchClient = new TwitchClient();
                twitchClient.Initialize(credentials);
                twitchClient.OnConnected += TwitchClient_OnConnected;
                //twitchClient.OnMessageReceived += TwitchClient_OnMessageReceived;
                twitchClient.OnChatCommandReceived += TwitchClient_OnChatCommandReceived;
            }
            catch (Exception e)
            {
                Console.WriteLine();
                Console.WriteLine("= ERROR =");
                Console.WriteLine(e.Message);
                Properties.Settings.Default.botname = "";
                Properties.Settings.Default.oauth   = "";
                Properties.Settings.Default.Save();
                Console.WriteLine("Press any key to close. Please relaunch the application.");
                Console.ReadKey();
                Environment.Exit(1);
            }

            // helper for connection to pokeapi.co
            ApiHelper.InitializeClient();
            #endregion

            twitchClient.Connect();
            do
            {
                //TODO: infinite loop check
                Console.WriteLine("Connecting to Twitch...");
                Thread.Sleep(500);
            } while (!con);
            con = false;
            twitchClient.JoinChannel(Properties.Settings.Default.channel);
            Console.WriteLine($"{Properties.Settings.Default.botname} has connected to {Properties.Settings.Default.channel}'s channel");
            Console.WriteLine();
            Helper();

            // wait forever
            Thread.Sleep(Timeout.Infinite);
            Console.WriteLine("End of program");
        }
示例#19
0
 public void Connect()
 {
     _twitchClient.Connect();
 }
示例#20
0
 private Task ConnectClient()
 {
     return(Task.Run(() => {
         TwitchClient.Connect();
     }));
 }