Example #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);
 }
 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;
     }
 }
Example #3
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()
 {
     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);
 }
        public void SubmitPostsToReddit(DateTimeOffset currentDateTimeOffset)
        {
            if (_subredditNames.Count == 0)
            {
                _log.Info("No subreddits to submit to configured.");
                return;
            }

            if (_credentials.IsValid == false)
            {
                _log.Info("Reddit credentials config options are invalid. Check your blog config.");
                return;
            }

            _log.Info($"Submitting #{RedditHelper.SendToRedditTag} posts to reddit.");

            var posts = RedditHelper.GetPostsForAutomaticRedditSubmission(_session, currentDateTimeOffset);

            if (posts.Any() == false)
            {
                _log.Info("No posts to submit to Reddit.");
                return;
            }

            _reddit.LogIn(_credentials.User, _credentials.Password);

            SubmitPosts(posts);
        }
Example #6
0
 static void Main(string[] args)
 {
     var reddit = new Reddit();
     var user = reddit.LogIn("botusername", "botpassword");
     var timer = new System.Threading.Timer(
     e => ModInvites(),
     null,
     TimeSpan.Zero,
     TimeSpan.FromMinutes(5));
 }
Example #7
0
        private bool ProcessLogin(string username, string password)
        {
            _reddit = new Reddit(WebAgent.RateLimitMode.Pace);

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) return false;

            try
            {
                OutputTextBlock.Text += $"\r\n{DateTime.Now} | Logging in as {username}.";
                _redditUser = _reddit.LogIn(username, password);
            }
            catch (Exception ex)
            {
                OutputTextBlock.Text += $"\r\n{DateTime.Now} | Login failed. Exception encountered: {ex.Message}. Is Reddit down?";
            }

            if (_redditUser != null) return true;
            return false;
        }
Example #8
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());
            }
        }
Example #9
0
        private static Reddit AuthorizeRedditBot()
        {
            BotWebAgent webAgent = new BotWebAgent(C.Reddit.Username,
                                                   C.Reddit.Password,
                                                   C.Reddit.ClientId,
                                                   C.Reddit.ClientSecret,
                                                   "https://google.com");

            Reddit reddit = new Reddit(webAgent, true);

            reddit.LogIn(C.Reddit.Username, C.Reddit.Password);
            string redditName = reddit.User.FullName;

            if (redditName.ToLower() == C.Reddit.Username.ToLower())
            {
                Console.WriteLine("Logged in!");
            }

            return(reddit);
        }
Example #10
0
        static void Main(string[] args)
        {
            Reddit reddit = new Reddit();

            Console.WriteLine("Logging in...");

            var user = reddit.LogIn("******", "**********");
            Console.WriteLine("Logged in!");
            int counter = 0;
            foreach (var comment in user.Comments)
            {
                if (counter >= 25)
                    break;
                comment.Del();
                Console.WriteLine("Comment deleted!");
                Thread.Sleep(1000);
                counter++;
            }
            Console.WriteLine("Rebooting...");
            Process process = Process.Start("ConsoleApplication4.exe");
        }
Example #11
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 modqueue = reddit.User.GetModerationQueue();
 }
Example #12
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);
                    }
                }
            }
        }
Example #13
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);
 }
        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)
 {
     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);
 }
Example #16
0
    private static Reddit Login(string password)
    {
      var reddit = new Reddit();

      while (string.IsNullOrWhiteSpace(password))
        password = GetPassword();

      do
      {
        try
        {
          Console.Clear();
          Console.Write("Logging in...");
          reddit.LogIn(Username, password);
        }
        catch (AuthenticationException)
        {
          Console.WriteLine("...failed!");
          password = GetPassword();
        }
      } while (reddit.User == null);

      return reddit;
    }
Example #17
0
        void Start()
        {
            _conn.Start().Wait();
        
            // Setup reddit connection
            var reddit = new Reddit();
            var user = reddit.LogIn("dxhack", "P@ssw0rd");

            // Call Reddit/r/All Hot and get top 25
            // filter all NSFW
            // Send to the GETCOMMENT Method
            reddit.RSlashAll.Hot.Take(25).ToList().ForEach(p =>
            {
                if (p.NSFW != true)
                {
                    p.Comments.ToList().ForEach(c =>
                    {
                        getComment(c, p.Title);
                    });

                    Console.WriteLine(p.Title);
                }
            });
        }
