private async Task ConfigLiveMonitorAsync() { API = new TwitchAPI(); API.Settings.ClientId = Settings.ClientId; API.Settings.AccessToken = Settings.AccessToken; Monitor = new LiveStreamMonitorService(API, 10); Monitor.OnServiceStarted += Monitor_OnServiceStarted; Monitor.OnServiceStopped += Monitor_OnServiceStopped; Monitor.OnServiceTick += Monitor_OnServiceTick; Monitor.OnChannelsSet += Monitor_OnChannelsSet; List <string> lst = new List <string> { Settings.ChannelName, "TaleLearnCode" }; Monitor.SetChannelsByName(lst); Monitor.OnStreamOnline += Monitor_OnStreamOnline; Monitor.OnStreamOffline += Monitor_OnStreamOffline; Monitor.OnStreamUpdate += Monitor_OnStreamUpdate; Monitor.Start(); await Task.Delay(-1); }
private async Task ConfigLiveMonitorAsync() { API = new TwitchAPI(); API.Settings.ClientId = _settings.ClientId; API.Settings.AccessToken = _settings.ChannelAuthToken; Monitor = new LiveStreamMonitorService(API, 30); //FollowerService = new FollowerService(API, 30, 10); List <string> channels = new List <string> { _settings.ChannelId }; Monitor.SetChannelsById(channels); Monitor.OnStreamOnline += Monitor_OnStreamOnline; Monitor.OnStreamOffline += Monitor_OnStreamOffline; Monitor.OnStreamUpdate += Monitor_OnStreamUpdate; Monitor.OnServiceStarted += Monitor_OnServiceStarted; Monitor.OnChannelsSet += Monitor_OnChannelsSet; //FollowerService.SetChannelsById(channels); //FollowerService.OnChannelsSet += Follower_OnChannelsSet; //FollowerService.OnNewFollowersDetected += Follower_OnNewFollow; //FollowerService.OnServiceStarted += Follower_OnServiceStarted; Monitor.Start(); //Keep at the end! //FollowerService.Start(); await Task.Delay(-1); }
private async Task ConfigLiveMonitorAsync(string clientid, string access_token, string channel) { API = new TwitchAPI(); API.Settings.ClientId = clientid; API.Settings.AccessToken = access_token; Monitor = new LiveStreamMonitorService(API, 60); Monitor.SetChannelsByName(new List <string> { channel }); /* * Monitor.OnStreamOnline += Monitor_OnStreamOnline; * Monitor.OnStreamOffline += Monitor_OnStreamOffline; * Monitor.OnStreamUpdate += Monitor_OnStreamUpdate; * * Monitor.OnServiceStarted += Monitor_OnServiceStarted; * Monitor.OnChannelsSet += Monitor_OnChannelsSet; */ Service = new FollowerService(API); if (Program.config.format_onfollow != null) { Service.OnNewFollowersDetected += Monitor_onNewFollowersDetected; } Service.Start(); Monitor.Start(); //Keep at the end! await Task.Delay(-1); }
public async void OnStreamUpdate_Called_When_StreamAlreadyOnline() { var usersFollowsResponseJson = JMock.Of <GetStreamsResponse>(o => o.Streams == new[] { Mock.Of <Stream>(u => u.UserId == "UserId") } ); var mockHandler = TwitchLibMock.HttpCallHandler(("https://api.twitch.tv/helix/streams", usersFollowsResponseJson)); _api = TwitchLibMock.TwitchApi(mockHandler); var eventExecuteCount = 0; _liveStreamMonitor = new LiveStreamMonitorService(_api); _liveStreamMonitor.SetChannelsById(Utils.CreateListWithStrings("UserId")); _liveStreamMonitor.OnStreamUpdate += (sender, e) => eventExecuteCount++; await _liveStreamMonitor.UpdateLiveStreamersAsync(); await _liveStreamMonitor.UpdateLiveStreamersAsync(); Assert.Equal(1, eventExecuteCount); }
public void Start_Throws_InvalidOperationException_When_ServiceAlreadyStarted() { _liveStreamMonitor = new LiveStreamMonitorService(_api); _liveStreamMonitor.SetChannelsById(Utils.CreateListWithEmptyString()); _liveStreamMonitor.Start(); AssertException.Throws <InvalidOperationException>(AlreadyStartedExceptionMessage, () => _liveStreamMonitor.Start()); }
internal void Connect() { Console.WriteLine("Connecting..."); client = new TwitchClient(); client.Initialize(credentials, TwitchInfo.ChannelName); //Client Events client.OnLog += Client_OnLog; client.OnConnectionError += Client_OnConnectionError; client.OnMessageReceived += Client_OnMessageReceived; client.OnNewSubscriber += Client_OnNewSubscriber; client.Connect(); api = new TwitchAPI(); api.Settings.ClientId = TwitchInfo.ClientID; api.Settings.AccessToken = TwitchInfo.BotToken; //API Events monitor = new LiveStreamMonitorService(api, int.Parse(TwitchInfo.UpdateInterval)); List <string> channels = new List <string>(); channels.Add(TwitchInfo.ChannelName); monitor.SetChannelsByName(channels); monitor.OnStreamOffline += Monitor_OnStreamOffline; monitor.OnStreamOnline += Monitor_OnStreamOnline; monitor.Start(); fservice = new FollowerService(api, int.Parse(TwitchInfo.UpdateInterval)); fservice.SetChannelsByName(channels); fservice.OnNewFollowersDetected += Fservice_OnNewFollowersDetected; fservice.Start(); //Excel Stuff excel = new Application(); excel.Visible = true; wb = excel.Workbooks.Open(TwitchInfo.ExcelPath); foreach (Worksheet sheet in wb.Sheets) { if (sheet.Name == TwitchInfo.ChannelName) { Console.WriteLine("Found exisiting channel..."); ws = sheet; break; } } if (ws == null) { //Create/copy a new worksheet from base worksheet Console.WriteLine("New channel detected, creating a new sheet..."); ws = (Worksheet)excel.Worksheets.Add(); ws.Name = TwitchInfo.ChannelName; } }
public void OnChannelsSet_Raised_When_ChannelsSet() { var eventRaised = false; _liveStreamMonitor = new LiveStreamMonitorService(_api); _liveStreamMonitor.OnChannelsSet += (sender, e) => eventRaised = true; _liveStreamMonitor.SetChannelsById(Utils.CreateListWithEmptyString()); Assert.True(eventRaised); }
private readonly string _developmentRoomId = string.Empty; // Only for use in debug mode public ChatbotService(ICommandHelper commandHelper, ITwitchClientFactory twitchClientFactory, TwitchPubSub pubsub, ITwitchLiveStreamMonitorFactory twitchLiveStreamMonitorFactory, IVipApiClient vipApiClient, IConfigService configService, IStreamStatusApiClient streamStatusApiClient, ISecretService secretService, ILogger <ChatbotService> logger) { _commandHelper = commandHelper; _pubsub = pubsub; _twitchLiveStreamMonitorFactory = twitchLiveStreamMonitorFactory; _vipApiClient = vipApiClient; _configService = configService; _streamStatusApiClient = streamStatusApiClient; _secretService = secretService; _logger = logger; _streamerChannel = _configService.Get <string>("StreamerChannel"); _isDevelopmentBuild = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development" || Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Local"; _client = twitchClientFactory.Get(); _client.OnJoinedChannel += OnJoinedChannel; _client.OnChatCommandReceived += OnCommandReceived; _client.OnCommunitySubscription += OnSubBomb; _client.OnBeingHosted += OnBeingHosted; _client.OnRaidNotification += OnRaidNotification; _client.OnDisconnected += OnDisconnected; _client.OnError += OnError; _client.OnConnectionError += OnConnectionError; _client.Connect(); _liveStreamMonitor = _twitchLiveStreamMonitorFactory.Get(); _liveStreamMonitor.SetChannelsByName(new List <string> { _streamerChannel }); _liveStreamMonitor.OnStreamOnline += OnStreamOnline; _liveStreamMonitor.OnStreamOffline += OnStreamOffline; _liveStreamMonitor.OnServiceStarted += OnStreamMonitorStarted; //this.liveStreamMonitor.OnStreamUpdate += OnStreamUpdate; _liveStreamMonitor.Start(); _pubsub.OnPubSubServiceConnected += OnPubSubConnected; _pubsub.OnBitsReceived += OnBitsReceived; _pubsub.OnListenResponse += OnListenResponse; _pubsub.OnChannelSubscription += OnSub; _pubsub.Connect(); }
public TwitchEvents(ConnectionCredentials credentials, string username) { try { Dictionary <string, string> channels = new Dictionary <string, string>() { { "phenomalytv", "PaymoneyWubby" } }; livemonitor = new LiveStreamMonitorService(TwitchApi, 20); livemonitor.SetChannelsByName(channels.Keys.ToList()); livemonitor.Start(); livemonitor.OnStreamOnline += OnStreamOnline; livemonitor.OnStreamOffline += OnStreamOffline; } catch (Exception ex) { Console.WriteLine(ex); } try { client = new TwitchClient { AutoReListenOnException = true }; client.Initialize(credentials, username); client.Connect(); client.OnConnected += OnConnected; client.OnReconnected += OnReconnected; client.OnDisconnected += OnDisconnected; client.OnNewSubscriber += OnNewSubscriber; client.OnMessageReceived += OnMessageReceived; pubsub.ListenToBitsEvents("109598326"); pubsub.ListenToFollows("109598326"); pubsub.ListenToSubscriptions("109598326"); pubsub.OnFollow += OnNewFollower; pubsub.OnBitsReceived += OnBitsReceived; pubsub.Connect(); if (!client.IsConnected) { throw new NotImplementedException("Error out no connection"); } } catch (Exception ex) { Console.WriteLine(ex); } }
public ConsoleApplication( ILogger <ConsoleApplication> logger, IOptions <AppSettings> config, ITwitchAPI twitchApi, IApiSettings apiSettings, IWebhookService webhookService ) { _logger = logger; _config = config; _twitchApi = twitchApi; _apiSettings = apiSettings; _webhookService = webhookService; _twitchMonitor = new LiveStreamMonitorService(_twitchApi, config.Value.TwitchApiCheckIntervalSeconds); _token = new CancellationToken(); }
private static void StartMonitor() { try { _StreamMonitor = new LiveStreamMonitorService(_TwitchApi, 30); _StreamMonitor.SetChannelsByName(SettingsManager.Configuration.TwitchStream.UsernameAsList); _StreamMonitor.Start(); _StreamMonitor.OnStreamOnline += OnStreamOnline; _StreamMonitor.OnStreamOffline += OnStreamOffline; LoggingManager.Log.Info($"Stream monitoring is running for: {SettingsManager.Configuration.TwitchStream.DisplayName}"); } catch (Exception ex) { LoggingManager.Log.Error(ex); } }
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); }
private static async Task BindHandlers() { twitchAPI = new TwitchAPI(); twitchAPI.Settings.ClientId = CredentialsKeeper.TWITCH_CID; monitor = new LiveStreamMonitorService(twitchAPI, 60); Console.WriteLine("Starting binds"); monitor.SetChannelsByName(UserProvider.GetTwitchUsers()); monitor.OnStreamOnline += StreamEventHandler.OnStreamOnline; monitor.OnStreamOffline += StreamEventHandler.OnStreamOffline; monitor.OnServiceStarted += StreamEventHandler.OnServiceStarted; monitor.Start(); Console.WriteLine("Binds finished"); }
// Start the Twitch API service to monitor Livestreams private void StartApi() { TwitchAPI twitchAPI = new TwitchAPI(); twitchAPI.Settings.ClientId = CredentialsKeeper.TwitchId; twitchAPI.Settings.AccessToken = CredentialsKeeper.TwitchSecret; LiveStreamMonitorService monitor = new LiveStreamMonitorService(twitchAPI, 60); Console.WriteLine("Starting Twitch API services"); monitor.SetChannelsByName(UserProvider.GetTwitchUsers()); monitor.OnStreamOnline += _eventHandler.OnStreamOnline; monitor.OnStreamOffline += _eventHandler.OnStreamOffline; monitor.OnServiceStarted += _eventHandler.OnServiceStarted; monitor.Start(); Console.WriteLine("Twitch API services started"); }
public StreamNotifier(DiscordSocketClient discordClient) { Configuration = ConfigurationHost.Current; DiscordClient = discordClient; TwitchAPI = new TwitchAPI(); TwitchAPI.Settings.ClientId = EnvUtils.VariableOrThrow(Constants.Environment.TwitchClientId); TwitchAPI.Settings.AccessToken = EnvUtils.VariableOrThrow(Constants.Environment.TwitchBotToken); LiveStreamMonitor = new LiveStreamMonitorService(TwitchAPI, 20); LiveStreamMonitor.SetChannelsByName(Configuration.TwitchFriends.ToList()); LiveStreamMonitor.OnStreamOnline += async(s, e) => { await LiveStreamMonitor_OnStreamOnline(e); }; ConfigurationHost.ConfigurationChanged += ConfigurationChanged; }
public async void LiveStreams_Contains_UserId_When_ServiceUpdated() { var usersFollowsResponseJson = JMock.Of <GetStreamsResponse>(o => o.Streams == new[] { Mock.Of <Stream>(u => u.UserId == "UserId") } ); _api = TwitchLibMock.TwitchApi( ("https://api.twitch.tv/helix/streams", usersFollowsResponseJson) ); _liveStreamMonitor = new LiveStreamMonitorService(_api); _liveStreamMonitor.SetChannelsById(Utils.CreateListWithStrings("UserId")); await _liveStreamMonitor.UpdateLiveStreamersAsync(); Assert.True(_liveStreamMonitor.LiveStreams.ContainsKey("UserId")); }
public ServiceMonitor(IConfiguration config) { _config = config; var channels = _config.GetSection("Values:Twitch:Channels").Get <List <string> >(); _processFileName = $@"{_config["Values:BotAssembly:Directory"]}\{_config["Values:BotAssembly:Name"]}"; var twitchApi = new TwitchAPI(); twitchApi.Settings.ClientId = config["Values:Twitch:ClientId"]; twitchApi.Settings.AccessToken = config["Values:Twitch:AccessToken"]; _liveStreamMonitorService = new LiveStreamMonitorService(twitchApi); _liveStreamMonitorService.SetChannelsByName(channels); _liveStreamMonitorService.OnStreamOnline += async(s, e) => await LiveStreamMonitorServiceOnOnStreamOnline(s, e); _liveStreamMonitorService.OnStreamOffline += async(s, e) => await LiveStreamMonitorServiceOnOnStreamOffline(s, e); }
public async void Register() { if (this.monitor == null) { this.monitor = new LiveStreamMonitorService(this.twitchAPI); List <string> channelIDs = (await this.twitchAPI.Helix.Users.GetUsersAsync(logins: new List <string> { this.twitchChannel })) .Users .Select(x => x.Id) .ToList(); this.monitor.SetChannelsById(channelIDs); this.monitor.OnStreamOnline += this.OnStreamOnline; this.monitor.OnStreamOffline += this.OnStreamOffline; this.monitor.OnStreamUpdate += this.OnStreamUpdate; } this.monitor.Start(); }
private async Task ConfigLiveMonitorAsync() { using (var scope = _serviceProvider.CreateScope()) { var guildService = scope.ServiceProvider.GetRequiredService <IGuildService>(); _api = new TwitchAPI(); _api.Settings.ClientId = "d0qgyohqojd71mpvsz7p0ldre5lfic"; _api.Settings.AccessToken = "ciif9s2t2hhrn8tcx92e9p6g8xxpbq"; _monitor = new LiveStreamMonitorService(_api, 60); var guilds = await guildService.GetAllAsync(); var items = guilds.Select(g => g.TwitchPlugin.TwitchChannelSubscriptions).ToList(); var channelsToMonitor = new List <string>(); foreach (var subscription in items .SelectMany(item => item .Where(subscription => !channelsToMonitor.Contains(subscription.StreamerId)))) { channelsToMonitor.Add(subscription.StreamerId); } _monitor.SetChannelsById(channelsToMonitor); _monitor.OnStreamOnline += Monitor_OnStreamOnline; _monitor.OnStreamOffline += Monitor_OnStreamOffline; _monitor.OnStreamUpdate += Monitor_OnStreamUpdate; _monitor.OnServiceStarted += Monitor_OnServiceStarted; _monitor.OnChannelsSet += Monitor_OnChannelsSet; _monitor.Start(); await Task.Delay(-1); } }
public void OnServiceTick_Raised_When_ServiceTicked() { var usersFollowsResponseJson = JMock.Of <GetStreamsResponse>(o => o.Streams == new[] { Mock.Of <Stream>() } ); _api = TwitchLibMock.TwitchApi( ("https://api.twitch.tv/helix/users/follows", usersFollowsResponseJson) ); var signalEvent = new ManualResetEvent(false); _liveStreamMonitor = new LiveStreamMonitorService(_api, checkIntervalInSeconds: 1); _liveStreamMonitor.SetChannelsById(Utils.CreateListWithEmptyString()); _liveStreamMonitor.OnServiceTick += (sender, e) => signalEvent.Set(); _liveStreamMonitor.Start(); Assert.True(signalEvent.WaitOne(1500)); }
public async static Task StartLiveMonitorAsync(DiscordSocketClient client) { _client = client; API = new TwitchAPI(); API.Settings.ClientId = AppSettings.Settings["twitchClientId"]; HttpResponseMessage results = await httpClient.PostAsync($"https://id.twitch.tv/oauth2/token?client_id={API.Settings.ClientId}&client_secret={AppSettings.Settings["twitchClientSecret"]}&grant_type=client_credentials", new FormUrlEncodedContent(new KeyValuePair <string, string> [0])); Log.Information($"Results: {results.ToString()}"); if (!results.IsSuccessStatusCode) { Log.Error($"Attempt to get Twitch Access Token Failed for reason: {await results.Content.ReadAsStringAsync()}"); } else { TwitchOAuthResponse twitchResponse = JsonConvert.DeserializeObject <TwitchOAuthResponse>(await results.Content.ReadAsStringAsync()); Log.Information($"Twitch Access Token successfully retrieved"); API.Settings.AccessToken = twitchResponse.access_token; } Monitor = new LiveStreamMonitorService(API, 15); await UpdateMonitorList(); await Task.Delay(-1); }
public async Task ConfigLiveMonitorAsync() { API = new TwitchAPI(); API.Settings.ClientId = "jxjz93r6z6x0n09a7khp6wq4dvle8k"; API.Settings.Secret = "mlabuaroc67pgokd5kc8hqulokkmsd"; API.Settings.AccessToken = API.Helix.Extensions.GetAccessToken(); Monitor = new LiveStreamMonitorService(API, 60); List <string> lst = new List <string> { "67794893" }; //Monitor.SetChannelsById(lst); Monitor.SetChannelsById(lst); Monitor.OnStreamOnline += Monitor_OnStreamOnline; Monitor.OnStreamOffline += Monitor_OnStreamOffline; Monitor.OnStreamUpdate += Monitor_OnStreamUpdate; Monitor.OnServiceStarted += Monitor_OnServiceStarted; Monitor.OnChannelsSet += Monitor_OnChannelsSet; Monitor.Start(); //Keep at the end! await Task.Delay(-1); }
private async Task ConfigLiveMonitorAsync() { api = new TwitchAPI(); api.Settings.ClientId = Resources.client_id; api.Settings.AccessToken = Resources.bot_access_token; Monitor = new LiveStreamMonitorService(api, 60); List <string> lst = new List <string> { Resources.channel_name }; Monitor.SetChannelsById(lst); Monitor.OnStreamOnline += Monitor_OnStreamOnline; Monitor.OnStreamOffline += Monitor_OnStreamOffline; Monitor.OnStreamUpdate += Monitor_OnStreamUpdate; Monitor.OnServiceStarted += Monitor_OnServiceStarted; Monitor.OnChannelsSet += Monitor_OnChannelsSet; followerService = new FollowerService(api); followerService.SetChannelsByName(channel); followerService.OnNewFollowersDetected += FollowerService_OnNewFollowersDetected; //followerService.OnServiceStopped += (o, e) => Console.WriteLine("Follower service started"); //followerService.OnServiceStarted += (o, e) => Console.WriteLine($"Follower service started with interval: seconds."); followerService.OnServiceStopped += (o, e) => form.WriteChat("Follower service started", false); followerService.OnServiceStarted += (o, e) => form.WriteChat($"Follower service started with default interval", false); followerService.Start(); Monitor.Start(); //Keep at the end! await Task.Delay(-1); }
static TwitchUtility() { if (Ditto.Twitch == null) { return; } Links = new ConcurrentDictionary <int, Link>(); IsMonitoring = false; Ditto.Connected += () => { var _ = Task.Run(async() => { _cancellationTokenSource?.Cancel(); _cancellationTokenSource = new CancellationTokenSource(); await Ditto.Database.ReadAsync((uow) => { Links = new ConcurrentDictionary <int, Link>( uow.Links.GetAllWithLinks() .Where(e => e.Type == LinkType.Twitch) .Select(i => new KeyValuePair <int, Link>(i.Id, i)) ); }); try { if (Monitor == null) { Monitor = new LiveStreamMonitorService(Ditto.Twitch, 60); Monitor.OnStreamOnline += Monitor_OnStreamOnline; Monitor.OnStreamOffline += Monitor_OnStreamOffline; Monitor.OnStreamUpdate += Monitor_OnStreamUpdate; // Start monitoring the twitch links, this will notify users when a stream switches it's live status. var channels = Links.ToList().Select(e => e.Value.Value.Split("|", StringSplitOptions.RemoveEmptyEntries).FirstOrDefault()).ToList(); MonitorChannels(channels); // Instantly update the monitoring service on load. if (Links.Count > 0) { await Monitor.UpdateLiveStreamersAsync(true).ConfigureAwait(false); } } } catch (Exception ex) { Log.Error($"Twitch | {ex}"); } }); return(Task.CompletedTask); }; Ditto.Exit += () => { _cancellationTokenSource?.Cancel(); Links?.Clear(); return(Task.CompletedTask); }; }
public void SetChannelsByName_Throws_ArgumentNullException_When_ChannelsArgumentNull() { _liveStreamMonitor = new LiveStreamMonitorService(_api); AssertException.Throws <ArgumentNullException>(() => _liveStreamMonitor.SetChannelsByName(null)); }
private void Reconnect() { var api = _twitchApiFactory.Get(); _monitorService = new LiveStreamMonitorService(api); }
public void SetChannelsByName_Throws_ArgumentException_When_ChannelsArgumentEmpty() { _liveStreamMonitor = new LiveStreamMonitorService(_api); AssertException.Throws <ArgumentException>(ChannelListEmptyExceptionMessage, () => _liveStreamMonitor.SetChannelsByName(new List <string>())); }
public void Start_Throws_InvalidOperationException_When_ChannelsNotSet() { _liveStreamMonitor = new LiveStreamMonitorService(_api); AssertException.Throws <InvalidOperationException>(ChannelsNotSetExceptionMessage, () => _liveStreamMonitor.Start()); }
public async Task CreateStreamMonoAsync() { // Check to see if a _liveStreamService has already been created if (_liveStreamMonitor != null) { return; // If one has, don't make a new one. Causes bot to send tons of duplicate alerts. } StreamModels = new Dictionary <string, StreamModel>(); await Task.Run(GetStreamerList); await GetStreamerIdDictAsync(); await Console.Out.WriteLineAsync($"{DateTime.UtcNow.ToString("hh:mm:ss")} [StreamMonoService]: GUILD COUNT {_discord.Guilds.Count}"); List <SocketTextChannel> notifChannels = new List <SocketTextChannel>(); IEnumerator <SocketGuild> eguilds = _discord.Guilds.GetEnumerator(); eguilds.MoveNext(); while (eguilds.Current != null) { int currentPos = 0; await Console.Out.WriteLineAsync($"{DateTime.UtcNow.ToString("hh:mm:ss")} [StreamMonoService]: Current Guild: {eguilds.Current.Name}"); IEnumerator <SocketTextChannel> echannels = eguilds.Current.TextChannels.GetEnumerator(); echannels.MoveNext(); while (currentPos != eguilds.Current.TextChannels.Count - 1) { currentPos++; if (echannels.Current != null && echannels.Current.Name.Contains(NotifChannelName)) { notifChannels.Add(echannels.Current); break; } echannels.MoveNext(); } echannels.Dispose(); eguilds.MoveNext(); } eguilds.Dispose(); StreamNotifChannels = notifChannels; if (StreamNotifChannels.Any()) { await Console.Out.WriteLineAsync($"{DateTime.UtcNow.ToString("hh:mm:ss")} [StreamMonoService]: Successfully collected Stream Update Notification channels. Amount: {StreamNotifChannels.Count()}"); } else { await Console.Out.WriteLineAsync($"{DateTime.UtcNow.ToString("hh:mm:ss")} [StreamMonoService ERROR]: No Stream Update Notification channels were found!"); } try { StreamProfileImages = await GetProfImgUrlsAsync(StreamIdList); } catch (TwitchLib.Api.Core.Exceptions.InternalServerErrorException ex) { if (CreationAttempts == 1) { await Console.Out.WriteLineAsync($"{DateTime.UtcNow.ToString("hh:mm:ss")} [StreamMonoService]: Maximum number of creation attempts exceeded. Live Stream Monitor Service is no longer available."); CreationAttempts = 0; return; } await Console.Out.WriteLineAsync($"{ex.GetType().Name} - Attempt #{CreationAttempts}: Error collecting Profile Images. Attempting to verify the streamers before trying again."); VerifyAndGetStreamIdAsync().RunSynchronously(); CreationAttempts++; await CreateStreamMonoAsync(); } _liveStreamMonitor = new LiveStreamMonitorService(TwApi, UpdInt, 100); _liveStreamMonitor.OnServiceTick += OnServiceTickEvent; _liveStreamMonitor.OnChannelsSet += OnChannelsSetEvent; _liveStreamMonitor.OnServiceStarted += OnServiceStartedEvent; _liveStreamMonitor.OnServiceStopped += OnServiceStoppedEvent; _liveStreamMonitor.OnStreamOnline += OnStreamOnlineEventAsync; _liveStreamMonitor.OnStreamOffline += OnStreamOfflineEvent; try { _liveStreamMonitor.SetChannelsById(StreamIdList); _liveStreamMonitor.Start(); } catch (ArgumentException e) { Console.WriteLine($"{DateTime.UtcNow.ToString("hh:mm:ss")} [StreamMonoService]: Stream list is empty. Start the service manually using \";lsm start\" once you have added at least one streamer."); } await Console.Out.WriteLineAsync($"{DateTime.UtcNow.ToString("hh:mm:ss")} [StreamMonoService]: Was service enabled? - {_liveStreamMonitor.Enabled}"); }
public void Stop_Throws_InvalidOperationException_When_ServiceAlreadyStopped() { _liveStreamMonitor = new LiveStreamMonitorService(_api); AssertException.Throws <InvalidOperationException>(AlreadyStoppedExceptionMessage, () => _liveStreamMonitor.Stop()); }