示例#1
0
        static void Main(string[] args)
        {
            var reddit = new RedditAPI("YourRedditAppID", "YourBotUserRefreshToken");

            // Retrieve the SelfPost we want and link to it on r/MySub.  The host will automatically be replaced with np.reddit.com and r/AskReddit will be credited in the title.  --Kris
            var newLinkPost = reddit.Subreddit("AskReddit").Posts.GetTop(t: "week")[0].XPostToAsLink("MySub");
        }
示例#2
0
        public List <DogeUrls> GetPicsUrls()
        {
            var appId        = Configuration["RedditSecretBot:AppId"];
            var Secret       = Configuration["RedditSecretBot:Secret"];
            var refreshToken = GetToken();

            RedditAPI reddit = new RedditAPI(appId,
                                             refreshToken, Secret, refreshToken);


            Subreddit sub   = reddit.Subreddit("Shiba");
            var       posts = sub.Posts.GetTop(new TimedCatSrListingInput(t: "day", limit: 10));

            List <DogeUrls> images = new List <DogeUrls>();

            if (posts.Any())
            {
                foreach (Post post in posts)
                {
                    if (post is LinkPost)
                    {
                        images.Add(new DogeUrls(
                                       (post as LinkPost).URL, (post as LinkPost).Thumbnail));
                    }
                }
            }


            return(images);
        }
示例#3
0
        // Post a trip report to the /r/randonauts subreddit
        // Reddit API used: https://github.com/sirkris/Reddit.NET/
        protected async Task PostTripReportToRedditAsync(string title, string text, string[] photoURLs)
        {
            // all posts are done under the user "thereal***REMOVED***"
            var redditApi = new RedditAPI(appId: Consts.REDDIT_APP_ID,
                                          appSecret: Consts.REDDIT_APP_SECRET,
                                          refreshToken: Consts.REDDIT_REFRESH_TOKEN,
                                          accessToken: Consts.REDDIT_ACCESS_TOKEN);

#if RELEASE_PROD
            var subreddit = redditApi.Subreddit("randonaut_reports");
#else
            var subreddit = redditApi.Subreddit("soliaxplayground");
#endif

            // Just seeing if we can upload images, was getting 403 error responses, even so it would be uploaded to the subreddit itself, not the user's post.
            // TODO: one day figure if we can upload images to posts
            //string photos = "";
            //if (photoURLs != null)
            //{
            //    int i = 0;
            //    foreach (string photoURL in photoURLs)
            //    {
            //        var webClient = new WebClient();
            //        byte[] imageBytes = webClient.DownloadData(photoURL);

            //        i++;
            //        ImageUploadResult imgRes = await subreddit.UploadImgAsync(imageBytes, $"Trip Photo #{i}");
            //        photos += $"![Trip Photo #{i}]({imgRes.ImgSrc})" + "\n\n";
            //    }

            //    text += "\n\n" + photos;
            //}

            await subreddit.SelfPost(title : title, selfText : text).SubmitAsync();
        }
示例#4
0
        static void Main(string[] args)
        {
            var reddit = new RedditAPI("YourRedditAppID", "YourBotUserRefreshToken");

            // Since we only need the posts, there's no need to call .About() on this one.  --Kris
            var worldnews = reddit.Subreddit("worldnews");

            // Just keep going until we hit a post from before today.  Note that the API may sometimes return posts slightly out of order.  --Kris
            var      posts    = new List <Post>();
            string   after    = "";
            DateTime start    = DateTime.Now;
            DateTime today    = DateTime.Today;
            bool     outdated = false;

            do
            {
                foreach (Post post in worldnews.Posts.GetNew(after: after))
                {
                    if (post.Created >= today)
                    {
                        posts.Add(post);
                    }
                    else
                    {
                        outdated = true;
                        break;
                    }

                    after = post.Fullname;
                }
            } while (!outdated &&
                     start.AddMinutes(5) > DateTime.Now &&
                     worldnews.Posts.New.Count > 0); // This is automatically populated with the results of the last GetNew call.  --Kris
        }
