Ejemplo n.º 1
0
        public Twitch(string username, string token, string[] channels, char Command = '!') : base(Command)
        {
            ConnectionCredentials credentials = new ConnectionCredentials(username, token);

            _client = new TwitchClient();

            _client.Initialize(credentials);

            _client.RemoveChatCommandIdentifier('!');
            _client.AddChatCommandIdentifier(Command);

            _client.OnMessageReceived     += MessageReceived;
            _client.OnChatCommandReceived += CommandReceived;

            _client.Connect();

            while (!_client.IsConnected)
            {
                System.Threading.Thread.Sleep(200);
            }

            while (_client.JoinedChannels.Count != channels.Length)
            {
                foreach (string C in channels)
                {
                    _client.JoinChannel(C, true);
                    System.Threading.Thread.Sleep(500);
                }
            }
        }
Ejemplo n.º 2
0
        internal async void Connect()
        {
            /*
             * Метод подключения бота к каналу
             */
            Console.WriteLine("Connected");



            /*
             * TwitchInfo.ChannelName - ChannelName это канал на твиче, к которому подключается бот
             */
            client = new TwitchClient();
            client.Initialize(credentials, TwitchInfo.ChannelName, autoReListenOnExceptions: false);
            api = new TwitchAPI();

            /*
             * allowedMessage - разрешенное число сообщений
             * time - время бездействия
             */
            int allowedMessage;
            int time;

            Console.WriteLine("Enter allowed messages:");
            allowedMessage = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Add Time:");
            time = Convert.ToInt32(Console.ReadLine());


            client.ChatThrottler = new MessageThrottler(client, allowedMessage, TimeSpan.FromSeconds(time));

            await client.ChatThrottler.StartQueue();


            await api.InitializeAsync(TwitchInfo.ClientId, TwitchInfo.AccessToken);


            /*
             * Инициализация методов функций бота
             */

            client.OnLog                 += Client_OnLog;
            client.OnConnectionError     += Client_OnConnectionError;
            client.OnMessageReceived     += Client_OnMessageReceivedAsync;
            client.OnMessageReceived     += TwitchClient_OnMessageReceived;
            client.OnMessageReceived     += File_OnMessageReceived;
            client.OnChatCommandReceived += Client_OnChatCommandReceived;

            client.AddChatCommandIdentifier('!');
            // TwitchLib.Services.FollowerService follows = new TwitchLib.Services.FollowerService(api, 5, 3);



            client.Connect();
        }
Ejemplo n.º 3
0
        internal void Connect()
        {
            Console.WriteLine("Connecting...");

            // Client Connect
            client = new TwitchClient(linkage);
            client.Initialize(botCred, Credentials.ChannelName);
            breakPedal = new Throttlers(linkage, TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(60));

            while (commandSwitch < 0 || commandSwitch > 3)
            {
                commandSwitch = Convert.ToInt16(WBF.gameQuestion());
            }

            masterList = WBF.UserTake(masterList);

            if (commandSwitch == 1 || commandSwitch == 2)
            {
                barracks = WBF.SoldierTake(barracks);
            }
            else if (commandSwitch == 3)
            {
                npc = WBF.NPC_Take(npc);
            }
            else
            {
                ;
            }

            client.OnConnected     += On_Connected;
            client.OnJoinedChannel += On_JoinedChennel;

            client.OnUserJoined += On_UserJoined;
            client.OnUserLeft   += On_UserLeft;

            client.AddChatCommandIdentifier('!');
            client.OnChatCommandReceived += On_CommandReceived;
            client.AddWhisperCommandIdentifier('!');
            client.OnWhisperCommandReceived += On_WhisperCommandReceived;

            client.OnBeingHosted      += On_BeingHosted;
            client.OnRaidNotification += On_BeingRaided;

            client.OnGiftedSubscription += On_GiftedSub;
            client.OnNewSubscriber      += On_NewSub;
            client.OnReSubscriber       += On_ReSub;

            client.OnMessageThrottled += On_MessageThrottle;
            client.OnWhisperThrottled += On_WhisperThrottle;

            client.Connect();

            upTimer();
        }
