Example #1
0
 /// <summary>
 /// Retrieves your test subreddit.  It is assumed that the subreddit already exists at this point.
 /// </summary>
 /// <returns>The populated Subreddit data.</returns>
 protected Controllers.Subreddit GetSubreddit(ref Controllers.Subreddit subreddit)
 {
     subreddit = reddit.Subreddit(testData["Subreddit"]).About();
     return(subreddit);
 }
Example #2
0
        /// <summary>
        /// The main method for the example application.
        /// </summary>
        /// <param name="args">If you're using the VS debugger, go to the Example project properties and
        /// enter your args in the "Application Arguments" field under "Debug" as you would in the CLI</param>
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("Usage: Example <Reddit App ID> <Reddit Refresh Token> [Reddit Access Token]");
            }
            else
            {
                string appId        = args[0];
                string refreshToken = args[1];
                string accessToken  = (args.Length > 2 ? args[2] : null);

                // Initialize the API library instance.  --Kris
                RedditAPI reddit = new RedditAPI(appId: appId, refreshToken: refreshToken, accessToken: accessToken);

                // Get info on the Reddit user authenticated by the OAuth credentials.  --Kris
                User me = reddit.Account.Me;

                Console.WriteLine("Username: "******"Cake Day: " + me.Created.ToString("D"));

                // Get post and comment histories (note that pinned profile posts appear at the top even on new sort; use "newForced" sort as a workaround).  --Kris
                List <Post>    postHistory    = me.PostHistory(sort: "newForced");
                List <Comment> commentHistory = me.CommentHistory(sort: "new");

                if (postHistory.Count > 0)
                {
                    Console.WriteLine("Most recent post: " + postHistory[0].Title);
                }
                if (commentHistory.Count > 0)
                {
                    Console.WriteLine("Most recent comment: " + commentHistory[0].Body);
                }

                // Create a new subreddit.  --Kris
                //Subreddit newSub = reddit.Subreddit("RDNBotSub", "Test Subreddit", "Test sub created by Reddit.NET", "My sidebar.").Create();

                // Get best posts.  Note that "Best" listings are subreddit-agnostic.  --Kris
                List <Post> bestPosts = reddit.Subreddit().Posts.Best;

                if (bestPosts.Count > 0)
                {
                    Console.WriteLine("Current best post (by " + bestPosts[0].Author + "): [" + bestPosts[0].Subreddit + "] " + bestPosts[0].Title);
                }

                // Get info about a subreddit.  --Kris
                Subreddit sub = reddit.Subreddit("AskReddit").About();

                Console.WriteLine("Subreddit Name: " + sub.Name);
                Console.WriteLine("Subreddit Fullname: " + sub.Fullname);
                Console.WriteLine("Subreddit Title: " + sub.Title);
                Console.WriteLine("Subreddit Description: " + sub.Description);

                // Get new posts from this subreddit.  --Kris
                List <Post> newPosts = sub.Posts.New;

                Console.WriteLine("Retrieved " + newPosts.Count.ToString() + " new posts.");

                // Monitor new posts on this subreddit for a minute.  --Kris
                Console.WriteLine("Monitoring " + sub.Name + " for new posts....");

                sub.Posts.NewUpdated += C_NewPostsUpdated;
                sub.Posts.MonitorNew();  // Toggle on.

                /*
                 * But wait, there's more!  We can monitor posts on multiple subreddits at once (delay is automatically multiplied to keep us under speed the limit).
                 * If you want to see something really crazy, check out Reddit.NETTests.ControllerTests.WorkflowTests.StressTests.AsyncTests.PoliceState().  That
                 * test creates 60 new posts on the test subreddit (and 10 comments for each post), while simultaneously monitoring each of these 60 posts for new
                 * comments, all while monitoring the test subreddit for new posts.  Of course, the delay between each monitoring thread's request would be roughly
                 * 90 seconds in this case (the delay is the number of things being monitored times 1.5 seconds), but the library handles all that for you automatically.
                 *
                 * I strongly recommend you closely examine the Reddit.NETTests project if you wish to become well-versed in developing using this library.
                 *
                 * --Kris
                 */
                Subreddit funny     = reddit.Subreddit("funny");
                Subreddit worldnews = reddit.Subreddit("worldnews");

                // Before monitoring, let's grab the posts once so we have a point of comparison when identifying new posts that come in.  --Kris
                funny.Posts.GetNew();
                worldnews.Posts.GetNew();

                Console.WriteLine("Monitoring funny for new posts....");

                funny.Posts.NewUpdated += C_NewPostsUpdated;
                funny.Posts.MonitorNew();  // Toggle on.

                Console.WriteLine("Monitoring worldnews for new posts....");

                worldnews.Posts.NewUpdated += C_NewPostsUpdated;
                worldnews.Posts.MonitorNew(10000);  // Toggle on with a custom delay of 10 seconds between each monitoring query.

                DateTime start = DateTime.Now;
                while (start.AddMinutes(1) > DateTime.Now)
                {
                }

                // Stop monitoring new posts.  --Kris
                sub.Posts.MonitorNew();  // Toggle off.
                sub.Posts.NewUpdated -= C_NewPostsUpdated;

                funny.Posts.MonitorNew();  // Toggle off.
                funny.Posts.NewUpdated -= C_NewPostsUpdated;

                worldnews.Posts.MonitorNew();  // Toggle off.
                worldnews.Posts.NewUpdated -= C_NewPostsUpdated;

                Console.WriteLine("Done monitoring!");

                // Grab today's top post in AskReddit and monitor its new comments.  --Kris
                Post post = sub.Posts.GetTop("day")[0];
                post.Comments.GetNew();

                Console.WriteLine("Monitoring today's top post on AskReddit....");

                post.Comments.MonitorNew();  // Toggle on.
                post.Comments.NewUpdated += C_NewCommentsUpdated;

                start = DateTime.Now;
                while (start.AddMinutes(1) > DateTime.Now)
                {
                }

                post.Comments.MonitorNew();  // Toggle off.
                post.Comments.NewUpdated -= C_NewCommentsUpdated;

                Console.WriteLine("Done monitoring!");

                // Now let's monitor r/all for a bit.  --Kris
                Subreddit all = reddit.Subreddit("all");
                all.Posts.GetNew();

                Console.WriteLine("Monitoring r/all for new posts....");

                all.Posts.MonitorNew();  // Toggle on.
                all.Posts.NewUpdated += C_NewPostsUpdated;

                start = DateTime.Now;
                while (start.AddMinutes(1) > DateTime.Now)
                {
                }

                all.Posts.MonitorNew();  // Toggle off.
                all.Posts.NewUpdated -= C_NewPostsUpdated;

                Console.WriteLine("Done monitoring!");
            }
        }