示例#5
0
        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation($"Starting reddit bot");

            if ((_config.GetValue("bot:REDDIT_CLIENT_ID", string.Empty) == string.Empty) ||
                (_config.GetValue("bot:REDDIT_REFRESH_TOKEN", string.Empty) == string.Empty) ||
                (_config.GetValue("bot:REDDIT_CLIENT_SECRET", string.Empty) == string.Empty))
            {
                _logger.LogWarning("Missing configuration entries for reddit");
                return(Task.CompletedTask);
            }

            if ((_config.GetValue("bot:REDDIT_SUBREDDIT", string.Empty) == string.Empty))
            {
                _logger.LogWarning("Missing configuration entry bot:REDDIT_SUBREDDIT");
                return(Task.CompletedTask);
            }

            _redditHelper = new RedditHelper(_config["DATACORE_WEB"], _logger, _searcher.Searcher, _crewData.BotHelper);

            _reddit = new RedditAPI(_config.GetValue <string>("bot:REDDIT_CLIENT_ID"), _config.GetValue <string>("bot:REDDIT_REFRESH_TOKEN"), _config.GetValue <string>("bot:REDDIT_CLIENT_SECRET"));

            _subReddit = _reddit.Subreddit(_config.GetValue <string>("bot:REDDIT_SUBREDDIT")).About();

            _subReddit.Posts.GetNew();
            _subReddit.Posts.MonitorNew();
            _subReddit.Posts.NewUpdated += c_NewPostAdded;

            return(Task.CompletedTask);
        }
示例#6
0
        static void Main(string[] args)
        {
            // TODO store subscriptions for renewal from pubsubhubbub (important)
            // TODO Handle invalid PMs better than just plain ignoring it
            // TODO [DONE] Step 0: Investigate issue with reddit token expiring
            // TODO Step 1: Setup channelbot on server
            // TODO Step 2: Send Reddit PMs to bot with add data (limited to 20 for testing reasons)
            // TODO Step 3: Validate bot working
            // TODO HMAC for pubsubhubbub
            var channels = JsonConvert.DeserializeObject <List <ChannelJson> >(File.ReadAllText("channels.json"));

            Console.WriteLine("Hello World!");
            var reddit = new RedditAPI(accessToken: "48589035-UwOdWWQh4Tg8VZCkPIx0zMwqEOU");
            var i      = 116;

            foreach (var channel in channels)
            {
                // 116
                i++;
                reddit.Account.Messages.Compose("channelbot", "add", $"channel_id: {channel.channel_id}\nsubreddit: {channel.subreddit}");
                // Wait 5 sec to not overload bot
                Thread.Sleep(5000);
                Console.WriteLine($"processing channel index: {i}");
            }
        }
示例#7
0
        public override TaskStatus Run()
        {
            Info("Retrieving post history...");

            Status status = Status.Success;

            RedditAPI reddit;

            try
            {
                reddit = new RedditAPI(AppId, RefreshToken);
                InfoFormat("Username: {0}", reddit.Account.Me.Name);
                InfoFormat("Cake Day: {0}", reddit.Account.Me.Created.ToString("D"));
                Info("Authentication succeeded.");
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception e)
            {
                ErrorFormat("Authentication failed: {0}", e.Message);
                return(new TaskStatus(Status.Error));
            }


            try
            {
                // Retrieve the authenticated user's recent post history.
                // Change "new" to "newForced" if you don't want older stickied profile posts to appear first.
                var posts = reddit.Account.Me.GetPostHistory(sort: "new", limit: MaxResults, show: "all");

                var xdoc = new XDocument(new XElement("Posts"));

                foreach (var post in posts)
                {
                    var xpost = new XElement("Post", new XAttribute("id", SecurityElement.Escape(post.Id)), new XAttribute("subreddit", SecurityElement.Escape(post.Subreddit)), new XAttribute("title", SecurityElement.Escape(post.Title)), new XAttribute("upvotes", post.UpVotes), new XAttribute("downvotes", post.DownVotes));
                    xdoc.Root.Add(xpost);
                }

                var xmlPath = Path.Combine(Workflow.WorkflowTempFolder,
                                           string.Format("{0}_{1:yyyy-MM-dd-HH-mm-ss-fff}.xml", "RedditListPosts", DateTime.Now));
                xdoc.Save(xmlPath);
                Files.Add(new FileInf(xmlPath, Id));
                InfoFormat("Post history written in {0}", xmlPath);
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception e)
            {
                ErrorFormat("An error occured while retrieving post history: {0}", e.Message);
                status = Status.Error;
            }

            Info("Task finished.");
            return(new TaskStatus(status));
        }