Example #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");
        }
 /*  -------------------------------------------------------------- */
 protected static void Login(Reddit reddit)
 {
     ProfileInfo profile = new ProfileInfo();
     try
     {
         Console.WriteLine(LOG_LOGIN);
         reddit.LogIn(profile.Username, profile.Password);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
         Environment.Exit(-1);
     }
 }
Example #20
0
        static void Main(string[] args)
        {
            // Register operations
            OperationTypes = new Dictionary<string, Type>();
            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                var types = assembly.GetTypes().Where(t => 
                    typeof(ISubredditOperation).IsAssignableFrom(t) &&
                    !t.IsAbstract && !t.IsInterface);
                foreach (var type in types)
                {
                    var instance = (ISubredditOperation)Activator.CreateInstance(type);
                    foreach (var keyword in instance.GetOperationNames())
                        OperationTypes[keyword] = type;
                }
            }
            // Start parsing arguments
            if (args.Length < 1)
            {
                Console.WriteLine("Error: No operation specified. Use \"srutil help\" for more information.");
                return;
            }
            string username = null, password = null;
            while (args[0].StartsWith("--"))
            {
                if (args[0] == "--username")
                {
                    username = args[1];
                    args = args.Skip(2).ToArray();
                }
                else if (args[0] == "--password")
                {
                    password = args[1];
                    args = args.Skip(2).ToArray();
                }
				else if (args[0] == "--domain")
				{
					Reddit.RootDomain = args[1];
					args = args.Skip(2).ToArray();
				}
            }
            if (!OperationTypes.ContainsKey(args[0]))
            {
                if (args[0] == "help")
                {
                    ShowHelp(args);
                    return;
                }
                Console.WriteLine("Error: Operation \"" + args[0] + "\" not found.");
                return;
            }
            // Log into reddit
            var reddit = new Reddit();
            while (reddit.User == null)
            {
                if (username == null)
                {
                    Console.Write("Username: "******"Password: "******"Logging in...");
                    reddit.LogIn(username, password);
                }
                catch (AuthenticationException e)
                {
                    Console.WriteLine("Incorrect login.");
                    username = password = null;
                }
            }
            // Execute command
            var operationType = OperationTypes[args[0]];
            var operation = (ISubredditOperation)Activator.CreateInstance(operationType);
            operation.Execute(args, reddit);
        }