Example #3
0
        public Workflow()
        {
            ConfigDir = Path.Combine(Environment.CurrentDirectory, "config");
            if (!Directory.Exists(ConfigDir))
            {
                Directory.CreateDirectory(ConfigDir);
            }

            ConfigPath = Path.Combine(ConfigDir, "RedditBerner.config.json");
            if (!File.Exists(ConfigPath))
            {
                // Create new config file and prompt user for token retrieval process.  --Kris
                Config = new Config(AppId);

                Console.WriteLine("****************************");
                Console.WriteLine("* Welcome to RedditBerner! *");
                Console.WriteLine("****************************");

                Console.WriteLine();

                Console.WriteLine("Before the bot can run, we'll need to link it to your Reddit account.");
                Console.WriteLine("This is very easy:  Whenever you're ready, press any key and a browser window will open and take you to the Reddit authentication page.");
                Console.WriteLine("Enter your username/password if you're not already logged in, then scroll down and click on the 'Allow' button to authorize this app to use your Reddit account.");

                Console.WriteLine();

                Console.WriteLine("Press any key to continue....");

                Console.ReadKey();

                AuthTokenRetrieverLib authTokenRetrieverLib = new AuthTokenRetrieverLib(AppId);
                authTokenRetrieverLib.AwaitCallback();

                Console.Clear();

                Console.WriteLine("Opening web browser....");

                OpenBrowser(authTokenRetrieverLib.AuthURL());

                DateTime start = DateTime.Now;
                while (string.IsNullOrWhiteSpace(authTokenRetrieverLib.RefreshToken) &&
                       start.AddMinutes(5) > DateTime.Now)
                {
                    Thread.Sleep(1000);
                }

                if (string.IsNullOrWhiteSpace(authTokenRetrieverLib.RefreshToken))
                {
                    throw new Exception("Unable to authorize Reddit; timeout waiting for Refresh Token.");
                }

                Config.AccessToken  = authTokenRetrieverLib.AccessToken;
                Config.RefreshToken = authTokenRetrieverLib.RefreshToken;

                SaveConfig();

                Console.WriteLine("Reddit authentication successful!  Press any key to continue....");

                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("*************************");
                Console.WriteLine("*      RedditBerner     *");
                Console.WriteLine("* Created by Kris Craig *");
                Console.WriteLine("*************************");

                Console.WriteLine();

                LoadConfig();
            }

            ScriptsDir = Path.Combine(Environment.CurrentDirectory, "scripts");
            if (!Directory.Exists(ScriptsDir))
            {
                Directory.CreateDirectory(ScriptsDir);
            }

            if (!Directory.EnumerateFileSystemEntries(ScriptsDir).Any())
            {
                throw new Exception("Scripts directory cannot be empty!  Please add at least 1 text file to serve as a comment template so the app knows what content to post.");
            }

            LoadScripts();
            if (Scripts == null ||
                Scripts.Count.Equals(0))
            {
                throw new Exception("No suitable scripts found!  Please add at least 1 text file under 10 K to serve as a comment template so the app knows what content to post.");
            }

            Reddit = new RedditAPI(appId: AppId, refreshToken: Config.RefreshToken, accessToken: Config.AccessToken);

            SubredditsPath = Path.Combine(ConfigDir, "subreddits.json");
            if (!File.Exists(SubredditsPath))
            {
                Subreddits = new List <Subreddit>
                {
                    Reddit.Subreddit("StillSandersForPres"),
                    Reddit.Subreddit("WayOfTheBern"),
                    Reddit.Subreddit("SandersForPresident"),
                    Reddit.Subreddit("BernieSanders")
                };
                SaveSubreddits();
            }
            else
            {
                LoadSubreddits();
            }

            Random = new Random();
        }
Example #4
0
        static void Main(string[] args)
        {
            var reddit = new RedditAPI("YourRedditAppID", "YourBotUserRefreshToken");

            reddit.Subreddit("MySub").Flairs.CreateUserFlair("KrisCraig", "F*****g Genius");
        }