示例#8
0
        static void Main(string[] args)
        {
            var reddit = new RedditAPI("YourRedditAppID", "YourBotUserRefreshToken");

            Console.WriteLine("Username: "******"Cake Day: " + reddit.Account.Me.Created.ToString("D"));
        }
        private void AddPostURL(RedditAPI r, SelfPost post, ref List <string> getUrlFromPosts)
        {
            string url = (new LinkPost(r.Models, post)).URL;

            if (url.Contains("jpg", StringComparison.OrdinalIgnoreCase) ||
                url.Contains("png", StringComparison.OrdinalIgnoreCase))
            {
                getUrlFromPosts.Add(url);
            }
        }
示例#10
0
 internal Post Previous(RedditAPI reddit)
 {
     if (PostIndex > 0)
     {
         PostIndex--;
     }
     return(reddit.GetPosts(new List <string> {
         _seenPosts[PostIndex]
     }).First());
 }
示例#11
0
        public Sidebar()
        {
            this.InitializeComponent();
            refreshToken = localSettings.Values["refresh_token"].ToString();
            var reddit    = new RedditAPI(appId, localSettings.Values["refresh_token"].ToString(), secret);
            var subreddit = reddit.Subreddit("Appraisit");

            Joined.Text = subreddit.Subscribers.ToString() + "160+ Reddit Subscribers";
            Online.Text = subreddit.ActiveUserCount.ToString() + "10+ Online";
            About.Text  = " Discover new apps and games. Learn about improvements to your favorites and help them get discovered. You decide who rises to the top!";
        }
示例#12
0
        static void Main(string[] args)
        {
            var reddit = new RedditAPI("YourRedditAppID", "YourBotUserRefreshToken");

            List <Post> posts = reddit.Subreddit("MySub").Search(new SearchGetSearchInput("Bernie Sanders"));  // Search r/MySub

            if (posts.Count == 0)
            {
                posts = reddit.Subreddit("all").Search(new SearchGetSearchInput("Bernie Sanders"));  // Search r/all
            }
        }
示例#13
0
        private static async Task <bool> _EstablishApi(int timeout = DefaultTimeout)
        {
            _establishingApiFlag = true;
            Console.WriteLine($"\nObtaining access token from reddit (timeout={timeout}ms)... ({DateTime.UtcNow})");

            var redditUsername = await Resources.ReadAllTextAsync("reddit_username.txt").ConfigureAwait(false);

            var redditPassword = await Resources.ReadAllTextAsync("reddit_password.txt").ConfigureAwait(false);

            var appSecret = await Resources.ReadAllTextAsync("reddit_secret.txt").ConfigureAwait(false);

            var appId = await Resources.ReadAllTextAsync("reddit_app_id.txt").ConfigureAwait(false);

            var restClient = new RestClient("https://www.reddit.com")
            {
                Authenticator = new HttpBasicAuthenticator(appId, appSecret),
                Timeout       = timeout
            };
            var restRequest = new RestRequest("/api/v1/access_token", Method.POST);

            restRequest.AddHeader("User-Agent", UserAgent);
            restRequest.AddParameter("grant_type", "password");
            restRequest.AddParameter("username", redditUsername);
            restRequest.AddParameter("password", redditPassword);

            IRestResponse restResponse = await restClient.ExecutePostTaskAsync(restRequest).ConfigureAwait(false);

            string accessToken;

            try
            {
                var restResponseJson = JObject.Parse(restResponse.Content);
                accessToken = (string)restResponseJson.GetValue("access_token");
            }
            catch (Exception)
            {
                Console.WriteLine("Error: could not obtain Reddit access token. " +
                                  "Received response from https://www.reddit.com/api/v1/access_token:");
                Console.WriteLine(restResponse.Content);

                Api = null;
                _establishingApiFlag = false;

                return(false);
            }

            Console.WriteLine("Reddit access token successfully obtained!");

            Api = new RedditAPI(appId, appSecret: appSecret, accessToken: accessToken);
            _establishingApiFlag = false;

            return(true);
        }