Ejemplo n.º 4
0
        // Call bot to connect
        internal void Connect()
        {
            consoleMessage[5] = "Initializing Twitch Chat Bot...";
            Program.SendToConsole(consoleMessage);
            client = new TwitchClient(credentials, streamerChannel, logging: false);

            consoleMessage[5] = $"Setting command identifier to {Commands.Commands.CommandPrefix}.";
            Program.SendToConsole(consoleMessage);
            client.AddChatCommandIdentifier(Commands.Commands.CommandPrefix);
            client.AddWhisperCommandIdentifier(Commands.Commands.CommandPrefix);

            // set message throttling
            consoleMessage[5] = "Setting Twitch chat throttle set to 19 messages every 30 seconds.";
            Program.SendToConsole(consoleMessage);
            client.ChatThrottler    = new TwitchLib.Services.MessageThrottler(client, 19, TimeSpan.FromSeconds(30));
            client.WhisperThrottler = new TwitchLib.Services.MessageThrottler(client, 19, TimeSpan.FromSeconds(30));

            consoleMessage[5] = "Registering Twitch chat events...";
            Program.SendToConsole(consoleMessage);

            // Connection events
            client.OnLog             += Client_OnLog;
            client.OnIncorrectLogin  += Client_OnIncorrectLogin;
            client.OnConnectionError += Client_OnConnecitonError;
            client.OnConnected       += Client_OnConnected;
            client.OnDisconnected    += Client_OnDisconnected;

            // Message events
            client.OnMessageReceived     += Client_OnMessageReceived;
            client.OnChatCommandReceived += Client_OnChatCommandReceived;
            client.OnMessageSent         += Client_OnMessageSent;

            // Whisper events
            client.OnWhisperReceived        += Client_OnWhisperReceived;
            client.OnWhisperCommandReceived += Client_OnWhisperCommandReceived;
            client.OnWhisperSent            += Client_OnWhisperSent;

            // User events
            client.OnUserJoined   += Client_OnUserJoined;
            client.OnUserLeft     += Client_OnUserLeft;
            client.OnUserTimedout += Client_OnUserTimedout;

            // Channel events
            client.OnJoinedChannel += Client_OnJoinedChannel;
            client.OnLeftChannel   += Client_OnLeftChannel;

            consoleMessage[5] = "Connecting to Twitch chat...";
            Program.SendToConsole(consoleMessage);
            client.Connect();
        }
Ejemplo n.º 5
0
        public TwitchChatClient(TwitchClientSettings settings)
        {
            _settings = settings;
            var connectionCredentials = new ConnectionCredentials(settings.UserName, settings.OAuth);

            _twitchClient = new TwitchClient();
            _twitchClient.Initialize(connectionCredentials, settings.Channel);
            _twitchClient.AddChatCommandIdentifier('!');

            _twitchClient.OnJoinedChannel       += TwitchClientOnOnJoinedChannel;
            _twitchClient.OnUserJoined          += TwitchClientOnOnUserJoined;
            _twitchClient.OnUserLeft            += TwitchClientOnOnUserLeft;
            _twitchClient.OnChatCommandReceived += TwitchClientOnOnChatCommandReceived;
        }
Ejemplo n.º 6
0
 private void InitTwitchClient()
 {
     client                        = new TwitchClient(credentials, Credentials.channelToJoin);
     client.OnConnected           += OnConnected;
     client.OnDisconnected        += OnDisconnected;
     client.OnUserJoined          += OnUserJoined;
     client.OnUserLeft            += OnUserLeft;
     client.OnConnectionError     += OnConnectionError;
     client.OnWhisperReceived     += OnWisperReceived;
     client.OnMessageReceived     += OnMessageReceived;
     client.OnChatCommandReceived += OnCommandReceived;
     client.AddChatCommandIdentifier(commandIdentifier);
     client.AddWhisperCommandIdentifier(commandIdentifier);
 }
Ejemplo n.º 7
0
        private async void ConfigLiveMonitorAsync()
        {
            API    = new TwitchAPI();
            Client = new TwitchClient();
            Log    = new LogHelper();

            FindSettings();

            API.Settings.ClientId    = Settings.ClientId;
            API.Settings.AccessToken = Settings.AccessToken;

            // Monitor stuff
            Monitor = new LiveStreamMonitorService(API);
            Monitor.SetChannelsByName(Settings.MonitoredChannels);

            Monitor.OnStreamOnline   += Monitor_OnStreamOnline;
            Monitor.OnStreamOffline  += Monitor_OnStreamOffline;
            Monitor.OnStreamUpdate   += Monitor_OnStreamUpdate;
            Monitor.OnServiceStarted += Monitor_OnServiceStarted;
            Monitor.OnChannelsSet    += Monitor_OnChannelSet;

            Monitor.Start();

            // Client Stuff
            ConnectionCredentials credentials = new ConnectionCredentials(Settings.BotConnectionDetails.UserName, Settings.BotConnectionDetails.OAuth);

            Client.Initialize(credentials, Settings.MonitoredChannels.FirstOrDefault());
            Client.AddChatCommandIdentifier(Settings.ChatCommandIdentifier);

            Client.OnLog                 += Client_OnLog;
            Client.OnJoinedChannel       += Client_OnJoinedChannel;
            Client.OnMessageReceived     += Client_OnMessageReceived;
            Client.OnConnected           += Client_OnConnected;
            Client.OnNewSubscriber       += Client_OnNewSubscriber;
            Client.OnReSubscriber        += Client_OnResubscriber;
            Client.OnGiftedSubscription  += Client_GiftedSubscription;
            Client.OnChatCommandReceived += Client_OnChatCommandReceived;

            Client.Connect();

            Log.SetBotUsername(Client.TwitchUsername);

            SetupCommands();

            await Task.Delay(-1);
        }
