Esempio n. 1
6
 static void Main(string[] args)
 {
     var reddit = new Reddit();
     while (reddit.User == null)
     {
         Console.Write("Username: "******"Password: "******"Logging in...");
             reddit.LogIn(username, password);
         }
         catch (AuthenticationException)
         {
             Console.WriteLine("Incorrect login.");
         }
     }
     var subreddit = reddit.GetSubreddit("pokemon");
     var posts = subreddit.GetNew();
     foreach (var post in posts.Take(25))
         Console.WriteLine("/u/{0}: (+{1}-{2}:{3}) {4}", post.AuthorName, post.Upvotes, post.Downvotes, post.Score, post.Title);
     Console.ReadKey(true);
 }
Esempio n. 2
5
 static void Main(string[] args)
 {
     var reddit = new Reddit();
     int backDays;
     try
     {
         reddit.User = reddit.LogIn(ModUserName, ModPassword);
         _sub = reddit.GetSubreddit(SubReddit);
         int.TryParse(ReadBackDays, out backDays);
         if(backDays<1)
         {
             Console.WriteLine("Invalid value for readBackDays in config file. Please enter an integer greater than 0.");
             throw new Exception();
         }
     }
     catch
     {
         Console.WriteLine("Configuration Error. Please confirm values in config file.");
         Console.WriteLine("Press Enter to exit.");
         Console.Read();
         return;
     }
     while (true)
     {
         try
         {
             AssignFlairs(TriggerText, DateTime.Today.AddDays(backDays));
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.Message);
         }
     }
 }
 public void Launch()
 {
     var reddit = new Reddit();
     var user = reddit.LogIn("bot_wallpaper", "qwerty");
     var subreddit = reddit.GetSubreddit("/r/botwallpaper");
     DateTime today = DateTime.Today;
     if (today.DayOfWeek == DayOfWeek.Sunday && !sentMessages)
     {
         using (StreamReader sr = new StreamReader("subreddits.txt"))
         {
             string line;
             while ((line = sr.ReadLine()) != null)
             {
                 SubredditProcessor wallpaper = new SubredditProcessor(
                     line);
                 wallpaper.Launch();
             }
             Console.WriteLine("ServerListener: Created subreddits");
         }
         sentMessages = true;
     }
     else if (today.DayOfWeek == DayOfWeek.Monday)
     {
         sentMessages = false;
     }
 }
 public void Launch()
 {
     List<String> title = new List<string>();
     List<String> urls = new List<string>();
     string body = "";
     var reddit = new Reddit();
     var user = reddit.LogIn("bot_wallpaper", "qwerty");
     var subreddit = reddit.GetSubreddit("/r/" + _wallpaperType);
     foreach (var post in subreddit.GetTop(FromTime.Week).Take(25))
     {
         if (_resolution == "null")
         {
             title.Add(post.Title);
             urls.Add(post.Url.ToString());
         }
         else if (post.Title.Contains(_resolution))
         {
             title.Add(post.Title);
             urls.Add(post.Url.ToString());
         }
     }
     for (int i = 0; i < title.Count; i++)
     {
         body += "[" + title[i] + "](" + urls[i] + ") \n\n";
     }
     reddit.ComposePrivateMessage("Wallpapers!", "#Here is the top wallpapers of this week in **/r/" + _wallpaperType + "** \n\n" + body + "\n\n I am a bot!", _username, "", "");
     Console.WriteLine("UserProcessor: Message sent to " + _username);
 }
Esempio n. 5
0
        public Form2(Reddit reddit)
        {
            InitializeComponent();
            radioButton1.Checked = true;
            this.reddit = reddit;
            default_subredit = reddit.FrontPage;
            createMainList(listView1, default_subredit, default_subreddit_posts);

            bottom_left_subreddit = reddit.GetSubreddit("/r/programming");
            createSideList(listView2, bottom_left_subreddit, bottom_left_posts, label1);

            bottom_right_subreddit = reddit.GetSubreddit("/r/linux");
            createSideList(listView3, bottom_right_subreddit, bottom_right_posts, label2);

            updateStatusBarLabels();
        }
Esempio n. 6
0
        public async Task<List<ImageLink>> GetImgurLinksFromSubReddit(Reddit reddit, string sub, SearchRange searchRange, Sorting sortOrder, string outputPath, CancellationToken token)
        {
            token.ThrowIfCancellationRequested();
            Subreddit subreddit = null;
            var links = new List<ImageLink>();

            if (!string.IsNullOrWhiteSpace(sub))
            {
                try
                {
                    subreddit = reddit.GetSubreddit(sub);
                    OutputLine($"{subreddit.Name}: Begining Search...");
                }
                catch (Exception e)
                {
                    OutputLine($"Error connecting to reddit: {e.Message}");
                    return links;
                }
            }

            if (_filter == null) _filter = string.Empty;

            var searchTo = DateTime.Now;
            var searchFrom = DateTime.Now;
            switch (searchRange)
            {
                case SearchRange.Today:
                    searchFrom = searchFrom.AddDays(-1);
                    break;
                case SearchRange.Week:
                    searchFrom = searchFrom.AddDays(-7);
                    break;
                case SearchRange.Fortnight:
                    searchFrom = searchFrom.AddDays(-14);
                    break;
                case SearchRange.Month:
                    searchFrom = searchFrom.AddMonths(-1);
                    break;
                case SearchRange.ThreeMonths:
                    searchFrom = searchFrom.AddMonths(-3);
                    break;
                case SearchRange.SixMonths:
                    searchFrom = searchFrom.AddMonths(-6);
                    break;
            }

            var search = !string.IsNullOrWhiteSpace(sub)
                ? searchRange == SearchRange.AllTime ? subreddit?.Search(_filter) : subreddit?.Search(searchFrom, searchTo, sortOrder)
                : reddit.Search<Post>(_filter);

            token.ThrowIfCancellationRequested();
            var listings = search?.GetEnumerator();

            links = CombineLinkLists(await GetImagesFromListing(reddit, listings, outputPath, token), links);

            return links;
        }
Esempio n. 7
0
        public RAOATools(string modMailSub)
        {
            try
            {

            _reddit = new Reddit();
            Sub = _reddit.GetSubreddit(modMailSub);
            }
            catch (Exception)
            {
            }
        }