示例#14
0
        internal Post Next(RedditAPI reddit, bool skipSeenPosts = true)
        {
            if (++PostIndex < _seenPosts.Count)
            {
                return(reddit.GetPosts(new List <string> {
                    _seenPosts[PostIndex]
                }).First());
            }

            var newPost = GetNewPost(GetSubreddit(reddit, Properties.SubredditName), Properties.Type, skipSeenPosts ? _seenPosts : null);

            _seenPosts.Add(newPost.Fullname);
            return(newPost);
        }
示例#15
0
        static void Main(string[] args)
        {
            var reddit = new RedditAPI("YourRedditAppID", "YourBotUserRefreshToken");

            // reddit.Subreddit("MySubreddit") loads an empty named subreddit instance, then About() queries Reddit and returns the data.  --Kris
            var subreddit = reddit.Subreddit("MySubreddit").About();

            /*
             * Gather all of yesterday's posts and add the total comments.  Note the use of "after" for pagination, as the API is limited to a maximum of 100 results per query.
             * The API sometimes returns posts slightly out of order (don't ask me why), so this will keep going until it gets 3 or more consecutive posts outside the date range.  It's an arbitrary number but should be sufficient.
             * Loop will timeout after 5 minutes, just to be safe.
             *
             * --Kris
             */
            int      totalComments = 0;
            int      outdatedPosts = 0;
            string   after         = "";
            DateTime start         = DateTime.Now;

            do
            {
                foreach (Post post in subreddit.Posts.GetNew(new CategorizedSrListingInput(after: after, limit: 100)))
                {
                    // Keep going until we hit 3 posts in a row from the day before yesterday.  Today's posts are completely ignored.  --Kris
                    if (post.Created >= DateTime.Today.AddDays(-1) && post.Created < DateTime.Today)
                    {
                        outdatedPosts  = 0;
                        totalComments += post.Listing.NumComments;
                    }
                    else if (post.Created < DateTime.Today.AddDays(-1))
                    {
                        outdatedPosts++;
                    }

                    after = post.Fullname;
                }
            } while (outdatedPosts < 3 && start.AddMinutes(5) > DateTime.Now);

            // Create a new self-post to report the result.  --Kris
            var newPost = subreddit.SelfPost("Total Comments for " + DateTime.Today.AddDays(-1).ToString("D"), totalComments.ToString()).Submit();

            // Update the sidebar to reflect yesterday's total.  --Kris
            subreddit.Sidebar = "**Yesterday's Comments Total:** " + totalComments.ToString();
            try
            {
                subreddit.Update();  // Sends the subreddit data with the updated sidebar text back to the Reddit API to apply the change.  --Kris
            }
            catch (RedditControllerException) { }
        }
示例#16
0
        public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Stopping reddit bot");

            if (_subReddit != null)
            {
                _subReddit.Posts.MonitorNew();
                _subReddit.Posts.NewUpdated -= c_NewPostAdded;
                _subReddit    = null;
                _reddit       = null;
                _redditHelper = null;
            }

            return(Task.CompletedTask);
        }