Ejemplo n.º 8
0
        private async Task InitializeBot()
        {
            var credentials = new ConnectionCredentials(_account?.TwitchBotSettings.Username,
                                                        _appSettings?.Keys.Twitch.Bot.Oauth);

            _client.Initialize(credentials, "KungRaseri", autoReListenOnExceptions: false);
            _client.ChatThrottler    = new MessageThrottler(_client, 15, TimeSpan.FromSeconds(30));
            _client.WhisperThrottler = new MessageThrottler(_client, 15, TimeSpan.FromSeconds(30));

            await _client.ChatThrottler.StartQueue();

            await _client.WhisperThrottler.StartQueue();

            if (_appSettings != null)
            {
                _client.AddChatCommandIdentifier(_account.TwitchBotSettings.CommandCharacter);
            }

            TwitchHandlers.Init(_client, _twitchPubSub, _appSettings, _account, _viewerCollection, _commandSettings);
        }
Ejemplo n.º 9
0
        public static void Connect(string token)
        {
            ConnectionCredentials credentials = new ConnectionCredentials(ChannelName, token);
            var clientOptions = new ClientOptions
            {
                MessagesAllowedInPeriod = 750,
                ThrottlingPeriod        = TimeSpan.FromSeconds(30)
            };
            WebSocketClient customClient = new WebSocketClient(clientOptions);

            Client = new TwitchClient(customClient);
            Client.Initialize(credentials, ChannelName);

            Client.OnLog                 += Client_OnLog;
            Client.OnConnected           += Client_OnConnected;
            Client.OnChatCommandReceived += Client_OnChatCommandReceived;
            Client.AddChatCommandIdentifier('!');

            Client.Connect();
        }
Ejemplo n.º 10
0
        internal void Connect(bool isLogging)
        {
            client = new TwitchClient();
            client.Initialize(cred, TwitchInfo.ChannelName);
            client.OnConnected += Client_OnConnected;

            Console.WriteLine("[Bot]: Connecting...");

            if (isLogging)
            {
                client.OnLog += Client_OnLog;
            }

            client.OnError               += Client_OnError;
            client.OnMessageReceived     += Client_OnMessageReceived;
            client.OnChatCommandReceived += Client_OnChatCommandReceived;
            client.AddChatCommandIdentifier('!');

            client.Connect();
        }
Ejemplo n.º 11
0
        private void InitializeClient()
        {
            var credentials = new ConnectionCredentials(
                _configuration.GetSection("twitch")["username"],
                _configuration.GetSection("twitch")["password"],
                _configuration.GetSection("twitch")["webSocketUri"],
                _configuration.GetSection("twitch").GetValue <bool>("disableUserNameCheck")
                );

            _client = new TwitchClient();

            _client.Initialize(credentials);

            _client.OnJoinedChannel += OnTwitchJoinChannel;
            _client.OnLeftChannel   += OnTwitchLeftChannel;

            _client.OnMessageReceived += OnTwitchMessage;
            _client.OnWhisperReceived += OnTwitchWhisperMessage;

            _client.OnChatCommandReceived    += OnTwitchCommand;
            _client.OnWhisperCommandReceived += OnTwitchWhisperCommand;

            _client.OnModeratorJoined += OnTwitchModeratorJoined;
            _client.OnModeratorLeft   += OnTwitchModeratorLeft;

            _client.OnUserJoined += OnTwitchUserJoined;
            _client.OnUserLeft   += OnTwitchUserLeft;

            _client.OnConnected += OnTwitchConnected;

            _client.AutoReListenOnException = true;
            _client.RemoveChatCommandIdentifier('!');
            _client.AddChatCommandIdentifier(_configuration.GetSection("twitch").GetSection("commandPrefix").Get <char>());

            _client.RemoveWhisperCommandIdentifier('!');
            _client.AddWhisperCommandIdentifier(_configuration.GetSection("twitch").GetSection("commandPrefix").Get <char>());

            _client.OnError += onTwitchError;
        }