Esempio n. 8
0
        static void Main()
        {
            bool dbug = Debugger.IsAttached;

            Console.Title = "BookHorseBot " + Constants.Version;
            List <string> ignoredUsers = C.Ignored.User;

            //Does all the dirty work of handling oAuth and tokens. Gives botclient authentication.
            AuthorizeFimFictionBot();
            Reddit reddit     = AuthorizeRedditBot();
            string redditName = reddit.User.FullName;

            Console.WriteLine(dbug ? "Debug detected. Running on test subreddit!" : "Running on Main subreddit!");
            Subreddit             subreddit     = reddit.GetSubreddit(dbug ? "bronyvillers" : "mylittlepony");
            IEnumerable <Comment> commentStream =
                subreddit.CommentStream.Where(c => !ignoredUsers.Contains(c.AuthorName.ToLower()) &&
                                              c.CreatedUTC >= DateTime.UtcNow.AddMinutes(-120) &&
                                              c.AuthorName.ToLower() != redditName.ToLower()
                                              );


            foreach (Comment comment in commentStream)
            {
                //Look for { and }, if none are found, skip!
                MatchCollection matches = Regex.Matches(comment.Body, @"(?<=\{)[^}]*(?=\})", RegexOptions.None);
                if (matches.Count == 0)
                {
                    continue;
                }
                //Check to see if we already replied to this comment.
                Comment qualifiedComment = reddit.GetComment(new Uri(comment.Shortlink));
                if (qualifiedComment.Comments.All(x => x.AuthorName != redditName))
                {
                    string         username = qualifiedComment.AuthorName.ToLower();
                    List <Command> commands = ExtractCommands(matches, username);
                    if (commands.Count > 0)
                    {
                        GetPostText(commands);
                        string postReplyBody = GeneratePostBody(commands);
                        try
                        {
                            comment.Reply(postReplyBody);
                            Console.WriteLine($"Reply posted to {comment.AuthorName}!");
                        }
                        catch (Exception e)
                        {
                            System.Console.WriteLine(e);
                        }
                    }
                }
            }
        }
        private void SubmitPosts(IList <Post> posts)
        {
            var subreddits = _subredditNames.Select(sr => _reddit.GetSubreddit(sr)).ToList();

            foreach (var post in posts)
            {
                InitRedditIntegration(post);

                foreach (var subreddit in subreddits)
                {
                    SubmitPostToSubreddit(post, subreddit);
                }
            }
        }
        public void Launch()
        {
            List<String> title = new List<string>();
            List<String> urls = new List<string>();
            string body = "";

            var reddit = new Reddit();
            var user = reddit.LogIn("bot_wallpaper", "qwerty");
            var wallpaperSubreddit = reddit.GetSubreddit("/r/" + _wallpaperType);
            var homeSubreddit = reddit.GetSubreddit("/r/botwallpaper");
            foreach (var post in wallpaperSubreddit.GetTop(FromTime.Week).Take(25))
            {
                title.Add(post.Title);
                urls.Add(post.Url.ToString());
            }
            for (int i = 0; i < title.Count; i++)
            {
                body += "[" + title[i] + "](" + urls[i] + ") \n\n";
            }
            DateTime thisDay = DateTime.Today;
            homeSubreddit.SubmitTextPost("[" + thisDay.ToString("D") + "] Top /r/" + _wallpaperType, "#Here is the top wallpapers of this week in **/r/" + _wallpaperType + "** \n\n" + body + "\n\n I am a bot!", "", "");
            Console.WriteLine("SubredditProcessor: Post submitted to " + homeSubreddit.Name + "with posts of " + wallpaperSubreddit.Name);
        }
        static void Main(string[] args)
        {
            Reddit reddit = null;
            var authenticated = false;

            try
            {
#if DEBUG
                reddit = new Reddit("", "", true);
#else
                reddit = new Reddit(args[0], args[1], true);
#endif
                authenticated = reddit.User != null;
            }
            catch (AuthenticationException)
            {
                Console.WriteLine("Incorrect login.");
                authenticated = false;
            }

            if (authenticated)
            {
                Subreddit dailyProgrammer = reddit.GetSubreddit("dailyprogrammer");
                List<PostMetaData> PostDataList = new List<PostMetaData>();

                foreach(Post post in dailyProgrammer.Posts)
                    PostDataList.Add(new PostMetaData(post.Title));

                using (StreamWriter writer = new StreamWriter("OutputMarkup.txt"))
                {
                    writer.WriteLine("<table>");
                    for (int i = PostDataList.Max(a => a.ChallengeNumber); i >= -1; i--)
                    {
                        writer.WriteLine("    <tr>");
                        writer.WriteLine("        <td>Challenge #{0}</td>", i.ToString());
                        foreach (PostMetaData data in PostDataList.Where(a => a.ChallengeNumber == i).OrderBy(b => b.Difficulty))
                        {
                            writer.WriteLine(string.Format("        <td>{0}</td>", data.Title));
                        }
                        writer.WriteLine("    </tr>");
                    }
                    writer.WriteLine("</table>");
                }
            }
            Console.WriteLine("Processing complete.");
            Console.ReadKey();
        }
Esempio n. 12
0
        public ActionResult Index()
        {
            var reddit = new Reddit();
            //var user = reddit.LogIn("EddieValiantsRabbit", "camaro");
            var all = reddit.GetSubreddit("/r/news");

            var listOfPosts = all.Hot.Take(25);

            ViewBag.Posts = new List<RedditSharp.Things.Post>();
            ViewBag.Posts = listOfPosts;

            ViewBag.Greeting = "Good " + SpareParts.DeterminePartOfDay();
            WebRequest weatherRequest = WebRequest.Create(@"http://api.openweathermap.org/data/2.5/weather?zip=94040,us&appid=8b3de9d1132f5c7199d2650d858cef68");
            weatherRequest.ContentType = "application/json; charset=utf-8";

            WeatherResponse jsonResponse = new WeatherResponse();

            using (HttpWebResponse weatherResponse = weatherRequest.GetResponse() as HttpWebResponse)
            {
                if (weatherResponse.StatusCode != HttpStatusCode.OK)
                    throw new Exception(String.Format(
                    "Server error (HTTP {0}: {1}).",
                    weatherResponse.StatusCode,
                    weatherResponse.StatusDescription));
                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(WeatherResponse));
                object objResponse = jsonSerializer.ReadObject(weatherResponse.GetResponseStream());
                jsonResponse
                = objResponse as WeatherResponse;

            }

            ViewBag.CurrentMonth = SpareParts.GetCurrentMonth(DateTime.Now.Month);
            ViewBag.CurrentDayOfMonth = DateTime.Now.Day;
            ViewBag.CurrentDayOfWeek = DateTime.Now.DayOfWeek;
            ViewBag.CurrentHour = DateTime.Now.Hour;
            ViewBag.CurrentMinute = DateTime.Now.Minute;
            ViewBag.CurrentSecond = DateTime.Now.Second;
            ViewBag.CurrentTemp = (jsonResponse.main.Temp - 273.15) * 1.8 + 32;
            ViewBag.WeatherDescription = jsonResponse.weather[0].Description;

            return View();
        }