示例#17
0
        private static void Main(string[] args)
        {
            //Console.Clear();
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Starting ChannelBot2");
            Console.CancelKeyPress += (sender, eArgs) => {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };
            Console.ForegroundColor = ConsoleColor.White;

            // Rainbows!!
            Console.ForegroundColor = ConsoleColor.Cyan;
            // Setup RedditToken for use in polling etc.
            var redditTokenManager = new RedditTokenManager();

            redditTokenManager.Start();
            Console.WriteLine("Initialized reddit token manager..");

            // Setup Reddit Client
            var redditAPI = new RedditAPI(accessToken: RedditTokenManager.CurrentToken);

            using (var reddit = new Reddit(redditAPI))
            {
                Program.reddit          = reddit;
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("Initialized reddit logic..");
                reddit.MonitorUnreadPMs();
                Console.ForegroundColor = ConsoleColor.Magenta;
                Console.WriteLine("Monitoring reddit PMs every 30sec..");

                //Start polling
                var pollManager = new PollManager();
                pollManager.Start();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Initialized backup poller for sending out posts to subreddits");

                // Start pubsubhubbub, call dispose on it to remove listeners from event
                using (var hubbub = new PubSubHubBub())
                {
                    hubbub.Start();
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("[SUPERDEBUG] Setup pubsubhubbub TCP listener..\r\n");
                    Console.ForegroundColor = ConsoleColor.DarkYellow;
                    QuitEvent.WaitOne();
                }
            }
        }
示例#18
0
        // Load ELIZA script file and instantiate our libraries.  --Kris
        public ELIZA()
        {
            string json = null;

            using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("DOCTOR.json"))
            {
                using (StreamReader streamReader = new StreamReader(stream))
                {
                    json = streamReader.ReadToEnd();
                }
            }

            Eliza          = new ELIZALib(json);
            Reddit         = new RedditAPI("YourAppID", "YourRefreshToken");
            ActiveSessions = new Dictionary <string, DateTime>();
        }
示例#19
0
        public BaseTests()
        {
            testData = GetData();

            // Primary test user's instance.  --Kris
            reddit = new RedditAPI(testData["AppId"], testData["RefreshToken"]);

            try
            {
                // Secondary test user's instance.  --Kris
                reddit2 = new RedditAPI(testData["AppId"], testData["RefreshToken2"]);
            }
            catch (Exception) { }

            // App-only instance.  --Kris
            reddit3 = new RedditAPI(testData["AppId"]);
        }
示例#20
0
        static void Main(string[] args)
        {
            var reddit = new RedditAPI("YourRedditAppID", "YourBotUserRefreshToken");

            NewMessages = new List <ConversationMessage>();

            // Start monitoring unread modmail messages and register the callback function.  --Kris
            reddit.Account.Modmail.MonitorUnread();
            reddit.Account.Modmail.UnreadUpdated += C_UnreadMessagesUpdated;

            while (true)
            {
            }                // Replace this with whatever you've got for a program loop.  The monitoring will run asynchronously in a separate thread.  --Kris

            // Stop monitoring and unregister the callback function.  --Kris
            reddit.Account.Modmail.MonitorUnread();
            reddit.Account.Modmail.UnreadUpdated -= C_UnreadMessagesUpdated;
        }
示例#21
0
        public void CheckAction(Models.Account user, DateTime lastCheck)
        {
            RedditAPI api = _redditService.GetApi(_redditService.GetToken(user));

            var subreddits = api.Account.MySubscribedSubreddits();

            for (int i = 0; i < subreddits.Count; i++)
            {
                var risingPosts = subreddits[i].Posts.Top;

                for (int j = 0; j < risingPosts.Count; j++)
                {
                    if (risingPosts[j].Created > lastCheck)
                    {
                        _newTopPosts.Add(risingPosts[j]);
                    }
                }
            }
        }
        public void CheckAction(Models.Account user, DateTime lastCheck)
        {
            RedditAPI api = _redditService.GetApi(_redditService.GetToken(user));

            var comments = api.Account.Me.CommentHistory();

            for (int i = 0; i < comments.Count; i++)
            {
                var replies = comments[i].Replies;

                for (int j = 0; j < replies.Count; j++)
                {
                    if (replies[j].Created > lastCheck)
                    {
                        _newReplies.Add(replies[j]);
                    }
                }
            }
        }
