public void getLowPriorityPost() { while (!isJobDone) { bool isSkipSleep = false; Console.WriteLine("[{0}] checking...", DateTime.Now.ToShortTimeString()); if (_shutdownEvent.WaitOne(0)) { break; } try { subreddit = reddit.GetSubreddit("/r/Dota2"); } catch (WebException ex) { isSkipSleep = true; Console.WriteLine("[{0}] WebException... Retrying...", DateTime.Now.ToShortTimeString()); Thread.Sleep(10000); } try { lock (queue) { IEnumerable<Post> posts = subreddit.New.Take(200); foreach (Post post in posts) { if ((post.Title.Contains("LP ")) || (post.Title.Contains(" LP")) || (post.Title.Contains("(LP)")) || (post.Title.Contains("[LP]")) || (post.Title.Contains("LPQ ")) || (post.Title.Contains(" LPQ")) || (post.Title.Contains("(LPQ)")) || (post.Title.Contains("[LPQ]")) || (post.Title.Contains("low prio")) || (post.Title.Contains("Low priority")) || (post.Title.Contains("Low Priority")) || (post.Title.Contains("low priority")) || (post.Title.IndexOf("low priority", StringComparison.OrdinalIgnoreCase) >= 0) || (post.Title.IndexOf("low prio", StringComparison.OrdinalIgnoreCase) >= 0)) { if (!ShitpostDBConnector.isExists(post.Permalink.ToString())) { if (!queue.Contains(post)) { queue.Enqueue(post); Console.WriteLine(post.Permalink.ToString()); } } } } } } catch (WebException wex) { Console.WriteLine(wex); Console.WriteLine("[{0}] retrying...", DateTime.Now.ToShortTimeString()); isSkipSleep = true; Thread.Sleep(10000); } if (!isSkipSleep) { Thread.Sleep(300000); } } }
public SubredditStyle(Reddit reddit, Subreddit subreddit, JToken json, IWebAgent webAgent) : this(reddit, subreddit, webAgent) { Images = new List<SubredditImage>(); var data = json["data"]; CSS = HttpUtility.HtmlDecode(data["stylesheet"].Value<string>()); foreach (var image in data["images"]) { Images.Add(new SubredditImage( Reddit, this, image["link"].Value<string>(), image["name"].Value<string>(), image["url"].Value<string>(), WebAgent)); } }
private void BuildListings(EntityBuilder entityBuilder, Subreddit subreddit) { BuildListingOption(entityBuilder, subreddit, "hot"); BuildListingOption(entityBuilder, subreddit, "new"); BuildListingOption(entityBuilder, subreddit, "rising"); BuildListingOption(entityBuilder, subreddit, "top"); BuildListingDuration(entityBuilder, subreddit, "top", "hour", "past hour"); BuildListingDuration(entityBuilder, subreddit, "top", "day", "past day"); BuildListingDuration(entityBuilder, subreddit, "top", "week", "past week"); BuildListingDuration(entityBuilder, subreddit, "top", "month", "past month"); BuildListingDuration(entityBuilder, subreddit, "top", "year", "past year"); BuildListingDuration(entityBuilder, subreddit, "top", "all", "all time"); }
public async Task RandomPost([Summary("The subreddit to look for a random post")] string rsubreddit) { try { string filtered = Regex.Replace(rsubreddit, "/?r/", ""); RedditApi redditService = new RedditApi(); Subreddit subreddit = await redditService.GetSubredditAsync(filtered); RedditNet.Things.Link link = await subreddit.GetRandomLinkAsync(); await ReplyAsync(link.Title + " - " + link.Url); } catch { await ReplyAsync("Sorry, I couldn't find a random post in that subreddit!"); } }
public async Task <bool> CheckSubredditAsync(string name) { try { Reddit reddit = new Reddit(); Subreddit subreddit = await reddit.GetSubredditAsync(name); var post = subreddit.New.Take(1); return(true); } catch { return(false); } }
/// <summary> /// Returns a collector for the given type. If the collector doesn't exist one will be created. /// </summary> /// <param name="subreddit"></param> /// <param name="baconMan"></param> /// <param name="sort"></param> /// <param name="sortTime"></param> /// <returns></returns> public static PostCollector GetCollector(Subreddit subreddit, BaconManager baconMan, SortTypes sort = SortTypes.Hot, SortTimeTypes sortTime = SortTimeTypes.Week, string forcePostId = null) { var container = new PostCollectorContext { Subreddit = subreddit, SortType = sort, ForcePostId = forcePostId, SortTimeType = sortTime, UniqueId = subreddit.Id + sort + sortTime + (string.IsNullOrWhiteSpace(forcePostId) ? string.Empty : forcePostId) }; // Make the uniqueId. If we have a force post add that also so we don't get an existing collector with the real subreddit. return((PostCollector)GetCollector(typeof(PostCollector), container.UniqueId, container, baconMan)); }
public ActionResult AddSubreddit(SubredditViewModel subredditViewModel) { using (var redditCloneContext = new RedditCloneContext()) { var subreddit = new Subreddit { SubredditName = subredditViewModel.SubredditName }; redditCloneContext.Subreddits.Add(subreddit); redditCloneContext.SaveChanges(); return(RedirectToAction("Detail", new { id = subreddit.SubredditId })); } }
/// <summary> /// Fired when a search result is tapped /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SearchResults_SelectionChanged(object sender, SelectionChangedEventArgs e) { // Grab the result SearchResult tappedResult = (SearchResult)ui_searchResults.SelectedItem; if (tappedResult != null) { if (tappedResult.ResultType == SearchResultTypes.ShowMore) { string context = ((string)tappedResult.DataContext); if (context.Equals(c_subredditShowMoreHeader)) { DoFilteredSearch(SearchResultTypes.Subreddit); } else if (context.Equals(c_postShowMoreHeader)) { DoFilteredSearch(SearchResultTypes.Post); } } else if (tappedResult.ResultType == SearchResultTypes.Subreddit) { Subreddit subreddit = (Subreddit)tappedResult.DataContext; // If is very important to not send in a upper case display name subreddit.DisplayName = subreddit.DisplayName.ToLower(); // Navigate to the subreddit Dictionary <string, object> args = new Dictionary <string, object>(); // Send the display name. args.Add(PanelManager.NAV_ARGS_SUBREDDIT_NAME, subreddit.DisplayName); m_panelManager.Navigate(typeof(SubredditPanel), subreddit.DisplayName + SortTypes.Hot, args); } else if (tappedResult.ResultType == SearchResultTypes.Post) { Post post = (Post)tappedResult.DataContext; // Navigate to the post Dictionary <string, object> args = new Dictionary <string, object>(); args.Add(PanelManager.NAV_ARGS_SUBREDDIT_NAME, post.Subreddit); args.Add(PanelManager.NAV_ARGS_FORCE_POST_ID, post.Id); // Make sure the page id is unique m_panelManager.Navigate(typeof(FlipViewPanel), post.Subreddit + SortTypes.Hot + post.Id, args); } // #todo user } // Reset the list ui_searchResults.SelectedIndex = -1; }
internal Tuple <SkillResponse, CurrentSession> previousPost(CurrentSession cs) { SkillResponse response; if (cs == null) { response = Function.MakeSkillResponse($"{NO_SUBREDDIT_SELECTED} {NO_SUBREDDIT_SELECTED_REPROMPT}", false, NO_SUBREDDIT_SELECTED_REPROMPT); } else { var backSubredditTask = reddit.SearchSubreddits(cs.subreddit).First(); backSubredditTask.Wait(); Subreddit backSubreddit = backSubredditTask.Result; log.LogLine($"BackSubreddit Selected: {backSubreddit}"); String backIntro; if (cs.postNumber > 1) { cs.postNumber--; backIntro = "Previous Post."; } else { cs.postNumber = 1; backIntro = "Can't go back any further."; } Task <Post> backPostTask = backSubreddit.GetPosts(cs.postNumber).Last(); Post backPost = backPostTask.Result; log.LogLine($"Post retrieved: {backPost}"); cs.selfText = backPost.SelfText; cs.title = backPost.Title; cs.inTitleMode = true; cs.url = backPost.Url.ToString(); List <IDirective> directives = getImageResponseIfUrlLeadsToImage(cs.url, cs.title); String speechResponse = $"{backIntro} {cs.title}."; if (directives != null) { response = Function.MakeSkillResponseWithDirectives(speechResponse, false, directives, BROWSING_REPROMPT_TEXT); } else { response = Function.MakeSkillResponse(speechResponse, false, BROWSING_REPROMPT_TEXT); } } return(new Tuple <SkillResponse, CurrentSession>(response, cs)); }
public SubredditManager(string subreddit, RedditClient api, ETHBotDBContext context, string before, string after) { SubredditName = subreddit; API = api; NewestPost = before; OldestPost = after; ETHBotDBContext = context; Subreddit = API.Subreddit(SubredditName); // dont load info from db if we manually are managing this if (before == null && after == null) { LoadSubredditInfo(); } }
public ActionResult Create([Bind(Include = "subreddit_name,username,description")] Subreddit subreddit) { if (Session["user"] == null) { return(RedirectToAction("Login", "UsersManage")); } if (ModelState.IsValid) { db.Subreddits.Add(subreddit); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.username = new SelectList(db.Users, "username", "gender", subreddit.username); return(View(subreddit)); }
public async Task <IList <Post> > GetPostsAsync(Subreddit subreddit) { IList <Post> threads = null; var content = await RestApi.GetRequestAsync(BaseUriString + $"r/{subreddit.Title}/top/.json?limit=30&sort=new"); if (content == null) { return(null); } threads = DeserializePostsJson(content); return(threads); }
private static SubredditUser GetSubredditUser(Subreddit subreddit, RedditUser user) { using (var context = new MassTaggerContext()) { var subUser = context.SubredditUsers.FirstOrDefault(su => su.UserId == user.id && su.SubredditId == subreddit.id); if (subUser == null) { subUser = new SubredditUser { UserId = user.id, SubredditId = subreddit.id }; context.SubredditUsers.Add(subUser); context.SaveChanges(); } return(subUser); } }
public async Task WithUserWithCreatedAndSubscribedSubreddits_ShouldReturnTwoSubredditsCount() { var dbUser = new User(); var dbSubreddit1 = new Subreddit(); var dbSubreddit2 = new Subreddit(); dbUser.CreatedSubreddits.Add(dbSubreddit1); this.SubscribeUserToSubreddit(dbUser, dbSubreddit2); var model = await this.CallPrepareModelForCreatingAsyncWithNullSubredditId(dbUser); var selectList = model.Subreddits; var selectListItemsCount = selectList.Count(); Assert.Equal(2, selectListItemsCount); }
private static Subreddit GetSubreddit(string subName) { using (var context = new MassTaggerContext()) { var subreddit = context.Subreddits.FirstOrDefault(s => s.SubName == subName); if (subreddit == null) { subreddit = new Subreddit { SubName = subName }; context.Subreddits.Add(subreddit); context.SaveChanges(); } return(subreddit); } }
public SubredditViewModel() { SortType = new ObservableCollection <string> { "hot", "new", "top", "controversial" }; QueriedSubreddits = new ObservableCollection <string>(); CurrentSubreddit = new Subreddit("/r/all", new ObservableCollection <SubredditThread>()); SelectedThread = null; SelectedQueriedSubreddit = null; IsSubredditLoading = true; IsEndlessLoading = false; IsNotConnectedToInternet = false; _nextListing = null; }
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(); }
public ActionResult AddSubreddit(SubredditViewModel subredditViewModel) { using (var redditCloneContext = new RedditCloneContext()) { // Build a new subreddit and save it to the DB. var newSubreddit = new Subreddit { SubredditName = subredditViewModel.SubredditName, OwnerId = User.Identity.GetUserId() }; redditCloneContext.Subreddits.Add(newSubreddit); redditCloneContext.SaveChanges(); return(RedirectToAction("Detail", new { id = newSubreddit.SubredditId })); } }
private void BuildListingOption(EntityBuilder entityBuilder, Subreddit subreddit, string listing) { var linkBuilder = new LinkBuilder() .WithRel("listing") .WithRel(listing) .WithHref($"{subreddit.Url.OriginalString}{listing}") .WithTitle(listing); if (listing == _order && _since == null) { linkBuilder .WithClass("active"); } entityBuilder .WithLink(linkBuilder); }
private void BuildListingDuration(EntityBuilder entityBuilder, Subreddit subreddit, string listing, string duration, string durataionText) { var linkBuilder = new LinkBuilder() .WithRel("listing.time") .WithRel(listing) .WithHref($"{subreddit.Url.OriginalString}{listing}/?sort={listing}&t={duration}") .WithTitle(durataionText); if (duration == _since) { linkBuilder .WithClass("active"); } entityBuilder .WithLink(linkBuilder); }
private static EmbedBuilder ParseEmbed(Post post, Subreddit subreddit, IGuild guild) { var htmlCode = WebHelper.GetSourceCode(post.Shortlink); var metaInfo = WebHelper.GetMetaInfoFromHtml(htmlCode); //var siteName = metaInfo.FirstOrDefault(e => e.Name.Equals("og:site_name", StringComparison.CurrentCultureIgnoreCase))?.Value; var title = metaInfo.FirstOrDefault(e => e.Name.Equals("title", StringComparison.CurrentCultureIgnoreCase))?.Value ?? metaInfo.FirstOrDefault(e => e.Name.Equals("og:title", StringComparison.CurrentCultureIgnoreCase))?.Value ?? WebHelper.GetTitleFromHtml(htmlCode); var description = metaInfo.FirstOrDefault(e => e.Name.Equals("description", StringComparison.CurrentCultureIgnoreCase))?.Value ?? metaInfo.FirstOrDefault(e => e.Name.Equals("og:description", StringComparison.CurrentCultureIgnoreCase))?.Value ?? ""; var image = metaInfo.FirstOrDefault(e => e.Name.Equals("og:image", StringComparison.CurrentCultureIgnoreCase))?.Value; var linkHtmlCode = WebHelper.GetSourceCode(post.Url.ToString()); var linkMeta = WebHelper.GetMetaInfoFromHtml(linkHtmlCode); var linkTitle = linkMeta.FirstOrDefault(e => e.Name.Equals("title", StringComparison.CurrentCultureIgnoreCase))?.Value ?? linkMeta.FirstOrDefault(e => e.Name.Equals("og:title", StringComparison.CurrentCultureIgnoreCase))?.Value ?? WebHelper.GetTitleFromHtml(linkHtmlCode); var linkDescription = linkMeta.FirstOrDefault(e => e.Name.Equals("description", StringComparison.CurrentCultureIgnoreCase))?.Value ?? linkMeta.FirstOrDefault(e => e.Name.Equals("og:description", StringComparison.CurrentCultureIgnoreCase))?.Value ?? ""; var linkImage = linkMeta.FirstOrDefault(e => e.Name.Equals("og:image", StringComparison.CurrentCultureIgnoreCase))?.Value; var date = post.CreatedUTC; return(new EmbedBuilder() .WithAuthor(new EmbedAuthorBuilder() .WithName(WebUtility.HtmlDecode(title)) //.WithIconUrl("https://www.redditstatic.com/favicon.ico") .WithIconUrl("https://www.redditstatic.com/icon-touch.png") .WithUrl(post.Shortlink) ) .WithTitle(post.Permalink.Equals(post.Url.LocalPath) ? null : WebUtility.HtmlDecode(linkTitle)) .WithThumbnailUrl( WebHelper.IsValidWebsite(post.Thumbnail?.ToString()) ? post.Thumbnail.ToString() : image ) .WithDescription(WebUtility.HtmlDecode(description)) .WithFooter(new EmbedFooterBuilder() .WithText($"⏰ posted at {date:dddd, MMMM} {date.Day.Ordinal()} {date:yyyy HH:mm}") ) .WithRssColour(guild) .WithUrl(post.Url.ToString())); }
public async Task WithModelWithSelectedSubredditId_ShouldReturnTrue() { var unitOfWork = this.GetRedditCloneUnitOfWork(); var dbUser = new User(); var dbSubreddit = new Subreddit(); this.AddUserToDatabase(unitOfWork, dbUser); this.AddSubredditToDatabase(unitOfWork, dbSubreddit); var model = new PostCreationBindingModel() { SelectedSubredditId = dbSubreddit.Id }; var result = await this.CallCreatePostAsync(unitOfWork, model, dbUser.Id); Assert.True(result); }
public ActionResult Create(Submission submission) { if (ModelState.IsValid) { int subredditID = (int)Session["subredditID"]; submission.SubredditID = subredditID; submission.Username = User.Identity.Name; Subreddit subreddit = db.Subreddits.Include("Submissions").Single(s => s.SubredditID == subredditID); submission.Subreddit = subreddit; db.Submissions.Add(submission); subreddit.Submissions.Add(submission); db.Entry(subreddit).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Details", new { id = submission.SubmissionID })); } return(View(submission)); }
private void ls(Subreddit dir) { var posts = sub.New.GetEnumerator(100); while (posts.MoveNext()) { if (!RedditFSUtils.isDirectory(posts.Current)) { Console.WriteLine("\t" + posts.Current.Title); } else { Console.BackgroundColor = ConsoleColor.Blue; Console.WriteLine("\t" + posts.Current.Title); Console.ResetColor(); } } }
/// <summary> /// Gets the links from a specific subreddit from Reddit /// </summary> /// <param name="target"></param> /// <param name="parameters"></param> /// <returns></returns> public async Task <Tuple <List <Link>, string> > GetHot(Subreddit target, string parameters) { List <Link> links = new List <Link>(); string url = (target.id == null) ? "/hot" : target.url + "hot"; url = (parameters.Equals("")) ? url : url + "?" + parameters; RestClient listings_request = new RestClient(url, state.access_token); string result = await listings_request.MakeRequest(parameters); LinkTree link_tree = JsonConvert.DeserializeObject <LinkTree>(result); foreach (LinkChild link in link_tree.data.children) { links.Add(link.data); } return(new Tuple <List <Link>, string>(links, link_tree.data.after)); }
public ActionResult Index() { var reddit = new Reddit(); Subreddit subreddit = reddit.GetSubreddit("programming"); Listing <Post> posts = subreddit.GetTop(FromTime.Day); var vm = new RedditViewModel(); vm.Posts = posts.Take(10).Select(p => new RedditPost { AuthorName = p.AuthorName, Score = p.Score, Title = p.Title, Url = p.Url.AbsoluteUri, TopComment = p.Comments.OrderByDescending(c => c.Score).First().Body }); return(View(vm)); }
/// <summary> /// Gets the top 5 posts from a subreddit /// /// Excludes stickied posts. /// </summary> /// <param name="targetSubreddit">Name of the subreddit to get the posts from</param> /// <returns>A list of the top 5 posts</returns> public List <Post> GetTopPosts(string targetSubreddit, int numOfPosts) { List <Post> posts = new List <Post>(); Subreddit subreddit = reddit.GetSubreddit("/r/" + targetSubreddit); foreach (var post in subreddit.Hot.Take(numOfPosts + 2)) //Maximum of two stickies in a subreddit { if (!post.IsStickied) { posts.Add(post); } if (posts.Count > numOfPosts - 1) //If we get 5 posts break { break; } } return(posts); //TODO: Change this }
//Overriden CompareTo() to sort by name public int CompareTo(Object alpha) { if (alpha == null) { throw new ArgumentNullException("argument bad"); } Subreddit rightOp = alpha as Subreddit; if (rightOp != null) { return(name.CompareTo(rightOp.name)); } else { throw new ArgumentException("argument was not a name."); } }
public async Task <string> PostUrl(string title, string url, string subreddit) { PrepareClient(); Subreddit sub = await RedditApi.GetSubredditAsync(subreddit); try { Post post = await sub.SubmitPostAsync(title, url); return(new Uri(new Uri("https://reddit.com/"), post.Permalink).ToString()); } catch (Exception e) { System.Diagnostics.Debug.WriteLine("reddit post fail: " + e.ToString()); throw e; } }
public async Task PostDankMeme(EduardoContext context) { Subreddit subreddit = await _reddit.GetSubredditAsync("dankmemes"); Listing <Post> postListing = subreddit.GetPosts(Subreddit.Sort.Hot, 100); List <Post> posts = new List <Post>(100); await postListing.ForEachAsync(post => { posts.Add(post); }); Post randomPost = posts[_rng.Next(0, posts.Count)]; using Stream stream = await NetworkHelper.GetStreamAsync(randomPost.Url.AbsoluteUri); await context.Channel.SendFileAsync(stream, $"{randomPost.Title}.png"); }
public async Task BossFight() { using (this.Context.Channel.EnterTypingState()) { IUserMessage introMessage = await this.ReplyAsync("Wild boss appears! *cue boss music*"); BotWebAgent webAgent = new BotWebAgent(Globals.Settings.RedditUsername, Globals.Settings.RedditPass, Globals.Settings.RedditClientID, Globals.Settings.RedditSecret, "https://github.com/JordanZeotni/CSharpDewott"); Reddit reddit = new Reddit(webAgent, false); Subreddit subreddit = reddit.GetSubreddit("/r/Bossfight/"); Post selectedPost = subreddit.GetTop(FromTime.All).Where(e => !e.NSFW).ToList()[Globals.Random.Next(0, subreddit.Posts.Count(e => !e.NSFW))]; Regex linkParser = new Regex(@"\b(?:https?://|www\.)\S+\b", RegexOptions.Compiled | RegexOptions.IgnoreCase); string imageLink = selectedPost.Url.ToString(); if (imageLink.ToLower().Contains("imgur")) { ImgurClient client = new ImgurClient(Globals.Settings.ImgurClientId); ImageEndpoint endpoint = new ImageEndpoint(client); imageLink = (await endpoint.GetImageAsync(Regex.Replace(Regex.Replace(imageLink, @".+imgur\.com/", string.Empty), @"\..+", string.Empty))).Link; } EmbedBuilder builder = new EmbedBuilder { Author = new EmbedAuthorBuilder { Name = selectedPost.Title, Url = selectedPost.Shortlink }, ImageUrl = imageLink, Footer = new EmbedFooterBuilder { Text = $"Author: {selectedPost.Author.Name}", IconUrl = "https://media.glassdoor.com/sqll/796358/reddit-squarelogo-1490630845152.png" } }; builder.WithColor(Color.OrangeRed); await introMessage.DeleteAsync(); await this.ReplyAsync(string.Empty, false, builder.Build()); } }
/// <summary> /// Fired when we should show a subreddit. /// </summary> /// <param name="subreddit"></param> public void SetSubreddit(IPanelHost host, Subreddit subreddit) { // Capture host m_host = host; // Make sure we don't already have it. if (m_currentSubreddit != null && m_currentSubreddit.Id.Equals(subreddit.Id)) { // Update the buttons SetSubButton(); SetSearchButton(); SetPinButton(); // Scroll the scroller to the top ui_contentRoot.ChangeView(null, 0, null, true); return; } // Set the current subreddit m_currentSubreddit = subreddit; // Set the title ui_titleTextBlock.Text = m_currentSubreddit.DisplayName; // Set the subs, if the value doesn't exist or the subreddit is fake make it "many" if (m_currentSubreddit.SubscriberCount.HasValue && !m_currentSubreddit.IsArtifical) { ui_subscribersTextBlock.Text = String.Format("{0:N0}", m_currentSubreddit.SubscriberCount) + " subscribers"; } else { ui_subscribersTextBlock.Text = "many subscribers"; } // Set the subscribe button SetSubButton(); SetPinButton(); SetSearchButton(); // Set the markdown SetMarkdown(); }
public async Task WithUserWithIdAndSelectedSubredditId_ShouldAddNewPostWithCorrectAuthorId() { var unitOfWork = this.GetRedditCloneUnitOfWork(); var dbUser = new User(); var dbSubreddit = new Subreddit(); this.AddUserToDatabase(unitOfWork, dbUser); this.AddSubredditToDatabase(unitOfWork, dbSubreddit); var model = new PostCreationBindingModel() { SelectedSubredditId = dbSubreddit.Id }; var result = await this.CallCreatePostAsync(unitOfWork, model, dbUser.Id); var dbPost = await this.GetPostWithByAuthorIdAsync(unitOfWork, dbUser.Id); Assert.Equal(dbPost.AuthorId, dbUser.Id); }
public void post(Subreddit subreddit) { reader = XmlReader.Create(URL); SyndicationFeed feed = SyndicationFeed.Load(reader); reader.Close(); foreach (SyndicationItem item in feed.Items) { if(item.Title.Text == lastPost.Title.Text) { break; } else { try { postItem(item, subreddit); } catch (Exception) { } } } }
private static IEnumerable<Post> GetOrCreateDailyPosts(Reddit reddit, Subreddit subreddit, AuthenticatedUser user, int year, int month) { var firstDateOfMonth = new DateTime(year, month, 1); var monthName = firstDateOfMonth.ToString("MMMM"); var createdPost = false; var dailyPostDate = firstDateOfMonth; var userPosts = user.Posts.ToList(); while (dailyPostDate.Month == month) { var dailyPostTitle = string.Format(DailyPostTitleFormat, year, monthName, dailyPostDate.Day); var dailyPosts = userPosts.Where(p => p.Title == dailyPostTitle).OrderByDescending(p => p.Created); if (dailyPosts.Any()) { if (dailyPosts.Count() > 1) reddit.ComposePrivateMessage("Multiple daily posts found", "Multiple posts found for " + dailyPostDate.ToShortDateString() + " post." + Environment.NewLine + string.Join(Environment.NewLine, dailyPosts.Select(p => p.Shortlink)), SubredditName); yield return dailyPosts.First(); } else { // Create the post for the day. var post = subreddit.SubmitTextPost(dailyPostTitle, string.Format(DailyPostDescription, dailyPostDate.ToLongDateString())); CreateDailyEvents(post, dailyPostDate.Year, dailyPostDate.Month, dailyPostDate.Day); yield return post; createdPost = true; Thread.Sleep(10000); // Wait 10 seconds before creating another post } dailyPostDate = dailyPostDate.AddDays(1); } if (createdPost) reddit.ComposePrivateMessage("New month worth of posts created", "Daily posts were created for " + monthName + ".", SubredditName); }
public SubredditSettings(Reddit reddit, Subreddit subreddit, IWebAgent webAgent) { Subreddit = subreddit; Reddit = reddit; WebAgent = webAgent; // Default settings, for use when reduced information is given AllowAsDefault = true; Domain = null; Sidebar = string.Empty; Language = "en"; Title = Subreddit.DisplayName; WikiEditKarma = 100; WikiEditAge = 10; UseDomainCss = false; UseDomainSidebar = false; HeaderHoverText = string.Empty; NSFW = false; PublicDescription = string.Empty; WikiEditMode = WikiEditMode.None; SubredditType = SubredditType.Public; ShowThumbnails = true; ContentOptions = ContentOptions.All; }
private void SubmitPostToSubreddit(Post post, Subreddit subreddit) { var redditIntegration = post.Integration.Reddit; var postSubmission = redditIntegration.GetPostSubmissionForSubreddit(subreddit.Name) ?? new PostSubmission() { Subreddit = subreddit.Name }; if (postSubmission.IsManualSubmissionPending) { HandleManualSubmission(subreddit, post); return; } if (postSubmission.ShouldTrySubmit == false) return; _log.Info($"Submitting \"{post.Title}\" to /r/{subreddit.Name}."); try { var redditPost = subreddit.SubmitPost(HttpUtility.HtmlDecode(post.Title), PostHelper.Url(post)); if (redditPost == null) { throw new Exception($"Got null from reddit submit for {post.Id}"); } postSubmission.Status = SubmissionStatus.Submitted; _log.Info( $"Post \"{post.Title}\" with ID {post.Id} has been successfully submitted to /r/{subreddit.Name} with permalink {redditPost.Permalink}."); } catch (DuplicateLinkException duplicateLinkException) { _log.InfoException($"Link to post \"{post.Title}\" with ID {post.Id} already submitted to Reddit.", duplicateLinkException); postSubmission.Status = SubmissionStatus.Submitted; } catch (CaptchaFailedException) { postSubmission.Status = SubmissionStatus.CaptchaFailure; } catch (Exception exception) { _log.ErrorException($"Error submitting post \"{post.Title}\" with ID {post.Id} to /r/{subreddit.Name}", exception); postSubmission.Status = SubmissionStatus.UnknownFailure; } redditIntegration.RegisterPostSubmission(postSubmission); NotifyOnFailure(post, postSubmission); }
protected internal Wiki(Reddit reddit, Subreddit subreddit, IWebAgent webAgent) { Reddit = reddit; Subreddit = subreddit; WebAgent = webAgent; }
private void createMainList(ListView list, Subreddit sub, List<Post> posts) { list.View = View.Details; list.Columns.Add("Title", -2, HorizontalAlignment.Left); list.Columns.Add("Subreddit", -2, HorizontalAlignment.Left); list.Columns.Add("Score", -2, HorizontalAlignment.Left); list.Columns[0].Width = (list.Width / 100) * 90; list.Columns[1].AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize); list.Columns[2].AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize); foreach (var post in sub.Hot.Take(15)) { posts.Add(post); list.Items.Add(new ListViewItem(new[] { post.Title, post.SubredditName, post.Score.ToString() })); } }
private void updateListviewWithRandomSubreddit(ListView view, ref Subreddit sub, ref List<Post> posts, TextBox textBox, Label label) { posts.Clear(); view.Items.Clear(); sub = reddit.GetSubreddit("/r/random"); foreach (var post in sub.Hot.Take(15)) { posts.Add(post); view.Items.Add(new ListViewItem(new[] { post.Title, post.Score.ToString() })); } label.Text = "/r/" + sub.Name; textBox.Clear(); }
private bool parseInput() { bool result = true; if (!Int32.TryParse(intervalTextBox.Text, out interval) || interval <= 0) { intervalTextBox.BackColor = Color.Red; result = false; } else { timer.Interval = interval * 1000; intervalTextBox.BackColor = Color.White; } if (usernameTextBox.Text != String.Empty && passwordTextBox.Text != String.Empty) { try { reddit.LogIn(usernameTextBox.Text, passwordTextBox.Text); usernameTextBox.BackColor = Color.White; passwordTextBox.BackColor = Color.White; } catch { usernameTextBox.BackColor = Color.Red; passwordTextBox.BackColor = Color.Red; MessageBox.Show("Login Failed"); result = false; } } else { result = false; } if (!subredditTextBox.Text.StartsWith("/r/")) { subredditTextBox.Text = "/r/" + subredditTextBox.Text; } else { try { subreddit = reddit.GetSubreddit(subredditTextBox.Text); subredditTextBox.BackColor = Color.White; } catch { subredditTextBox.BackColor = Color.Red; result = false; } } return result; }
/// <summary> /// Initializes a new instance of the ProcessNewPosts class. /// </summary> /// <param name="reddit">Reddit API instance</param> /// <param name="sub">Target subreddit</param> public ProcessNewPosts(Reddit _reddit, Subreddit _sub) { reddit = _reddit; sub = _sub; }
public SubredditStyle(Reddit reddit, Subreddit subreddit, IWebAgent webAgent) { Reddit = reddit; Subreddit = subreddit; WebAgent = webAgent; }
private void createSideList(ListView list, Subreddit sub, List<Post> posts, Label label) { list.View = View.Details; label.Text = "/r/" + sub.Name; list.Columns.Add("Title", -2, HorizontalAlignment.Left); list.Columns.Add("Score", -2, HorizontalAlignment.Left); list.Columns[0].Width = (list.Width / 9) * 8; list.Columns[1].AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize); foreach (var post in sub.Hot.Take(15)) { posts.Add(post); list.Items.Add(new ListViewItem(new[] { post.Title, post.Score.ToString() })); } }
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."); } }
private void refreshListWithNewestPosts(ListView view, Subreddit sub, ref List<Post> posts) { view.Items.Clear(); posts.Clear(); Debug.WriteLine(sub); foreach (var post in sub.Hot.Take(15)) { posts.Add(post); if (sub.ToString() == "/r/Front Page") { view.Items.Add(new ListViewItem(new[] { post.Title, post.SubredditName, post.Score.ToString() })); } else { view.Items.Add(new ListViewItem(new[] { post.Title, post.Score.ToString() })); } } updateStatusBarLabels(); }
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { var args = (ScriptArgs)e.Argument; try { if (!signedin) { try { wallpapers = new Reddit(args.Username, args.Password).GetSubreddit("wallpapers"); signedin = true; } catch (AuthenticationException) { e.Result = "Bad username/password combination."; return; } } string description = "This image was uploaded using Paperwallz by /u/foxneZz. OP: /u/" + args.Username; Imgur.Image image; if (args.IsUrl) { args.File = Wallhaven(args.File); image = imgur.Upload(args.File, args.Title, description); } else { try { image = imgur.Upload(new Bitmap(args.File), args.Title, description); } catch (WebException) { e.Result = "The image is too big or has bad format."; return; } } int i = 0; while (true) { if (i == 5) { e.Result = "I can't post your wallpaper. I don't know why :("; return; } try { wallpapers.SubmitPost(args.Title + " [" + image.Width + "×" + image.Height + "]", image.Link.ToString()); break; } catch (WebException) { i++; } } e.Result = "Noice"; } catch (Exception ex) { e.Result = "Exception: " + ex + "\nMessage: " + ex.Message + "\nSource: " + ex.Source; } }
private void postItem(SyndicationItem item, Subreddit subreddit) { subreddit.SubmitPost(item.Title.Text, item.Links.ElementAt(0).Uri.OriginalString); }
public SubredditSettings(Subreddit subreddit, Reddit reddit, JObject json, IWebAgent webAgent) : this(reddit, subreddit, webAgent) { var data = json["data"]; AllowAsDefault = data["default_set"].ValueOrDefault<bool>(); Domain = data["domain"].ValueOrDefault<string>(); Sidebar = HttpUtility.HtmlDecode(data["description"].ValueOrDefault<string>() ?? string.Empty); Language = data["language"].ValueOrDefault<string>(); Title = data["title"].ValueOrDefault<string>(); WikiEditKarma = data["wiki_edit_karma"].ValueOrDefault<int>(); UseDomainCss = data["domain_css"].ValueOrDefault<bool>(); UseDomainSidebar = data["domain_sidebar"].ValueOrDefault<bool>(); HeaderHoverText = data["header_hover_text"].ValueOrDefault<string>(); NSFW = data["over_18"].ValueOrDefault<bool>(); PublicDescription = HttpUtility.HtmlDecode(data["public_description"].ValueOrDefault<string>() ?? string.Empty); SpamFilter = new SpamFilterSettings { LinkPostStrength = GetSpamFilterStrength(data["spam_links"].ValueOrDefault<string>()), SelfPostStrength = GetSpamFilterStrength(data["spam_selfposts"].ValueOrDefault<string>()), CommentStrength = GetSpamFilterStrength(data["spam_comments"].ValueOrDefault<string>()) }; if (data["wikimode"] != null) { var wikiMode = data["wikimode"].ValueOrDefault<string>(); switch (wikiMode) { case "disabled": WikiEditMode = WikiEditMode.None; break; case "modonly": WikiEditMode = WikiEditMode.Moderators; break; case "anyone": WikiEditMode = WikiEditMode.All; break; } } if (data["subreddit_type"] != null) { var type = data["subreddit_type"].ValueOrDefault<string>(); switch (type) { case "public": SubredditType = SubredditType.Public; break; case "private": SubredditType = SubredditType.Private; break; case "restricted": SubredditType = SubredditType.Restricted; break; } } ShowThumbnails = data["show_media"].ValueOrDefault<bool>(); WikiEditAge = data["wiki_edit_age"].ValueOrDefault<int>(); if (data["content_options"] != null) { var contentOptions = data["content_options"].ValueOrDefault<string>(); switch (contentOptions) { case "any": ContentOptions = ContentOptions.All; break; case "link": ContentOptions = ContentOptions.LinkOnly; break; case "self": ContentOptions = ContentOptions.SelfOnly; break; } } }
static Subreddit GetSubreddit(string subreddit) { try { WebClient wc = new WebClient(); StreamReader sr = new StreamReader(wc.OpenRead("http://reddit.com/r/" + subreddit + "/about.json")); string data = sr.ReadToEnd(); sr.Close(); JObject json = JObject.Parse(data); Subreddit reddit = new Subreddit(); reddit.Readers = json["data"]["subscribers"].Value<int>(); reddit.Name = json["data"]["display_name"].Value<string>(); reddit.NSFW = json["data"]["over18"].Value<bool>(); return reddit; } catch { } return null; }
public void login(string username, string password) { user = reddit.LogIn(username, password); subreddit = reddit.GetSubreddit("/r/Dota2"); }
private void HandleManualSubmission(Subreddit subreddit, Post post) { _log.Info($"Post was manually submitted \"{post.Title}\" to /r/{subreddit.Name}. Verifying."); var postUrl = PostHelper.Url(post); var posts = subreddit.Search($"url:{postUrl}"); var postSubmission = post.Integration.Reddit.GetPostSubmissionForSubreddit(subreddit.Name); if (posts.Any()) { _log.Info($"Post \"{post.Title}\" found in /r/{subreddit.Name}."); postSubmission.Status = SubmissionStatus.Submitted; return; } postSubmission.Attempts++; _log.Warn($"Post \"{post.Title}\" not found in /r/{subreddit.Name}."); if (postSubmission.Attempts >= 3) { postSubmission.Status = SubmissionStatus.ManualSubmissionFailure; postSubmission.Attempts = 0; } }
private void updateListviewWithNewSubreddit(ListView view, ref Subreddit sub, ref List<Post> posts, TextBox textBox, Label label, string defaultSub = "programming") { try { posts.Clear(); view.Items.Clear(); sub = reddit.GetSubreddit("/r/" + textBox.Text); foreach (var post in sub.Hot.Take(15)) { posts.Add(post); view.Items.Add(new ListViewItem(new[] { post.Title, post.Score.ToString() })); } label.Text = "/r/" + sub.Name; textBox.Clear(); } catch (Exception ex) { posts.Clear(); view.Items.Clear(); sub = reddit.GetSubreddit("/r/" + defaultSub); foreach (var post in sub.Hot.Take(15)) { posts.Add(post); view.Items.Add(new ListViewItem(new[] { post.Title, post.Score.ToString() })); } label.Text = "/r/" + sub.Name; textBox.Clear(); MessageBox.Show(ex.ToString(), "List update failed", MessageBoxButtons.OK, MessageBoxIcon.Error); } }