Example #1
0
        /// <summary>
        /// Checks which users are live, along with who has gone offline.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Tick(object sender, ElapsedEventArgs e)
        {
            if (ticking == true)
            {
                return;
            }
            ticking = true;
            List <string> liveUsers = new List <string>();
            var           s         = await GetStreams();

            if (s != null)
            {
                for (int i = 0; i < s.Length; i++)
                {
                    liveUsers.Add(s[i].UserName);
                    // User is/was live.
                    if (LiveStreams.ContainsKey(s[i].UserName))
                    {
                        // It's the same stream.
                        if (LiveStreams[s[i].UserName].Id == s[i].Id)
                        {
                            LiveStreams[s[i].UserName] = s[i];
                            // Invoke event.
                            OnStreamArgs onStreamUpdateArgs = new OnStreamArgs(s[i].UserName, s[i]);
                            OnStreamUpdate?.Invoke(this, onStreamUpdateArgs);
                            continue;
                        }
                        // Different stream.
                        else
                        {
                            if (LiveStreams.TryRemove(s[i].UserName, out Stream v))
                            {
                                if (LiveStreams.TryAdd(s[i].UserName, s[i]))
                                {
                                    // Invoke event.
                                    OnStreamArgs onStreamOnlineArgs = new OnStreamArgs(s[i].UserName, s[i]);
                                    OnStreamOnline?.Invoke(this, onStreamOnlineArgs);
                                }
                            }
                        }
                    }
                    // User was not live before.
                    else
                    {
                        if (LiveStreams.TryAdd(s[i].UserName, s[i]))
                        {
                            // Invoke event.
                            OnStreamArgs oso = new OnStreamArgs(s[i].UserName, s[i]);
                            OnStreamOnline?.Invoke(this, oso);
                        }
                    }
                }

                Cleanup(liveUsers);
            }
            ticking = false;

            SaveLoadService.Save(monitoredUsersFilename, LiveStreams);
        }
Example #2
0
        /// <summary>
        /// Cleanup streams that have gone offline.
        /// </summary>
        /// <param name="users"></param>
        private void Cleanup(List <string> users)
        {
            List <string> streamsToRemove = new List <string>();

            foreach (string k in LiveStreams.Keys)
            {
                if (!users.Contains(k))
                {
                    streamsToRemove.Add(k);
                }
            }
            foreach (string s in streamsToRemove)
            {
                OnStreamArgs offlineArgs = new OnStreamArgs(s, LiveStreams[s]);
                OnStreamOffline?.Invoke(this, offlineArgs);
                LiveStreams.TryRemove(s, out Stream v);
            }
        }
Example #3
0
 private void OnStreamOffline(object sender, OnStreamArgs e)
 {
 }
Example #4
0
        private async void OnStreamOnline(object sender, OnStreamArgs e)
        {
            try
            {
                foreach (TwitchGuildDefinition guild in guilds)
                {
                    //If the user should be reported on in this guild.
                    if (!String.IsNullOrEmpty(guild.users.Find(x => x.ToLower() == e.Stream.UserName.ToLower())))
                    {
                        //Get the text channel.
                        var textChannel = client.GetGuild(guild.guildID).TextChannels.FirstOrDefault(x => x.Id == guild.textChannelID);

                        //Channel doesn't exist, skip this one.
                        if (textChannel == null)
                        {
                            Console.WriteLine($"Text channel {guild.textChannelID} in {guild.guildID} does not exist.");
                            continue;
                        }

                        //Grab data on the stream and user.
                        var userChannel    = (await api.V5.Channels.GetChannelByIDAsync(e.Stream.UserId));
                        var sGame          = (await api.Helix.Games.GetGamesAsync(new List <string>()
                        {
                            e.Stream.GameId
                        }));
                        var streamGame     = sGame.Games.Count() > 0 ? sGame.Games[0] : null;
                        var streamGameName = streamGame == null ? "?" : streamGame.Name;

                        TimeSpan timeLive       = (DateTime.UtcNow - e.Stream.StartedAt);
                        int      hoursUp        = ((int)timeLive.TotalMinutes) / 60;
                        int      minutesUp      = (int)timeLive.TotalMinutes - (60 * hoursUp);
                        string   timeLiveString = timeLive.TotalMinutes < 60 ? $"{(int)timeLive.TotalMinutes} minutes."
                            : $"{hoursUp} hours, {minutesUp} minutes.";

                        //Build the message.
                        var output = new EmbedBuilder()
                                     .WithTitle($"{e.Stream.UserName} is online!")
                                     .AddField($"Playing {streamGameName}", $"[{e.Stream.Title}](https://www.twitch.tv/{e.Stream.UserName})")
                                     .AddField($"Current Viewers:", $"{e.Stream.ViewerCount}")
                                     .AddField("Up For:", timeLiveString);

                        output.Footer = new EmbedFooterBuilder
                        {
                            Text = $"{userChannel.Followers} followers, {userChannel.Views} total views."
                        };

                        switch (guild.previewMode)
                        {
                        case 1:
                            output.WithImageUrl($"{e.Stream.ThumbnailUrl.Replace("{width}", "1280").Replace("{height}", "720")}?{DateTime.UtcNow.Minute}");
                            if (streamGame != null)
                            {
                                string boxArtURL = streamGame.BoxArtUrl.Replace("{width}", "425").Replace("{height}", "550");
                                try
                                {
                                    output.WithThumbnailUrl(boxArtURL);
                                }
                                catch (Exception exception)
                                {
                                    Console.WriteLine($"Twitch error with url: {boxArtURL}");
                                }
                            }
                            break;

                        case 2:
                            if (streamGame != null)
                            {
                                output.WithThumbnailUrl(streamGame.BoxArtUrl.Replace("{width}", "425").Replace("{height}", "550"));
                            }
                            break;
                        }


                        await textChannel.SendMessageAsync("", false, output.Build());
                    }
                }
            }catch (Exception exc)
            {
                Console.WriteLine($"Exception thrown while reporting online stream. {exc.Message}");
            }
        }