示例#23
0
        //Gathers comments from a few specified facebook and reddit accounts to use as training data
        private void GatherTrainingData()
        {
            List <string> conservativeComments = new List <string>();
            List <string> liberalComments      = new List <string>();

            RedditAPI   rd = new RedditAPI();
            FacebookAPI fb = new FacebookAPI();

            //TODO: Check if these still work with the changes to GetPosts
            conservativeComments.AddRange(fb.GetPostMessages("DonaldTrump"));
            conservativeComments.AddRange(fb.GetPostMessages("VicePresidentPence"));
            conservativeComments.AddRange(fb.GetPostMessages("100000544532899"));
            conservativeComments.AddRange(fb.GetPostMessages("100001387924004"));
            conservativeComments.AddRange(fb.GetPostMessages("100001351601986"));
            conservativeComments.AddRange(fb.GetPostMessages("100007241612747"));

            conservativeComments.AddRange(rd.GetCommentsText("JackalSpat"));
            conservativeComments.AddRange(rd.GetCommentsText("neemarita"));
            conservativeComments.AddRange(rd.GetCommentsText("AVDLatex"));
            conservativeComments.AddRange(rd.GetCommentsText("optionhome"));
            conservativeComments.AddRange(rd.GetCommentsText("2481632641282565121k"));

            liberalComments.AddRange(fb.GetPostMessages("100007731198419"));
            liberalComments.AddRange(fb.GetPostMessages("1534242220"));
            liberalComments.AddRange(fb.GetPostMessages("1521723653"));
            liberalComments.AddRange(fb.GetPostMessages("100001884654096"));
            liberalComments.AddRange(fb.GetPostMessages("hillaryclinton"));

            liberalComments.AddRange(rd.GetCommentsText("Mentoman72"));
            liberalComments.AddRange(rd.GetCommentsText("jereddit"));
            liberalComments.AddRange(rd.GetCommentsText("TheHeckWithItAll"));
            liberalComments.AddRange(rd.GetCommentsText("bustopher-jones"));
            liberalComments.AddRange(rd.GetCommentsText("TheSelfGoverned"));
            liberalComments.AddRange(rd.GetCommentsText("Splatypus"));

            string liberalPath      = System.Web.Hosting.HostingEnvironment.MapPath(@"~/Data/liberal_training.txt");
            string conservativePath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/Data/conservative_training.txt");

            File.WriteAllLines(liberalPath, liberalComments.ToArray());
            File.WriteAllLines(conservativePath, conservativeComments.ToArray());
        }
        static void Main(string[] args)
        {
            var reddit = new RedditAPI("YourRedditAppID", "YourBotUserRefreshToken");

            NewComments = new List <Comment>();

            // Start monitoring the subreddit for new comments and register the callback function.  --Kris
            var subreddit = reddit.Subreddit("AskReddit");

            subreddit.Comments.GetNew();              // This call prevents any existing "new"-sorted comments from triggering the update event.  --Kris
            subreddit.Comments.MonitorNew();
            subreddit.Comments.NewUpdated += C_NewCommentsUpdated;

            while (true)
            {
            }                           // Replace this with whatever you've got for a program loop.  The monitoring will run asynchronously in a separate thread.  --Kris

            // Stop monitoring and unregister the callback function.  --Kris
            subreddit.Comments.MonitorNew();
            reddit.Account.Modmail.NewUpdated -= C_NewCommentsUpdated;
        }