Ejemplo n.º 12
0
        public TwitchBotClient(string _userName, string password, string _channelName)
        {
            userName             = _userName;
            channelName          = _channelName;
            addUsersToListThread = new Thread(FillUserList);
            addUsersToListThread.Start();
            //Should be filled with oAuthToken and userId
            credentials = new ConnectionCredentials("", "");
            client      = new TwitchClient();

            client.Initialize(credentials, channelName);
            client.ChatThrottler    = new TwitchLib.Client.Services.MessageThrottler(client, 20, TimeSpan.FromSeconds(30));
            client.WhisperThrottler = new TwitchLib.Client.Services.MessageThrottler(client, 20, TimeSpan.FromSeconds(30));
            client.ChatThrottler.StartQueue();
            client.OnJoinedChannel       += OnJoinedChannel;
            client.OnMessageReceived     += OnMessageReceived;
            client.OnWhisperReceived     += OnWhisperReceived;
            client.OnNewSubscriber       += OnNewSubscriber;
            client.OnConnected           += Client_OnConnected;
            client.OnBeingHosted         += Client_OnBeingHosted;
            client.OnReSubscriber        += Client_OnReSubscriber;
            client.OnUserJoined          += Client_OnUserJoined;
            client.OnUserLeft            += Client_OnUserLeft;
            client.OnChatCommandReceived += Client_OnChatCommandReceived;
            client.AddChatCommandIdentifier('!');

            //Unsub events will come late .... (nur zur anmerkung)
            try
            {
                client.Connect();
            }
            catch (Exception e)
            {
                Console.WriteLine("Verbindung konnte nicht hergestellt werden. Exception: " + e);
            }
        }
        public Task StartAsync(CancellationToken cancellationToken)
        {
            _ = PostHealth();

            // Needs to happen at a later time because the SignalR hub needs to be started first.
            _ = Task.Run(async() =>
            {
                await Task.Delay(TimeSpan.FromSeconds(3));

                await _hub.StartAsync();
                _logger.LogInformation("Connected to SignalR");

                await _hub.RegisterAsBot();
                _logger.LogInformation("Subscribed to Bot Group");
                _twitch.Connect();
            });

            // Init Twitch bot.
            var credentials   = new ConnectionCredentials("proto4bot", ACCESS_TOKEN);
            var clientOptions = new ClientOptions
            {
                MessagesAllowedInPeriod = 750,
                ThrottlingPeriod        = TimeSpan.FromSeconds(30)
            };
            var customClient = new WebSocketClient(clientOptions);

            _twitch = new TwitchClient(customClient);
            _twitch.AddChatCommandIdentifier('!');
            _twitch.Initialize(credentials);
            _twitch.OnJoinedChannel       += Twitch_OnJoinedChannel;
            _twitch.OnLeftChannel         += Twitch_OnLeftChannel;
            _twitch.OnChatCommandReceived += Twitch_OnChatCommandReceived;
            _twitch.OnConnected           += Twitch_OnConnected;

            return(Task.CompletedTask);
        }
Ejemplo n.º 14
0
        public void BotStart()
        {
            try
            {
                ConnectionCredentials credentials = new ConnectionCredentials("JustAnyBot", Settings.AuthToken);

                client = new TwitchClient();
                client.Initialize(credentials);
                client.OnConnected += Client_OnConnected;
                client.AddChatCommandIdentifier(char.Parse("#"));
                client.OnConnectionError += Client_ConnectionError;
                client.OnUserTimedout    += Client_TimedOut;
                if (Settings.AnnounceJoin)
                {
                    client.OnUserJoined += Client_UserJoined;
                }
                client.OnChatCommandReceived += Client_ChatCommandReceived;
                if (Settings.AnnounceLeave)
                {
                    client.OnUserLeft += Client_UserLeft;
                }
                if (Settings.ThankSubscribers)
                {
                    client.OnNewSubscriber += Client_Subscribed;
                }

                api = new TwitchAPI();
                api.Settings.ClientId    = Settings.ClientId;
                api.Settings.AccessToken = Settings.AuthToken;

                GetInfo();

                if (Settings.ThankFollowers)
                {
                    follower = new FollowerService(api, 5);
                    follower.SetChannelByChannelId(Settings.ChannelId);
                    follower.OnNewFollowersDetected += Client_Followed;
                    follower.StartService();
                }

                if (Settings.AnnounceBan)
                {
                    client.OnUserBanned += Client_Banned;
                }
                if (Settings.AnnounceNowHosting)
                {
                    client.OnNowHosting += Client_Hosting;
                }

                UserApi = new TwitchLib.Api.Sections.Users.V5Api(api);

                client.Connect();


                window.Dispatcher.Invoke((Action)(() =>
                {
                    window.BotStarting();
                }));
            }
            catch (ThreadAbortException e)
            {
                MessageBox.Show("Erro: A Janela fechou antes de obter o AuthToken");
            }
            catch (Exception e)
            {
                MessageBox.Show($"An exception has occurred: \n\n{e.Message}");
            }
        }
