Esempio n. 1
0
        static async Task Main()
        {
            // listen for cancel events
            RegisterCancels();

            // listen for unhandled exceptions in the application
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            // set up logging
            EnsureLogs();

            Logger.LogInfo("Application is starting");

            // load the configuration file into memory
            await ReadConfiguration();

            // validate the configuration; throws if an error is found
            ValidateConfiguration();

            // authenticate user
            var oAuthHandler = new OAuthHandler(
                Config.ClientId.Trim(),
                Config.ClientToken.Trim(),
                Config.RedirectUri.Trim()
                );

            Logger.LogInfo("Begin authentication...");

            // get the access token for a user
            var token = await oAuthHandler.AuthorizeOAuth();

            if (token != null)
            {
                Logger.LogInfo("Twitch authentication finished successfully");
            }
            else
            {
                Logger.LogError("Error while authenticating with Twitch. The application will now exit.");
                Environment.Exit(1);
                return;
            }

            // start communicating with Twitch
            using var twitchHandler = new TwitchHandler(
                      token,
                      Config.ClientId.Trim(),
                      Config.ClientToken.Trim(),
                      Config.OutputFile.Trim(),
                      Config.OutputFormat.Trim()
                      );
            await twitchHandler.Init();

            // wait for an exit event to continue
            try
            {
                await ExitToken.Token;
            }
            catch { }
        }
Esempio n. 2
0
        public async Task test(params string[] args)
        {
            List <TwitchHandler.TwitchData> userInfo = await TwitchHandler.GetTwitchInfo(args[1]);

            Color        TwitchColour = new Color(100, 65, 165);
            EmbedBuilder eb           = new EmbedBuilder();

            eb.Title = userInfo[0].display_name;
            eb.Color = TwitchColour;
            eb.WithCurrentTimestamp();

            switch (args[0].ToLower())
            {
            case "channel":
                eb.Description = userInfo[0].description;
                eb.Footer      = new EmbedFooterBuilder()
                {
                    IconUrl = userInfo[0].profile_image_url,
                    Text    = $"created at: {userInfo[0].created_at}"
                };
                eb.AddField("Twitch account information", $"Link to profile: https://www.twitch.tv/{args[1]} \nView count: {userInfo[0].view_count}\nUser id: {userInfo[0].id}");
                break;

            case "av":
            case "avatar":
            case "pfp":
                eb.Description = $"Here's the profile picture for {userInfo[0].display_name}:";
                eb.ImageUrl    = userInfo[0].profile_image_url;
                break;

            case "livetest":
                List <TwitchHandler.UserStreams> userStreams = await TwitchHandler.GetStreams(args[1]);

                if (userStreams.Count == 0)
                {
                    await Context.Message.ReplyAsync("", false, Global.EmbedMessage("Error", $"The user {args[1]} is not currently live on Twitch.", false, Color.Red).Build());

                    return;
                }

                eb.Title       = $"{args[1]} is live on Twitch!";
                eb.ImageUrl    = $"https://static-cdn.jtvnw.net/previews-ttv/live_user_{args[1]}.jpg";
                eb.Description = $"[Watch {args[1]} live on Twitch!](https://twitch.tv/{args[1]})";
                eb.AddField("Stream information", $"title: {userStreams[0].title}\ngame name: {userStreams[0].game_name}\nviewer count: {userStreams[0].viewer_count}");
                eb.Footer = new EmbedFooterBuilder()
                {
                    IconUrl = userInfo[0].profile_image_url,
                    Text    = $"Live started at: {userStreams[0].started_at}"
                };

                break;
            }

            await ReplyAsync("", false, eb.Build());
        }
Esempio n. 3
0
        public MessageHandler(MainWindow w)
        {
            _w = w;
            DiscordHandler discord = new DiscordHandler();
            TwitchHandler  twitch  = new TwitchHandler();
            TwitterHandler twitter = new TwitterHandler();

            Messengers.Add(discord);
            Messengers.Add(twitch);
            Messengers.Add(twitter);
            RunMessengers();
        }