示例#25
0
        public async Task <ActionResult <string> > Post([FromBody] TokenGroup tokenGroup)
        {
            string username;

            try
            {
                RedditAPI reddit = new RedditAPI(System.Environment.GetEnvironmentVariable("VUE_APP_CLIENT_ID"), accessToken: tokenGroup.AccessToken);
                username = reddit.Account.Me.Name;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(Unauthorized(e.Message));
            }

            // No exceptions, token is valid and we have username
            // insert into database and store the primary key
            RedditUser user;

            try
            {
                string hashedUsername = RedditUser.HashUsername(username);
                user = _context.RedditUsers.Single(u => u.Username == hashedUsername);
            }
            catch (InvalidOperationException)
            {
                user = new RedditUser()
                {
                    Username = username
                };
                _context.Add(user);
                _context.SaveChanges();
            }
            // retrieve username using Reddit.NET and variables from .env
            // if successful, store hashed token and hashed username in tables
            // call AuthenticateUser(username, token)
            await AuthenticateUser(user.Id, tokenGroup.RefreshToken);

            return(NoContent());
        }
        static void Main(string[] args)
        {
            var reddit = new RedditAPI("YourRedditAppID", "YourBotUserRefreshToken");

            var subreddit = reddit.Subreddit("MySub");
            var today     = DateTime.Today;

            string pageContent = "## Top Posts for " + today.ToString("D") + Environment.NewLine;

            // Get the top 10 posts from the last 24 hours.  --Kris
            var posts = subreddit.Posts.GetTop(new TimedCatSrListingInput(t: "day", limit: 10));

            if (posts.Count > 0)
            {
                foreach (Post post in posts)
                {
                    if (post.Created >= today && post.Created < today.AddDays(1))
                    {
                        pageContent += Environment.NewLine + "### [" + post.Title + "](" + post.Permalink + ")" + Environment.NewLine;
                    }
                }
            }
            else
            {
                pageContent += "*There were no new top posts today.*";
            }

            var pageUrl = "TopPosts/" + today.Year + "/" + today.Month + "/" + today.Day;

            // Create the wiki page.  Note that the first argument is the edit reason for the history and is required by the API.  --Kris
            var wikiPage = subreddit.Wiki.Page(pageUrl).CreateAndReturn("Created the page.", pageContent);

            // Retrieve the index.  Note that this page should already exist with a single revision even on a brand new subreddit.  --Kris
            var index = subreddit.Wiki.GetPage("index");

            // You'd probably want to break this up into multiple pages and whatnot, but you get the idea.  --Kris
            index.EditAndReturn("Added top posts for: " + today.ToString("D"),
                                index.ContentMd + Environment.NewLine + "### [" + today.ToString("D") + "](" + pageUrl + ")" + Environment.NewLine,
                                index.Revisions()[0].Id); // FYI, the Revisions() are sorted by most-recent first.  --Kris
        }
示例#27
0
        public async Task <IEnumerable <Posts> > GetPagedItemsAsync(int pageIndex, int pageSize, CancellationToken cancellationToken = default(CancellationToken))
        {
            await Task.Run(() =>
            {
                string refreshToken = localSettings.Values["refresh_token"].ToString();
                PostCollection      = new List <Posts>();
                var reddit          = new RedditAPI(appId, refreshToken, secret);
                var subreddit       = reddit.Subreddit("Appraisit");
                var posts           = subreddit.Posts.GetControversial(limit: limit).Skip(skipInt);
                limit = limit + 10;

                foreach (Post post in posts)
                {
                    // pageContent += Environment.NewLine + "### [" + post.Title + "](" + post.Permalink + ")" + Environment.NewLine;

                    var p = post as SelfPost;
                    // Console.WriteLine("New Post by " + post.Author + ": " + post.Title);
                    PostCollection.Add(new Posts()
                    {
                        TitleText        = post.Title,
                        PostSelf         = post,
                        PostAuthor       = string.Format("PostBy".GetLocalized(), post.Author),
                        PostDate         = string.Format("PostDate".GetLocalized(), post.Created),
                        PostUpvotes      = post.UpVotes.ToString(),
                        PostDownvotes    = post.DownVotes.ToString(),
                        PostCommentCount = post.Comments.GetComments("new").Count.ToString(),
                        PostFlair        = post.Listing.LinkFlairText,
                        PostFlairColor   = post.Listing.LinkFlairBackgroundColor
                    });
                }

                // Simulates a longer request...
                skipInt = skipInt + 10;
            });

            // Gets items from the collection according to pageIndex and pageSize parameters.


            return(PostCollection);
        }