Example #21
0
        public static int Main(string[] args)
        {
            Config = new Configuration();
            if (File.Exists("config.json"))
                Config = JsonConvert.DeserializeObject<Configuration>(File.ReadAllText("config.json"));
            else
            {
                File.WriteAllText("config.json", JsonConvert.SerializeObject(Config, Formatting.Indented));
                Console.WriteLine("Saved empty configuration in config.json, populate it and restart.");
                return 1;
            }
            Reddit = new Reddit();
            Reddit.LogIn(Config.Username, Config.Password);

            Timer = new Timer(o => DoUpdate(), null, 0, 30000);

            Console.WriteLine("Press 'q' to exit.");
            ConsoleKeyInfo cki;
            do cki = Console.ReadKey(true);
            while (cki.KeyChar != 'q');

            return 0;
        }
        public static void Main(string[] args)
        {
            string[] contentIds;
            
            var config = Newtonsoft.Json.JsonConvert.DeserializeObject<Config>(File.ReadAllText("config.json"));

            using (var cli = new BungieClient(config.BungieApiKey))
            {
                contentIds = cli.GetAllNews("Destiny", "en").Result
                    .Where(x => x.properties.Title.StartsWith("Bungie Weekly Update"))
                    .Select(x => x.contentId)
                    .ToArray();
            }

            var reddit = new Reddit();
            var me = reddit.LogIn(config.RedditUser, config.RedditPassword);

            using (var outStream = File.OpenWrite("results.csv"))
            {
                using (var writer = new StreamWriter(outStream))
                {
                    foreach (var aid in contentIds)
                    {
                        var misses = 0;
                        
                        foreach (var post in reddit.Search<Post>($"selftext:aid={aid} self:yes subreddit:DestinyTheGame", sortE: Sorting.Top))
                        {
                            Console.Write(".");
                            
                            if (++misses == 10)
                                return;

                            try
                            {
                                if (!post.IsSelfPost || (post.Title.IndexOf("Bungie Weekly Update", StringComparison.OrdinalIgnoreCase) == -1 && post.Title.IndexOf("Destiny Update", StringComparison.OrdinalIgnoreCase) == -1))
                                    continue;
                            }
                            catch (WebException ex) when ((ex.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.NotFound)
                            {
                                continue;
                            }

                            var scores = new List<double>();

                            foreach (var comment in post.GetCommentsRecursive())
                            {
                                if (string.IsNullOrEmpty(comment.Body))
                                    continue;
                                
                                scores.Add(i4Ds.LanguageToolkit.SentimentAnalyzer.GetSentiment("en", comment.Body));
                            }

                            var line = string.Format("{0:yyyy/MM/dd},{1}", post.CreatedUTC, scores.Average());

                            writer.WriteLine(line);

                            Console.WriteLine();
                            Console.WriteLine(line);

                            break;
                        }
                    }
                }
            }
        }
Example #23
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 void Main(string[] args)
        {
            Console.BufferWidth = 100;//Make console wider for better reading
            Console.SetWindowSize(Console.LargestWindowWidth / 2, Console.LargestWindowHeight / 2);
            Reddit reddit = new Reddit();
            while (reddit.User == null)//Keep trying to login until it works
            {
                Console.Write("Username: "******"Password: "******"Logging in...");
                    reddit.LogIn(username, password);
                }
                catch (AuthenticationException)
                {
                    Console.WriteLine("Incorrect login.");
                }
            }
            Console.WriteLine("Logged in.");

            Post p = reddit.GetPost("http://www.reddit.com/r/AskReddit/comments/1m15pa/teachers_of_reddit_what_is_the_funniest_thing/");//Put your post url (with http://) here
            Comment[] comments = p.GetComments();

            Console.WriteLine("Got post comments");

            string output = string.Empty;

            int i = 0;
            foreach (Comment c in comments)
            {
                try
                {
                    string text = c.Body;//Take the text of the string from the comment

                    if (!ContainsBlackListedWords(text))//Make sure the comment isn't a witty one liner (rudimentary)
                    {

                        string[] sentences = text.Split('.');//Split the comment into each setence

                        string sentence = sentences[i.MaxAt(sentences.Length-1)] + ".";//Take a sentence out of the sentence array
                        if (sentence.Length > 2 )//Check if it is a good sentence
                        {
                            sentence.Trim();//Trim spaces from both sides of the sentence.

                            Regex whitespaceremoval = new Regex(@"\s\s+");

                            sentence = whitespaceremoval.Replace(sentence, "");//Apply regex to remove excess spacing inside the sentence (readability)

                            //Regex alphanum = new Regex("[^a-zA-Z0-9. ,-]");

                            //sentence = alphanum.Replace(sentence, "");//Remove crazy symbol using regex (readability)

                            output += sentence;//Add the sentence to the output string

                            i++;//Increment i to continue the paragraph

                            Console.WriteLine("Parsed comment:" + i);//Log success
                        }
                    }
                    else
                    {
                        Console.WriteLine("Failed to parse comment : Comment contained blacklisted word");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to parse comment :" + e.Message);//Error catching for that damn null comment at the end of every post
                }
            }
            Console.WriteLine();//Add spacing
            Console.WriteLine();//""

            Console.Write(output);

            File.WriteAllText("out" + DateTime.Now.Ticks.ToString() + ".txt", output);

            Console.ReadKey();
        }
Example #25
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.
        }
Example #26
0
        public bool connect()//This is where the bot connects to the server and logs in
        {
            ChangeLabel("Connecting...");
            user_message = "USER " + NICK + " " + NICK + "_h" + " " + NICK + "_s" + " :/r/naruto \n";
            nick_message = "NICK " + NICK + "\r\n";
            join_message = "JOIN " + HOME_CHANNEL + "\r\n";
            quit_message = "QUIT " + HOME_CHANNEL + "\n";

            userList.Clear();

            irc = new TcpClient(HOST, PORT);
            stream = irc.GetStream();
            reader = new StreamReader(stream);
            writer = new StreamWriter(stream) { AutoFlush = true };

            reddit = new Reddit();


            if (Settings.Default.redditUserEnabled)
                user = reddit.LogIn(Settings.Default.redditUser, Settings.Default.redditPass);

            try
            {
                messageSender(writer, user_message);
                messageSender(writer, nick_message);
                return true;//Weee, we connected!
            }

            catch (SocketException se)
            {
                Console.Out.Write(se);
                return false;//Boo, we didnt connect
            }
        }
Example #27
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
        }