public async Task ConnectAsyncShouldSuccessfullyConnectToTwitch()
        {
            // Arrange
            var client = new TwitchClient(_output.BuildLoggerFor <TwitchClient>());

            TwitchMessage.Welcome welcome = null;

            var cts = new CancellationTokenSource();

            cts.CancelAfter(TimeSpan.FromMinutes(1));
            async Task ReadLoop()
            {
                while (client.IsConnected && welcome is null)
                {
                    welcome = await client.ReadMessageAsync <TwitchMessage.Welcome>(token : cts.Token);
                }
            }

            // Act
            await client.ConnectAsync("justinfan0227", "");

            await ReadLoop();

            // Assert
            Assert.NotNull(welcome);
        }
        public async Task JoinChannelShouldSuccessfullyJoinAChannel()
        {
            // Arrange
            var client = new TwitchClient(_output.BuildLoggerFor <TwitchClient>());

            TwitchMessage.Join join = null;

            var cts = new CancellationTokenSource();

            cts.CancelAfter(TimeSpan.FromMinutes(1));
            async Task ReadLoop()
            {
                while (client.IsConnected && join is null)
                {
                    join = await client.ReadMessageAsync <TwitchMessage.Join>(token : cts.Token);
                }
            }

            // Act
            await client.ConnectAsync("fdgttest", "", serverUri : "wss://irc.fdgt.dev");

            var readTask = ReadLoop();

            await client.JoinChannelAsync("fdgt");

            await readTask;

            // Assert
            Assert.NotNull(join);
            Assert.Equal("fdgt", join.Channel);
            Assert.Equal("fdgttest", join.Username);
        }
        private async Task <TwitchClient> InitClient()
        {
            var twitchUsername = ConfigurationManager.AppSettings.Get("username");
            ConnectionCredentials credentials = new ConnectionCredentials(twitchUsername, _token);

            var client         = new TwitchClient();
            var defaultChannel = ConfigurationManager.AppSettings.Get("default_channel");

            client.Initialize(credentials, defaultChannel);
            await client.ConnectAsync();

            return(client);
        }
        public async Task TwitchClientShouldSupportReceivingGiftSubs()
        {
            // Arrange
            var client = new TwitchClient(_output.BuildLoggerFor <TwitchClient>());

            TwitchMessage.GiftSub giftSub = null;

            var cts = new CancellationTokenSource();

            cts.CancelAfter(TimeSpan.FromMinutes(1));
            async Task ReadLoop()
            {
                while (client.IsConnected && giftSub is null)
                {
                    giftSub = await client.ReadMessageAsync <TwitchMessage.GiftSub>(token : cts.Token);
                }
            }

            // Act
            await client.ConnectAsync("fdgttest", "", serverUri : "wss://irc.fdgt.dev");

            var readTask = ReadLoop();

            await client.JoinChannelAsync("fdgt");

            while (!client.JoinedChannels.Contains("fdgt"))
            {
                ;
            }
            await client.SendChatMessageAsync("fdgt", "subgift --count 25 --userid 123 --userid2 456 --channelid 789");

            await readTask;

            // Assert
            Assert.NotNull(giftSub);
            Assert.Equal("fdgt", giftSub.Channel);
            Assert.Equal("fdgttest", giftSub.SenderUserName);
        }
Esempio n. 5
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            // get and keep the latest auth tokens
            using (var context = _contextFactory.CreateDbContext())
            {
                _tokens = context.AccessTokens.OrderByDescending(a => a.CreatedOn).First();
            }

            // validate our tokens and refresh if necessary
            var api      = _apiFactory.CreateApiClient();
            var response = await api.VerifyAccessTokenAsync(_tokens.AccessToken);

            if (response is null)
            {
                _tokens = await _mediator.Send(new RefreshTokensRequest(), stoppingToken);
            }

            // hook up events
            _client.OnDisconnected += TwitchClient_OnDisconnected;

            // connect to Twitch
            _logger.LogInformation("Connecting to Twitch...");
            await _client.ConnectAsync(_settings.BotUsername, _tokens.AccessToken, token : stoppingToken);

            // continue to read messages until the application stops
            while (!stoppingToken.IsCancellationRequested)
            {
                var message = await _client.ReadMessageAsync(stoppingToken);

                using (_logger.BeginScope(new Dictionary <string, object>
                {
                    ["@TwitchMessage"] = message
                }))
                {
                    try
                    {
                        switch (message)
                        {
                        case TwitchMessage.Welcome:
                            _logger.LogInformation("Connected!");
                            await TwitchClient_OnConnected();

                            break;

                        case TwitchMessage.Join join:
                            _logger.LogDebug("User {UserName} has joined channel {ChannelName}.", join.Username, join.Channel);
                            break;

                        case TwitchMessage.Chat chat:
                            await TwitchClient_OnMessageReceived(chat);

                            break;

                        case TwitchMessage.ClearChat clearChat:
                            var channelId = await _userService.GetIdByUsername(clearChat.Channel);

                            if (string.IsNullOrWhiteSpace(clearChat.User))
                            {
                                // todo: clear the entire channel's history
                            }
                            else
                            {
                                _logger.LogInformation("Banning user {UserName} from channel {ChannelName}.", clearChat.User, clearChat.Channel);
                                await _mediator.Send(new BanUserRequest(clearChat.Channel, clearChat.User), stoppingToken);
                            }
                            break;

                        case TwitchMessage.ClearMsg clearMsg:
                            await _mediator.Send(new DeleteMessageNotification(clearMsg.TargetMessageId), stoppingToken);

                            break;

                        case TwitchMessage.GiftSub giftSub:
                            await TwitchClient_OnGiftedSubscription(giftSub);

                            break;

                        case TwitchMessage.Part part:
                            _logger.LogDebug("User {UserName} has left channel {ChannelName}.", part.Username, part.Channel);
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        _logger.LogError(e, "Exception caught in message read loop after receiving {MessageType}.", message.GetType());
                    }
                }
            }

            _isStopping = true;
            _logger.LogInformation("Disconnecting from Twitch...");
        }