示例#28
0
        private List <Post> GetTopRedditPosts(string subRedditName, int amountOfPosts, string sortType, string sortTypeTopType)
        {
            //Add your reddit bot appID which is right below the use of the app and your secret. You can get your refreashtoken from a easy to use reddit python script.
            var reddit = new RedditAPI(
                appId: Config.config.RedditAppId,
                appSecret: Config.config.RedditAppSecret,
                refreshToken: Config.config.RedditAppRefreshToken);

            Subreddit posts;

            if (amountOfPosts > 100)
            {
                amountOfPosts = 100;
            }

            switch (sortType)
            {
            case "top":
                posts = reddit.Subreddit(subRedditName).About();
                return(posts.Posts.GetTop(sortTypeTopType, "", "", amountOfPosts));

            case "hot":
                posts = reddit.Subreddit(subRedditName).About();
                return(posts.Posts.GetHot("", "", "", amountOfPosts));

            case "new":
                posts = reddit.Subreddit(subRedditName).About();
                return(posts.Posts.GetNew("", "", amountOfPosts));

            case "rising":
                posts = reddit.Subreddit(subRedditName).About();
                return(posts.Posts.GetControversial("top", "", "", amountOfPosts));

            default:
                posts = reddit.Subreddit(subRedditName).About();
                return(posts.Posts.GetTop(sortTypeTopType, "", "", amountOfPosts));
            }
        }
示例#29
0
        static void Main(string[] args)
        {
            var reddit = new RedditAPI("YourRedditAppID", "YourBotUserRefreshToken");

            // Since we only need the posts, there's no need to call .About() on this one.  --Kris
            var news = reddit.Subreddit("news");

            /*
             * If you call GetTop() directly, the last "t" value you passed will be used for the .Top property.
             * Remember that the .Top property is automatically cached with the results of GetTop(), so we're
             * only doing one API query for the posts retrieval part.
             *
             * --Kris
             */
            if (news.Posts.GetTop(t: "day")[0].Listing.IsSelf)
            {
                var newSelfPost = news.SelfPost(news.Posts.Top[0].Fullname).About().XPostTo("MySub");
            }
            else
            {
                var newLinkPost = news.LinkPost(news.Posts.Top[0].Fullname).About().XPostTo("MySub");
            }
        }
示例#30
0
        public MainPage()
        {
            InitializeComponent();
            FlowListView.Init();

            var r   = new RedditAPI("8fp-KAo4cqMTCA", "42551102-qKfgfzbeZW1MZaegec6AiOZ8z0w");
            var sub = r.Subreddit("aww");

            var getHotPosts    = sub.Posts.GetHot(limit: 20);
            var getRisingPosts = sub.Posts.GetRising(limit: 15);

            List <string> getUrlFromPosts = new List <string>();

            for (int i = 0; i < Math.Max(getHotPosts.Count, getRisingPosts.Count); i++)
            {
                if (i < getHotPosts.Count &&
                    !getHotPosts[i].Listing.IsSelf)
                {
                    AddPostURL(r, (SelfPost)getHotPosts[i], ref getUrlFromPosts);
                }
                if (i < getRisingPosts.Count &&
                    !getRisingPosts[i].Listing.IsSelf)
                {
                    AddPostURL(r, (SelfPost)getRisingPosts[i], ref getUrlFromPosts);
                }
            }

            gridaww.FlowItemsSource = getUrlFromPosts;

            gridaww.FlowColumnCount           = 3;
            gridaww.FlowRowBackgroundColor    = Color.White;
            gridaww.VerticalOptions           = LayoutOptions.FillAndExpand;
            gridaww.HorizontalOptions         = LayoutOptions.FillAndExpand;
            gridaww.FlowTappedBackgroundColor = Color.Gray;
            gridaww.RowHeight = 200;
        }
示例#31
0
    // Use this for initialization
    void Start()
    {
        spaceship.SetActiveRecursively(false);
        slideRightTime = spaceship.animation["slerp"].length;
        slideRightTime = spaceship.animation["slerp"].speed = .01f;
        spawner.active = false;
        reddit = new RedditAPI("SpaceKnightsOfNew_Game v.2 /u/publicstaticlloyd");

        currentLinks = new List<LinkBrief>();
        startPosition = startTransform.position;
        startRotation = startTransform.rotation;
    }