Esempio n. 4
0
        public async void CheckLiveUsers()
        {
            MongoClient    mongoClient = new MongoClient(Global.Mongoconnstr);
            IMongoDatabase database    = mongoClient.GetDatabase("finlay");
            IMongoCollection <BsonDocument> collection = database.GetCollection <BsonDocument>("guilds");
            ulong        _id = 0;
            EmbedBuilder eb  = new EmbedBuilder();
            List <TwitchHandler.TwitchData> userInfo;
            Color TwitchColour = new Color(100, 65, 165);

            eb.Color = TwitchColour;
            string        itemVal     = "";
            BsonDocument  item        = null;
            List <string> stringArray = new List <string>();
            List <TwitchHandler.UserStreams> userStreams = new List <TwitchHandler.UserStreams>();
            string                     modlogchannel     = "";
            SocketTextChannel          logchannel;
            Dictionary <string, ulong> AlreadySent = new Dictionary <string, ulong>();

            while (true)
            {
                foreach (SocketGuild guild in _client.Guilds)
                {
                    _id  = guild.Id;
                    item = await collection.Find(Builders <BsonDocument> .Filter.Eq("_id", _id)).FirstOrDefaultAsync();

                    try
                    {
                        itemVal = item?.GetValue("TwitchUsers").ToJson();
                    }

                    catch { continue; }

                    if (itemVal != null)
                    {
                        stringArray = JsonConvert.DeserializeObject <string[]>(itemVal).ToList();

                        foreach (string user in stringArray)
                        {
                            userStreams = await TwitchHandler.GetStreams(user);

                            if (userStreams.Count == 0)
                            {
                                if (AlreadySent.ContainsKey(user))
                                {
                                    List <string> IdenticalKeys = AlreadySent.Where(x => x.Key == user).Select(x => x.Key).ToList();

                                    foreach (string key in IdenticalKeys)
                                    {
                                        AlreadySent.Remove(key);
                                    }
                                }
                            }

                            if (AlreadySent.ContainsKey(user))
                            {
                                continue;
                            }

                            modlogchannel = await TwitchHandler.GetTwitchChannel(guild);

                            if (modlogchannel == "0")
                            {
                                continue;
                            }

                            logchannel = guild.GetTextChannel(Convert.ToUInt64(modlogchannel));
                            userInfo   = await TwitchHandler.GetTwitchInfo(user);

                            eb.Title       = $"{user} is live on Twitch!";
                            eb.ImageUrl    = $"https://static-cdn.jtvnw.net/previews-ttv/live_user_{user}.jpg";
                            eb.Description = $"[Watch {user} live on Twitch!](https://twitch.tv/{user})";
                            eb.AddField("Stream information", $"title: {userStreams[0].title}\ngame name: {userStreams[0].game_name}");
                            eb.Footer = new EmbedFooterBuilder()
                            {
                                IconUrl = userInfo[0].profile_image_url,
                                Text    = $"Live started at: {userStreams[0].started_at}"
                            };
                            AlreadySent.Add(user, guild.Id);
                            //AlreadySent.Append(user);
                            await logchannel.SendMessageAsync("", false, eb.Build());
                        }
                    }
                }
            }
        }
Esempio n. 5
0
 public TwitchService(IServiceProvider services)
 {
     _client = services.GetRequiredService <DiscordShardedClient>();
     //CheckLiveUsers();
     TwitchHandler.GetAccessToken().Wait();
 }
Esempio n. 6
0
        public async Task NotifyTwitch(string user)
        {
            SocketGuildUser GuildUser = Context.Guild.GetUser(Context.User.Id);

            if (GuildUser.GuildPermissions.ManageMessages || Global.DevUIDs.Contains(Context.Message.Author.Id))
            {
                List <TwitchHandler.TwitchData> ValidateUser = await TwitchHandler.GetTwitchInfo(user);

                if (ValidateUser.Count == 0)
                {
                    await Context.Message.ReplyAsync("", false, Global.EmbedMessage("Error", $"The user {user} could not be found on Twitch.", false, Color.Red).Build());

                    return;
                }

                MongoClient    mongoClient = new MongoClient(Global.Mongoconnstr);
                IMongoDatabase database    = mongoClient.GetDatabase("finlay");
                IMongoCollection <BsonDocument> collection = database.GetCollection <BsonDocument>("guilds");
                ulong        _id           = Context.Guild.Id;
                BsonDocument guildDocument = await MongoHandler.FindById(collection, _id);

                if (guildDocument == null)
                {
                    MongoHandler.InsertGuild(_id);
                }

                BsonDocument guild = await collection.Find(Builders <BsonDocument> .Filter.Eq("_id", _id)).FirstOrDefaultAsync();

                try
                {
                    string        itemVal     = guild?.GetValue("TwitchUsers").ToJson();
                    List <string> stringArray = JsonConvert.DeserializeObject <string[]>(itemVal).ToList();
                    Regex         re          = new Regex(@"\b(" + string.Join("|", stringArray.Select(word => string.Join(@"\s*", word.ToCharArray()))) + @")\b", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

                    if (re.IsMatch(user))
                    {
                        EmbedBuilder errembed = new EmbedBuilder();
                        errembed.WithTitle("Error");
                        errembed.WithDescription("This user is already included in the notification list!");
                        errembed.WithColor(Color.Red);
                        errembed.WithAuthor(Context.Message.Author);
                        await Context.Message.ReplyAsync("", false, errembed.Build());

                        return;
                    }
                }

                catch { }

                if (guild == null)
                {
                    BsonDocument document = new BsonDocument {
                        { "_id", (decimal)_id }, { "TwitchUsers", user }
                    };
                    collection.InsertOne(document);
                }

                else
                {
                    collection.UpdateOne(Builders <BsonDocument> .Filter.Eq("_id", _id), Builders <BsonDocument> .Update.Push("TwitchUsers", user));
                }

                EmbedBuilder embed = new EmbedBuilder();
                embed.WithTitle("Twitch notification user list updated!");
                embed.WithDescription($"Successfully added notifications for when {user} goes live on Twitch!");
                embed.WithColor(Color.Green);
                embed.WithAuthor(Context.Message.Author);
                embed.WithCurrentTimestamp();
                await Context.Message.Channel.SendMessageAsync("", false, embed.Build());
            }

            else
            {
                await Context.Channel.TriggerTypingAsync();

                await Context.Message.Channel.SendMessageAsync("", false, new EmbedBuilder()
                {
                    Color       = Color.LightOrange,
                    Title       = "You don't have Permission!",
                    Description = $"Sorry, {Context.Message.Author.Mention} but you do not have permission to use this command.",
                    Footer      = new EmbedFooterBuilder()
                    {
                        IconUrl = Context.User.GetAvatarUrl() ?? Context.User.GetDefaultAvatarUrl(),
                        Text    = $"{Context.User}"
                    },
                }.WithCurrentTimestamp().Build());
            }
        }