Ejemplo n.º 15
0
 private void _TwitchClient_OnConnected(object sender, TwitchLib.Client.Events.OnConnectedArgs e)
 {
     _TwitchClient.AddChatCommandIdentifier('!');
     _TwitchClient.SendMessage(BotAppSettings.ChannelName, $"O pai ta on! {EmotesConsts.PogChamp}");
     Console.WriteLine($"Twitch bot conectado às {DateTime.Now}");
 }
Ejemplo n.º 16
0
        public async Task RealMainAsync()
        {
            var config = new ConfigurationBuilder()
                         .AddJsonFile("config.json")
                         .Build();

            _config = new BotConfig(config);

            AppDomain.CurrentDomain.UnhandledException += async(_, e) =>
                                                          await Utils.SendDiscordErrorWebhookAsync($"{_config.DiscordWebhookUserPing}: Error with Twitch bot, check logs.", _config.DiscordWebhookUrl);

            _api = new TwitchAPI();
            _api.Settings.ClientId    = _config.TwitchClientId;
            _api.Settings.AccessToken = _config.TwitchOAuth;
            _client = new TwitchClient();
            _client.Initialize(new ConnectionCredentials(_config.TwitchUsername, _config.TwitchOAuth));

            _client.OnConnected     += ChatConnected;
            _client.OnJoinedChannel += (_, e) => Utils.LogToConsole($"Joined chat channel {e.Channel}");

            _client.OnChatCommandReceived += CommandHandler;
            _client.OnConnectionError     += ChatConnectionError;
            _client.OnDisconnected        += ChatDisconnected;
            _client.OnError          += ChatError;
            _client.OnIncorrectLogin += ChatIncorrectLogin;

            _client.AddChatCommandIdentifier('!');

            _pubSub = new TwitchPubSub();

            _slothySvc = new SlothyService();
            await _slothySvc.InitializeAsync();

            _multiHandler = new MultitwitchCommandHandler(_client, _api);
            await _multiHandler.InitializeAsync();

            _crendorQuoteHandler = new QuoteCommandHandler <CrendorQuoteRecord>(_client);
            await _crendorQuoteHandler.InitializeAsync();

            _omarQuoteHandler = new QuoteCommandHandler <OmarQuoteRecord>(_client);
            await _omarQuoteHandler.InitializeAsync();

            _betSvc = new SlothyBetService();
            await _betSvc.InitializeAsync();

            _slothyHandler    = new SlothyCommandHandler(_client, _api, _slothySvc);
            _slothFactHandler = new SlothFactCommandHandler(_client);
            _woppyHandler     = new WoppyCommandHandler(_config, _client);

            _slothyBetCommandHandler = new SlothyBetCommandHandler(_client, _betSvc, _slothySvc);
            await _slothyBetCommandHandler.InitializeAsync();

            ConnectChat();

            _pubSub.OnPubSubServiceConnected += PubSubConnected;
            _pubSub.OnPubSubServiceClosed    += PubSubClosed;
            _pubSub.OnPubSubServiceError     += PubSubClosed;
            _pubSub.OnListenResponse         += ListenResponse;

            _subPointsHandler = new SubPointsHandler(_config, _client, _pubSub, _api, _slothySvc);
            await _subPointsHandler.InitializeAsync();

            _stretchTimerHandler = new StretchTimerHandler(_config, _client, _pubSub);

            _pubSubReconnectTimer = new Timer(_ => ReconnectPubSub(), null, TimeSpan.Zero, TimeSpan.FromHours(18));

            await Task.Delay(-1);
        }