Esempio n. 13
0
        public static void Submit(string title, string url)
        {
            try
            {
                string youtubeTitle = HypeBotYoutube.YoutubeTitle(url);
                if (youtubeTitle != null)
                {
                    title = Regex.Replace(title, @"(https?://)?(www.)?(youtu.\S*)", '"' + youtubeTitle + '"');
                }

                var reddit = new Reddit();
                var user = reddit.LogIn(username, password, false);
                var sub = reddit.GetSubreddit(subreddit);
                sub.SubmitPost(title, url);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Esempio n. 14
0
        public string GetSubreddit(string input)
        {
            string result = "";

            try
            {
                Subreddit sub   = reddit.GetSubreddit(input);
                int       count = 0;
                foreach (Post post in sub.GetTop(FromTime.Day).Take(5))
                {
                    count++;
                    result += count + ". " + post.Title + '(' + post.Shortlink + ')' + '\n';
                }
            } catch (Exception e)
            {
                Console.WriteLine(e.Message);
                result = "";
            }

            return(result);
        }
Esempio n. 15
0
        static void Main(string[] args)
        {
            /// <summary>
            /// Simple reddit bot that replies to comments.
            /// </summary>
            var reddit = new Reddit();
            var user = reddit.LogIn("BotKazy", "thisisapassword");
            var subreddit = reddit.GetSubreddit("/r/test");

            foreach (var post in subreddit.New.Take(25))
            {
                Console.WriteLine("THREAD : {0}", post.Title);
                if (post.Title == "Test")
                {
                    try
                    {
                        foreach (var comment in post.Comments)
                        {
                            if (comment.Body.Contains("Kazy") || comment.Body.Contains("kazy"))
                                if (comment.Author != "BotKazy")

                                {
                                    using (WebClient client = new WebClient())
                                    {
                                        comment.Reply("[Kazy is a bot](https://play.esea.net/users/727731)");

                                        Thread.Sleep(5000);
                                        //penis
                                    }
                                }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Exception: {0}", e.Message);
                    }
                }
            }
        }
Esempio n. 16
0
 static void Main(string[] args)
 {
     var reddit = new Reddit();
     while (reddit.User == null)
     {
         Console.Write("Username: "******"Password: "******"Logging in...");
             reddit.LogIn(username, password);
         }
         catch (AuthenticationException)
         {
             Console.WriteLine("Incorrect login.");
         }
     }
     Console.Write("Create post? (y/n) [n]: ");
     var choice = Console.ReadLine();
     if (!string.IsNullOrEmpty(choice) && choice.ToLower()[0] == 'y')
     {
         Console.Write("Type a subreddit name: ");
         var subname = Console.ReadLine();
         var sub = reddit.GetSubreddit(subname);
         Console.WriteLine("Making test post");
         var post = sub.SubmitTextPost("RedditSharp test", "This is a test post sent from RedditSharp");
         Console.WriteLine("Submitted: {0}", post.Url);
     }
     else
     {
         var subreddit = Subreddit.GetRSlashAll(reddit);
         foreach (var post in subreddit.Posts.Take(10))
             Console.WriteLine("\"{0}\" by {1}", post.Title, post.Author);
     }
     Console.ReadKey(true);
 }
Esempio n. 17
0
        static void Main(string[] args)
        {
            var auth = new AuthProvider(_clientId, _clientSecret, _redirectUrl);

            var _authToken = auth.GetOAuthToken("curiosity_auto", "reddit18");
            
            var reddit = new Reddit(_authToken);
            
            var limit = reddit.RateLimit;
            
            var subreddit = reddit.GetSubreddit("/r/gaming");

            foreach (var post in subreddit.New.Take(250))
            {
                if (post.Title.ToLower().Contains("halo"))
                {
                    if (post.Liked.HasValue && post.Liked.Value)
                        continue;
                    post.Upvote();
                    post.Comment("hell yes");
                }
            }
        }
Esempio n. 18
0
        static void Init()
        {
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.WriteLine("ScreenshotBot is bootstrapping...");

            try
            {
                reddit = new Reddit();
                Reddit.UserAgent = "ScreenshotBot";
                ini = new IniFile("sst.ini");
                reddit.LogIn(ini.IniReadValue("ACCOUNT", "Username"), ini.IniReadValue("ACCOUNT", "Password"));
                var inisub = ini.IniReadValue("BOT", "Subreddit");
                if (inisub == "all") sub = Subreddit.GetRSlashAll(reddit);
                else sub = reddit.GetSubreddit(inisub);
                popular = new BlackList("popular", ini);
                www = ini.IniReadValue("BOT", "www");
                template = ini.IniReadValue("BOT", "Template");

                Work1 = new List<Post>();
                Work2 = new List<Post>();
                ProcessedURLs = new List<string>();

                ThreadPool.QueueUserWorkItem(new WaitCallback(ScreenshotWorker), 1);
                ThreadPool.QueueUserWorkItem(new WaitCallback(ScreenshotWorker), 2);

            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Initialization failure! Error details: \r\n" + ex.ToString());
                Console.ReadLine();
                return;
            }

            Console.WriteLine("ScreenshotBot was successfully initialized!\n----------------------------------------------------------\r\n\r\n");
        }
Esempio n. 19
0
 static void Main(string[] args)
 {
     var reddit = new Reddit();
     while (reddit.User == null)
     {
         Console.Write("Username: "******"Password: "******"Logging in...");
             reddit.LogIn(username, password);
         }
         catch (AuthenticationException e)
         {
             Console.WriteLine("Incorrect login.");
         }
     }
     var subreddit = reddit.GetSubreddit("/r/sircmpwn");
     var style = subreddit.GetStylesheet();
     var image = File.ReadAllBytes("test_image.jpg");
     style.UploadImage("test-image", SubredditStyle.ImageType.JPEG, image);
 }
Esempio n. 20
0
        static void Main(string[] args)
        {
            try
            {
                SkimurContext.Initialize(
                    new Program(),
                    new Skimur.App.Registrar());

                _mirrorSettings = SkimurContext.ServiceProvider.GetRequiredService<ISettingsProvider<MirrorSettings>>().Settings;
                _subService = SkimurContext.ServiceProvider.GetRequiredService<ISubService>();
                _postService = SkimurContext.ServiceProvider.GetRequiredService<IPostService>();
                _membershipService = SkimurContext.ServiceProvider.GetRequiredService<IMembershipService>();
                _commandBus = SkimurContext.ServiceProvider.GetRequiredService<ICommandBus>();

                if (_mirrorSettings.SubsToMirror == null || _mirrorSettings.SubsToMirror.Count == 0)
                    return;

                var botUser = _membershipService.GetUserByUserName(_mirrorSettings.BotName);
                if (botUser == null) return;

                var reddit = new Reddit();

                foreach (var subToMirror in _mirrorSettings.SubsToMirror)
                {
                    Console.WriteLine("Attempting to mirror " + subToMirror + ".");

                    var sub = _subService.GetSubByName(subToMirror);
                    if (sub == null)
                    {
                        Console.WriteLine("Sub doesn't exist.");
                        continue;
                    }

                    var redditSub = reddit.GetSubreddit("/r/" + subToMirror);
                    if (redditSub == null)
                    {
                        Console.WriteLine("Couldn't find reddit sub.");
                        continue;
                    }

                    foreach (var redditPost in redditSub.GetTop(_mirrorSettings.FromTime).Take(_mirrorSettings.PostsPerSub))
                    {
                        Console.WriteLine("Syncing " + redditPost.Title);

                        var existing = _postService.QueryPosts(redditPost.Title, sub.Id).Select(x => _postService.GetPostById(x)).ToList();
                        var exists = false;
                        if (existing.Count > 0)
                        {
                            foreach (var item in existing)
                            {
                                if (item.Title == redditPost.Title && item.Mirrored == "reddit")
                                    exists = true;
                            }
                        }
                        if (exists)
                        {
                            Console.WriteLine("Already exists.");
                            continue;
                        }

                        var createPostResponse = _commandBus.Send<CreatePost, CreatePostResponse>(
                            new CreatePost
                            {
                                CreatedByUserId = botUser.Id,
                                Title = redditPost.Title,
                                Url = redditPost.Url.ToString(),
                                Content = redditPost.SelfText,
                                PostType = redditPost.IsSelfPost ? PostType.Text : PostType.Link,
                                SubName = subToMirror,
                                NotifyReplies = false,
                                Mirror = "reddit",
                                OverrideDateCreated = redditPost.CreatedUTC
                            });

                        if (!string.IsNullOrEmpty(createPostResponse.Error))
                        {
                            Console.WriteLine("Couldn't create post. " + createPostResponse.Error);
                            continue;
                        }

                        if (!createPostResponse.PostId.HasValue)
                        {
                            Console.WriteLine("No post id");
                            continue;
                        }

                        var createCommentResponse = _commandBus.Send<CreateComment, CreateCommentResponse>(
                           new CreateComment
                           {
                               PostId = createPostResponse.PostId.Value,
                               DateCreated = Common.CurrentTime(),
                               AuthorUserName = botUser.UserName,
                               Body = string.Format("Mirrored from [here]({0}).", redditPost.Shortlink),
                               SendReplies = false
                           });

                        if (!string.IsNullOrEmpty(createCommentResponse.Error))
                        {
                            Console.WriteLine("Couldn't create comment. " + createCommentResponse.Error);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Esempio n. 21
0
        static void Main(string[] args)
        {
            try
            {
                var username = Convert.ToString(ConfigurationManager.AppSettings["Username"]);
                var password = Convert.ToString(ConfigurationManager.AppSettings["Password"]);
                var updateInterval = Convert.ToInt32(ConfigurationManager.AppSettings["UpdateInterval"]);
                _reddit = new Reddit(username, password);
                //_subreddit = _reddit.GetSubreddit("/r/CFL");
                _subreddit = _reddit.GetSubreddit("/r/HomerSPCTest");
                lastUpdateDt = DateTime.MinValue;

                var appPath = Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
                var file = new StreamReader(appPath + @"\Blacklist.txt");
                while (!file.EndOfStream)
                {
                    BLACKLIST.Add(file.ReadLine());
                }
                file.Close();

                while (!Console.KeyAvailable)
                {
                    Loop();
                    Thread.Sleep(updateInterval * 1000);
                }
            }
            catch (AuthenticationException)
            {
                Console.WriteLine("Incorrect login.");
            }
        }
Esempio n. 22
0
        private void Threaddit()
        {
            download = "";
            try
            {
                //Log in to reddit
                Reddit reddit = new Reddit();
                //Pick a random sub, then remove it from the list so we don't keep looking there if nothing is found
                Random rng = new Random();
                int i = rng.Next(0, subs.Count - 1);
                workingSub = subs[i];
                Subreddit subreddit = reddit.GetSubreddit("/r/" + workingSub);
                if (subs.Count > 0)
                    subs.RemoveAt(i);

                //Take the sub's top 10 hot posts
                foreach (var post in subreddit.Hot.Take(10))
                {
                    if (LegitPost(post.Url.ToString()))
                    {
                        Properties.Settings.Default.CollectedUrls.Add(post.Url.ToString());
                        Properties.Settings.Default.Save();
                        title = post.Title;
                        download = urlModder(post.Url.ToString());
                        break;
                    }
                }
            }
            catch (Exception error)
            {
                UpdateConsole(String.Format("You found an error, congratulations! \n This happened when the Reddit API was being interacted with. Read on for more info... \n\n\n {0}", error));
            }
            if (download != "")
            {
                //Save the image to computer
                string saveName = Properties.Settings.Default.SaveDirectory;
                saveName = saveName + "\\" + workingSub + "\\";
                if (!Directory.Exists(saveName))
                    Directory.CreateDirectory(saveName);
                int fCount = Directory.GetFiles(saveName, "*", SearchOption.TopDirectoryOnly).Length;
                string suffix = "." + download.Substring(download.Length - 3, 3);
                saveName = saveName + "Image" + fCount.ToString() + suffix;
                WebClient web = new WebClient();
                using (web)
                {
                    try
                    {
                        web.DownloadFile(download, saveName);
                    }
                    catch (Exception except)
                    {
                        UpdateConsole("Error! Couldn't download file! More info... \n" + except);
                    }
                }

                //Now that we have the image saved, we can check the dimensions and make sure it fits.
                try
                {
                    int height = 0;
                    int width = 0;
                    using (Image dimensionschecker = Image.FromFile(saveName))
                    {
                        height = dimensionschecker.Height;
                        width = dimensionschecker.Width;
                    }

                    if ((height >= Properties.Settings.Default.MinHeight) &&
                        (width >= Properties.Settings.Default.MinWidth) &&
                        (height <= Properties.Settings.Default.MaxHeight) &&
                        (width <= Properties.Settings.Default.MaxWidth))
                    {
                        UpdateConsole(String.Format("Found a cool image from {0} - {1}", workingSub, title));
                        bool tooBig = ((height > Screen.PrimaryScreen.Bounds.Height * 1.1) ||
                            (width > Screen.PrimaryScreen.Bounds.Width * 1.1));
                        MakeBackground(saveName, tooBig);
                    }
                    else
                    {
                        //Image is wrong size. Delete it, then try again.
                        try { File.Delete(saveName); }
                        catch (IOException)
                        {
                            UpdateConsole("Tried to delete a file, but couldn't. This shouldn't be a problem, unless you see this message a lot.");
                        }
                        //UpdateConsole("Found an image, but it was not within your dimensions. If you're seeing this message a lot, you might try lowering your minimum height/width dimensions.");
                        firstTime = false;
                        RunReddit();
                    }

                }
                catch (Exception except)
                {
                    UpdateConsole("We couldn't make an image out of whatever we downloaded; must not have grabbed a real url. Try again..." + except);
                    try { File.Delete(saveName); }
                    catch (IOException)
                    {
                        UpdateConsole("Tried to delete a file (" + saveName + "), but couldn't. This shouldn't be a problem, unless you see this message a lot.");
                    }
                    firstTime = false;
                    RunReddit();
                }

            }
            else if (subs.Count >= 1)
            {
                UpdateConsole("Couldn't find any valid images in " + workingSub + ". Trying again.");
                firstTime = false;
                RecursiveReddit();
            }
            else
            {
                UpdateConsole("We've tried every sub on the list, and couldn't find anything that meets our requirements.");
                firstTime = true;
            }
        }
        public void tmr1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            //Gif (1hr)
            client.SendMessageToChannel("Hourly gif:", dc);
            var reddit = new Reddit();
            string sub;
            sub = "/r/gifs";
            var subreddit = reddit.GetSubreddit(sub);
            monoFlat_TextBox2.Text += subreddit;
            foreach (var post in subreddit.New.Take(1))
            {
                string st;
                st = post.Url.ToString();

                monoFlat_TextBox2.Text += st;

                client.SendMessageToChannel(st, dc);
            }
            tmr1.Interval = GetInterval1();
            tmr1.Start();
        }
        //end timer intervals setting and start on timer elapsed events
        public void tmr_Elapsed(object sender, System.Timers.ElapsedEventArgs e) 
        {
            //Shower thought (30 mins)
            client.SendMessageToChannel("Half hourly Shower thought:", dc);
            //reddit
            var reddit = new Reddit();
            var subreddit = reddit.GetSubreddit("/r/showerthoughts");
            foreach (var post in subreddit.New.Take(1))
            {
                string st;
                st = post.Title;
                monoFlat_TextBox2.Text += st;

                client.SendMessageToChannel(st, dc);
            }
            tmr.Interval = GetInterval();
            tmr.Start();
        }
Esempio n. 25
0
        public void PostArticles()
        {
            StreamReader txtReader = new StreamReader("feeds.txt");
            feedSources = txtReader.ReadToEnd().Split(',').ToList();
            txtReader.Close();

            txtReader = new StreamReader("keywords.txt");
            keywords = txtReader.ReadToEnd().ToLower().Split(',').ToList();
            txtReader.Close();

            Reddit reddit = new Reddit(Credentials.USERNAME, Credentials.PASSWORD);
            var subreddit = reddit.GetSubreddit("gamersource");
            List<string> existingTitles = new List<string>();
            Dictionary<string, int> dictionary = new Dictionary<string, int>();
            List<Uri> uriFeedList = new List<Uri>();

            foreach (var url in feedSources)
                uriFeedList.Add(new Uri(url));

            foreach (var uri in uriFeedList)
            {
                dictionary[uri.Host.Replace("feeds.", "")] = 0;
            }

            foreach (var post in subreddit.New.Take(25))
            {
                existingTitles.Add(post.Title);
                try
                {
                    dictionary[post.Url.Host]++;
                }
                catch (Exception ex)
                {
                    _logger.Warn("No key found for {0}", post.Url.Host);
                }
            }

            var biggestNumberOfPostsFrom = dictionary.Aggregate((l, r) => l.Value > r.Value ? l : r).Key;

            foreach (var source in feedSources)
            {
                if (source.Contains(biggestNumberOfPostsFrom))
                {
                    _logger.Info("Skipping {0} because too many posts from there", biggestNumberOfPostsFrom);
                    continue;
                }

                var reader = XmlReader.Create(source);
                var feed = SyndicationFeed.Load(reader);

                reader.Close();

                foreach (var article in feed.Items)
                {
                    var keywordsMatchList = keywords.Intersect(article.Title.Text.ToLower().Split(' ')).ToList();

                    bool shouldExit = false;
                    foreach (var title in existingTitles)
                    {
                        if (title.Split(' ').Intersect(article.Title.Text.ToLower().Split(' ')).ToList().Count > 5)
                        {
                            shouldExit = true;
                        }
                    }

                    if (shouldExit)
                        break;

                    if (!existingTitles.Contains(article.Title.Text) && keywordsMatchList.Count > 0)
                    {
                        try
                        {
                            subreddit.SubmitPost(article.Title.Text, article.Links[0].Uri.ToString());
                            _logger.Info("Posted article {0}", article.Title.Text);
                        }
                        catch (Exception ex)
                        {
                            _logger.Warn("Could not post article {0}", article.Title.Text);
                        }
                        break;
                    }
                }
            }

            _logger.Info("Finished");
        }
Esempio n. 26
0
        static void Main(string[] args)
        {
            try
            {
                try
                {
                    // Create sitter File if it doesn't exist
                    if (!System.IO.File.Exists(ConfigurationManager.AppSettings["sitterPath"]))
                    {
                        System.IO.File.Create(ConfigurationManager.AppSettings["sitterPath"]).Close();
                        log("Created missing sitter File. It is still empty");
                    }
                    if (!System.IO.File.Exists(ConfigurationManager.AppSettings["sitterPathNsfw"]))
                    {
                        System.IO.File.Create(ConfigurationManager.AppSettings["sitterPathNsfw"]).Close();
                        log("Created missing NSFW sitter File. It is still empty");
                    }

                    // Initial Vars
                    string[] sitter = System.IO.File.ReadAllLines(ConfigurationManager.AppSettings["sitterPath"]);
                    string[] sitterNsfw = System.IO.File.ReadAllLines(ConfigurationManager.AppSettings["sitterPathNsfw"]);

                    // Log programm start
                    log("Started");

                    // Bot Login Data
                    string BotUser = ConfigurationManager.AppSettings["botUser"];
                    string BotPass = ConfigurationManager.AppSettings["botPass"];

                    // LogIn to reddit
                    var reddit = new Reddit();
                    var user = reddit.LogIn(BotUser, BotPass);
                    log("Login as \"" + BotUser + "\"");

                    // check for new message
                    var privateMessage = reddit.User.PrivateMessages;

                    // Check each Message
                    foreach (var message in privateMessage)
                    {
                        if (message.Body.Contains("gadzooks!") && message.Unread)
                        {
                            // Get Subreddit and accept Mod-Invite
                            var sub = reddit.GetSubreddit(message.Subreddit);
                            sub.AcceptModeratorInvite();
                            log("Accepted Moderation Invite for \"" + sub);

                            // Check if sub is NSFW
                            if ((bool)sub.NSFW)
                            {
                                // Sub is NSFW
                                log("\"" + sub + "\" is NSFW");
                                // Adding NSFW Sitter
                                log("+++ Starting to add sitters to \"" + sub + "\" (NSFW) +++");
                                foreach (string addAsMod in sitterNsfw)
                                {
                                    sub.AddModerator(addAsMod);
                                    log("Added sitter \"" + addAsMod + "\" as a sitter to \"" + sub + "\" (NSFW)");
                                }
                                log("+++ Finished adding sitters (NSFW) +++");
                            }
                            else
                            {
                                // Sub is not NSFW
                                // Adding Sitter
                                log("+++ Starting to add sitters to \"" + sub + "\" +++");
                                foreach (string addAsMod in sitter)
                                {
                                    sub.AddModerator(addAsMod);
                                    log("Added sitter \"" + addAsMod + "\" as a sitter to \"" + sub + "\"");
                                }
                                log("+++ Finished adding sitters +++");
                            }
                        }
                        message.SetAsRead();
                    }
                }
                catch (System.Security.Authentication.AuthenticationException exc)
                {
                    log("Autentication Failed \n" + exc);
                    Console.WriteLine("");
                    Console.WriteLine("Press any key to exit ....");
                    Console.ReadKey(true);
                }
                catch (Exception exc)
                {
                    log("Unknown Exception: \n" + exc);
                    throw;
                }
            #region final catch
            }
            catch (Exception)
            {
                try
                {
                    // Things to do in final catch
                }
                catch (Exception)
                {
                    // final catch failed
                    // This should stay
                }
            }
            finally
            {
                try
                {
                    log("END");
                    log("\n");  // Needs to be single to don't add Timestamp
                }
                catch (Exception)
                {
                    // final finally failed
                    // This should stay
                }
            }
            #endregion
        }
Esempio n. 27
0
        static bool RedditSetup()
        {
            string Username = string.Empty;
            string Password = string.Empty;

            string RedditLoginQuery = "SELECT * FROM User LIMIT 1";
            using (SQLiteCommand RedditLoginCommand = new SQLiteCommand(RedditLoginQuery, CurrentDB))
            {
                using (SQLiteDataReader RedditLogin = RedditLoginCommand.ExecuteReader())
                {
                    if (RedditLogin.Read())
                    {
                        Username = RedditLogin[0].ToString();
                        Password = RedditLogin[1].ToString();
                    }
                }
            }

            try
            {
                Reddit = new Reddit(Username, Password, true);
                Subreddit = Reddit.GetSubreddit("/r/" + SubredditName);

                return true;
            }
            catch { return false; }
        }
Esempio n. 28
0
 public void Execute(string[] args, Reddit reddit)
 {
     if (args.Length != 3)
     {
         Console.WriteLine("Invalid usage. See 'srutil help backup' for more information.");
         return;
     }
     var subreddit = reddit.GetSubreddit(args[1]);
     // Verify archive
     var settings = new SubredditSettings(reddit, subreddit);
     var styles = new SubredditStyle(reddit, subreddit);
     var serializer = new JsonSerializer();
     using (var file = new ZipFile(File.OpenRead(args[2])))
     {
         if (file.GetEntry("stylesheet.css") == null ||
             file.GetEntry("settings.json") == null ||
             file.GetEntry("flair.json") == null)
         {
             Console.WriteLine("{0} is not a valid subreddit backup.", args[2]);
             return;
         }
         Console.WriteLine("Resetting {0} to default settings...", subreddit.DisplayName);
         var reset = new Reset();
         reset.Execute(new[] { "reset", subreddit.DisplayName, "all" }, reddit);
         foreach (ZipEntry entry in file)
         {
             if (!entry.IsFile)
                 continue;
             if (entry.Name == "stylesheet.css")
             {
                 var stream = new StreamReader(file.GetInputStream(entry));
                 styles.CSS = stream.ReadToEnd();
                 // We udpate the CSS last to avoid errors with images
             }
             else if (entry.Name == "settings.json")
             {
                 Console.WriteLine("Restoring settings...");
                 var stream = new StreamReader(file.GetInputStream(entry));
                 serializer.Populate(new JsonTextReader(stream), settings);
                 settings.UpdateSettings();
             }
             else if (entry.Name == "flair.json") // TODO: Link flair templates, selected flair for users
             {
                 var stream = new StreamReader(file.GetInputStream(entry));
                 var flair = serializer.Deserialize<UserFlairTemplate[]>(new JsonTextReader(stream));
                 if (flair.Any())
                 {
                     Console.WriteLine("Restoring user flair templates...");
                     int progress = 1;
                     int left = Console.CursorLeft; int top = Console.CursorTop;
                     foreach (var item in flair)
                     {
                         subreddit.AddFlairTemplate(item.CssClass, FlairType.User, item.Text, true);
                         Console.CursorLeft = left; Console.CursorTop = top;
                         Console.WriteLine("{0}/{1}", progress++, flair.Length);
                     }
                 }
             }
             else if (entry.Name == "header.png" || entry.Name == "header.jpg")
             {
                 var image = Path.GetFileName(entry.Name);
                 Console.WriteLine("Restoring header image...");
                 var stream = file.GetInputStream(entry);
                 var data = new byte[entry.Size];
                 stream.Read(data, 0, (int)entry.Size);
                 subreddit.UploadHeaderImage(entry.Name,
                     Path.GetExtension(entry.Name) == "png" ? ImageType.PNG : ImageType.JPEG, data);
             }
             else if (entry.Name.StartsWith("images/"))
             {
                 var image = Path.GetFileName(entry.Name);
                 Console.WriteLine("Restoring image: " + image);
                 var stream = file.GetInputStream(entry);
                 var data = new byte[entry.Size];
                 stream.Read(data, 0, (int)entry.Size);
                 styles.UploadImage(Path.GetFileNameWithoutExtension(image),
                     Path.GetExtension(image) == ".png" ? ImageType.PNG : ImageType.JPEG, data);
             }
         }
         Console.WriteLine("Restoring CSS...");
         styles.UpdateCss();
         Console.WriteLine("Finished restoring {0}", subreddit.DisplayName);
     }
 }
Esempio n. 29
0
 public void Execute(string[] args, Reddit reddit)
 {
     if (args.Length != 3)
     {
         Console.WriteLine("Invalid usage. See 'srutil help backup' for more information.");
         return;
     }
     var subreddit = reddit.GetSubreddit(args[1]);
     using (var file = new ZipOutputStream(File.Create(args[2])))
     {
         file.SetLevel(5);
         var writer = new StreamWriter(file);
         writer.AutoFlush = true;
         var settings = subreddit.GetSettings();
         var serializer = new JsonSerializer();
         // Save settings
         Console.WriteLine("Saving settings...");
         var entry = new ZipEntry("settings.json");
         entry.DateTime = DateTime.Now;
         file.PutNextEntry(entry);
         serializer.Serialize(writer, settings);
         file.CloseEntry();
         // Save flair
         Console.WriteLine("Saving flair templates...");
         var flair = subreddit.GetUserFlairTemplates();
         entry = new ZipEntry("flair.json");
         file.PutNextEntry(entry);
         serializer.Serialize(writer, flair);
         file.CloseEntry();
         // Save styles
         Console.WriteLine("Saving CSS...");
         var styles = subreddit.GetStylesheet();
         entry = new ZipEntry("stylesheet.css");
         file.PutNextEntry(entry);
         writer.Write(styles.CSS);
         file.CloseEntry();
         // Save images
         Console.WriteLine("Saving images...");
         var webClient = new WebClient();
         var left = Console.CursorLeft; var top = Console.CursorTop;
         int progress = 1;
         foreach (var image in styles.Images)
         {
             var data = webClient.DownloadData(image.Url);
             entry = new ZipEntry("images/" + image.Name + Path.GetExtension(image.Url));
             file.PutNextEntry(entry);
             file.Write(data, 0, data.Length); file.Flush();
             file.CloseEntry();
             Console.CursorLeft = left; Console.CursorTop = top;
             Console.WriteLine("{0}/{1}", progress++, styles.Images.Count);
         }
         // Save header
         if (subreddit.HeaderImage != null)
         {
             Console.WriteLine("Saving header image...");
             var data = webClient.DownloadData(subreddit.HeaderImage);
             entry = new ZipEntry("header" + Path.GetExtension(subreddit.HeaderImage));
             file.PutNextEntry(entry);
             file.Write(data, 0, data.Length);
             file.CloseEntry();
         }
         Console.WriteLine("Done. {0} backed up to {1}.", subreddit.DisplayName, args[2]);
     }
 }
Esempio n. 30
0
        static void Main(string[] args)
        {
            var password = string.Empty;
            var username = string.Empty;

            if (args != null && args.Count() == 2)
            {
                password = args[1];
                username = args[0];
            }
            else
            {
                password = CloudConfigurationManager.GetSetting("pass");
                username = CloudConfigurationManager.GetSetting("user");
            }

            if (string.IsNullOrWhiteSpace(password) || string.IsNullOrWhiteSpace(username))
            {
                Console.WriteLine("Invalid or missing username and password.");
                Environment.Exit(1);
            }

            var reddit = new Reddit();
            var user = reddit.LogIn(username, password);
            var subreddit = reddit.GetSubreddit(SubredditName);

            AppDomain.CurrentDomain.UnhandledException += (o, e) =>
            {
                reddit.ComposePrivateMessage("Exception", e.ExceptionObject.ToString(), SubredditName);
                Console.WriteLine(e.ExceptionObject);
                Environment.Exit(3);
            };

            subreddit.Subscribe();

            if (!user.ModeratorSubreddits.Any(s => s.ToString().Equals(SubredditName, StringComparison.OrdinalIgnoreCase)))
            {
                reddit.ComposePrivateMessage("Bot user not a moderator", "The user '" + username + "' is not a moderator for the " + SubredditName + " subreddit.", SubredditName);
                Console.WriteLine("The user '" + username + "' is not a moderator for the " + SubredditName + " subreddit.");
                Environment.Exit(2);
            }

            // Reply to any private messages that have been sent to the mod bot.
            foreach (var message in user.PrivateMessages.Where(m => m.Unread))
            {
                message.Reply("You have messaged the " + SubredditName + " moderator bot. These private messages are not actively monitored.");
                message.SetAsRead();
            }

            // Get or create the post for this month
            var today = DateTime.Now;
            var dailyPosts = GetOrCreateDailyPosts(reddit, subreddit, user, today.Year, today.Month).ToList();
            var todaysPosts = dailyPosts.Where(p => p.AuthorName == user.Name && p.Title == string.Format(DailyPostTitleFormat, today.Year, today.ToString("MMMM"), today.Day)).ToList();

            if (dailyPosts.Any())
            {
                var settings = subreddit.Settings;
                var sidebar = settings.Sidebar;

                if (!string.IsNullOrEmpty(sidebar) && sidebar.Contains(SidebarSectionMarkdown))
                {
                    var startIndex = sidebar.IndexOf(SidebarSectionMarkdown, StringComparison.Ordinal) + SidebarSectionMarkdown.Length;
                    var endIndex = sidebar.IndexOf("#**", startIndex, StringComparison.Ordinal); // Find the beginning of the next section

                    if (endIndex < 0)
                        endIndex = sidebar.Length - 1; // There's no next section, so just replace the rest of the content

                    var newSidebarContent = "* [" + today.DayOfWeek + "](" + todaysPosts.First().Shortlink + ")";
                    newSidebarContent += Environment.NewLine + "* [" + today.ToString("MMMM") + "](" + todaysPosts.First().Shortlink + ")";
                    newSidebarContent += Environment.NewLine + "* [" + today.Day + "](" + todaysPosts.First().Shortlink + ")";
                    newSidebarContent += Environment.NewLine + Environment.NewLine + ">" + Environment.NewLine;
                    newSidebarContent += Environment.NewLine + "* [There are " + todaysPosts.First().ListComments(2000).Count() + " events today. Check it out or add your own.](" + todaysPosts.First().Shortlink + ")";
                    newSidebarContent += Environment.NewLine + Environment.NewLine + "&nbsp;" + Environment.NewLine;

                    newSidebarContent += "######" + today.ToString("MMMM");
                    newSidebarContent += Environment.NewLine + "| Su | Mo | Tu | We | Th | Fr | Sa |" + Environment.NewLine + "|-|-|-|-|-|-|-|";

                    for (var i = 1; i <= DateTime.DaysInMonth(today.Year, today.Month); i++)
                    {
                        var date = new DateTime(today.Year, today.Month, i);

                        if (i == 1)
                            newSidebarContent += Environment.NewLine + string.Join("|", Enumerable.Range(0, (int)date.DayOfWeek + 1).Select(d => string.Empty));

                        var dailyPost = dailyPosts.Where(p => p.AuthorName == user.Name && p.Title == string.Format(DailyPostTitleFormat, today.Year, today.ToString("MMMM"), i)).ToList();

                        if (dailyPost.Any())
                            newSidebarContent += "| [" + i + "](" + dailyPost.First().Shortlink + ")";
                        else
                            newSidebarContent += "| " + i;

                        if (date.DayOfWeek == DayOfWeek.Saturday)
                            newSidebarContent += "|" + Environment.NewLine;
                    }

                    newSidebarContent += Environment.NewLine + Environment.NewLine + "&nbsp;" + Environment.NewLine;
                    newSidebarContent += Environment.NewLine + SidebarSectionAdditional;

                    settings.Sidebar = sidebar.Remove(startIndex, endIndex - startIndex).Insert(startIndex, Environment.NewLine + Environment.NewLine + newSidebarContent + Environment.NewLine + Environment.NewLine);
                    settings.UpdateSettings();
                }
                else
                {
                    reddit.ComposePrivateMessage("No sidebar section found", "There was no sidebar section found for updating.", SubredditName);
                }
            }
            else
            {
                reddit.ComposePrivateMessage("No daily post found", "There was no daily comment found for " + today.ToString("MMMM d, yyyy") + ".", SubredditName);
            }

            // Ensure next months post exists if we're more than 25 days into the current month
            if (today.Day > 25)
            {
                var nextMonth = today.AddMonths(1);
                var nextMonthPosts = GetOrCreateDailyPosts(reddit, subreddit, user, nextMonth.Year, nextMonth.Month).ToList();
            }

            // TODO: Find or add the API methods for automatically making certain Monthly posts sticky.
        }
Esempio n. 31
0
        void redditWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            var reddit = new Reddit();
            var rsubreddit = reddit.GetSubreddit(subreddit);
            var posts = rsubreddit.GetHot();
            foreach (var post in posts.Take(20))
            {
                if (post.LinkFlairText == "EVENT")
                {
                    events evt = new events();
                    evt.title = post.Title.ToString();
                    evt.author = post.Author.ToString();
                    evt.url = post.Shortlink;

                    rposts.Add(evt);
                }
            }
        }
Esempio n. 32
0
        public bool RedditSetup()
        {
            string Username = string.Empty;
            string Password = string.Empty;

            string RedditLoginQuery = "SELECT * FROM User LIMIT 1";
            using (SQLiteCommand RedditLoginCommand = new SQLiteCommand(RedditLoginQuery, CurrentDB))
            {
                CurrentDB.Open();
                using (SQLiteDataReader RedditLogin = RedditLoginCommand.ExecuteReader())
                {
                    if (RedditLogin.Read())
                    {
                        Username = RedditLogin[0].ToString();
                        Password = RedditLogin[1].ToString();
                    }
                }
                CurrentDB.Close();
            }

            try
            {
                Reddit = new Reddit(Username, Password, true);
                Subreddit = Reddit.GetSubreddit("/r/" + MainForm.GetSubreddit());

                return true;
            }
            catch
            {
                MainForm.NewError("Failed reddit login");
                return false;
            }
        }
Esempio n. 33
0
        /// <summary>
        /// This is the main entry point for your service replica.
        /// This method executes when this replica of your service becomes primary and has write status.
        /// </summary>
        /// <param name="cancellationToken">Canceled when Service Fabric needs to shut down this service replica.</param>
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            var eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, eventHubName);
            //var eventHubSender = EventHubSender.CreateFromConnectionString(connectionString);

            var redditCounter = await StateManager.GetOrAddAsync <IReliableDictionary <string, DateTime> >("reddit");

            var reddit    = new RedditSharp.Reddit(WebAgent.RateLimitMode.Pace);
            var user      = reddit.LogIn("leap17", "leap17");
            var subreddit = reddit.GetSubreddit("/r/pics/");

            var lastDateTime = DateTime.UtcNow;

            var comments = new List <CommentShape>();

            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();
                using (var tx = StateManager.CreateTransaction())
                {
                    var result = await redditCounter.TryGetValueAsync(tx, "Counter");

                    ServiceEventSource.Current.ServiceMessage(Context, "Current lastTime Value: {0}",
                                                              result.HasValue ? result.Value.ToString() : "Value does not exist.");

                    try
                    {
                        var subComments =
                            subreddit.Comments.Take(10).OrderBy(c => c.CreatedUTC).Where(c => c.CreatedUTC > lastDateTime);

                        foreach (var comment in subComments)
                        {
                            lastDateTime = comment.CreatedUTC;
                            await redditCounter.AddOrUpdateAsync(tx, "Counter", DateTime.UtcNow,
                                                                 (key, value) => lastDateTime);

                            var commentLinkId = comment.LinkId;

                            comments.Add(new CommentShape
                            {
                                Comment    = comment.Body,
                                UpWotes    = comment.Upvotes,
                                DownVotes  = comment.Downvotes,
                                Id         = comment.Id,
                                CreatedUTC = comment.CreatedUTC,
                                Author     = comment.Author
                            }
                                         );
                        }
                        if (comments.Any())
                        {
                            //Send Comment To EventHub
                            var message = JsonConvert.SerializeObject(comments);
                            //await eventHubSender.SendAsync(new EventData(Encoding.UTF8.GetBytes(message)));
                            await eventHubClient.SendAsync(new EventData(Encoding.UTF8.GetBytes(message)));
                        }
                        ServiceEventSource.Current.ServiceMessage(Context, "Got {0} new comments",
                                                                  comments.Count);
                        comments.Clear();
                    }
                    catch (Exception e)
                    {
                        ServiceEventSource.Current.ServiceMessage(Context, "Error happend: {0}",
                                                                  e.Message);
                        await Task.Delay(TimeSpan.FromSeconds(10), cancellationToken);
                    }

                    await tx.CommitAsync();
                }
                await Task.Delay(TimeSpan.FromSeconds(3), cancellationToken);
            }
        }
        static int Main(string[] args)
        {
            Reddit reddit = new Reddit();
            Login(reddit);

            Subreddit subreddit = GetFrontPage(reddit);
            IEnumerable<Post> topPosts = GetTopPosts(subreddit);
            Subreddit subredditToPostTo = reddit.GetSubreddit("readability");

            foreach (Post post in topPosts)
            {
                StringBuilder commentToPost = new StringBuilder(String.Format("Thread link: http://www.reddit.com/{0}\n\n***\n\n", post.Id));
                List<Comment> topComments = GetTopComments(post);

                foreach (Comment comment in topComments)
                {
                    commentToPost.Append(String.Format("\"{0}\"\n\n", comment.Body));

                    // Removes formatting so that linguistic analysis works properly
                    string commentText = comment.Body;
                    RemoveFormatting(ref commentText);

                    LinguisticAnalysis analysis = new LinguisticAnalysis(commentText);
                    commentToPost.Append(String.Format("`Words: {0}`\n\n`Characters: {1}`\n\n`Sentences: {2}`\n\n`Syllables: {3}`\n\n`% Hard Words: {4}`\n\n", analysis.GetWords(), analysis.GetCharacters(), analysis.GetSentences(), analysis.GetSyllables(), analysis.GetPercentageHardWords()));
                    ReadabilityAnalysis(analysis, commentToPost);
                    commentToPost.Append("***\n\n");
                }

                PostRedditThread(subredditToPostTo, post.Title, commentToPost);
            }

            Console.WriteLine(LOG_SUCCESSFUL_RUN);
            Console.Read();     // Remove later
            return 1;
        }