public void TestPolling() { var reddit = new RedditClient(() => new HttpClient()); var pollingClient = new RedditPollingClient(reddit, "funny", TimeSpan.FromSeconds(10), ex => { }); var resetEvent = new ManualResetEvent(false); var subscription = pollingClient.Posts.Subscribe( x => Debug.WriteLine($"New post: {x.Title}"), ex => { Debug.WriteLine($"Error while retrieving reddit posts: {ex.Message}"); resetEvent.Set(); }, () => { Debug.WriteLine("Finished retrieving posts"); resetEvent.Set(); }); pollingClient.Start(); resetEvent.WaitOne(60000); }
/// <summary> /// Create an instance of <see cref="RedditClient"/> /// </summary> /// <returns></returns> private void LoadRedditConfiguration() { Console.WriteLine("Creating Reddit Configuration"); var reddit = new RedditClient(Settings.RedditSettings.AppId, Settings.RedditSettings.RefreshToken); RedditClient = reddit; }
static void Main(string[] args) { var reddit = new RedditClient("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"); }
public void TestPolling() { var reddit = new RedditClient(() => new HttpClient()); var pollingClient = new RedditPollingClient(reddit, "funny", TimeSpan.FromSeconds(10), ex => { }); var resetEvent = new ManualResetEvent(false); var subscription = pollingClient.Posts.Subscribe( x => Debug.WriteLine($"New post: {x.Title}"), ex => { Debug.WriteLine($"Error while retrieving reddit posts: {ex.Message}"); resetEvent.Set(); }, () => { Debug.WriteLine("Finished retrieving posts"); resetEvent.Set(); }); pollingClient.Start(); resetEvent.WaitOne(60000); }
static void Main(string[] args) { var reddit = new RedditClient("YourRedditAppID", "YourBotUserRefreshToken"); // Get the number of direct replies to the top comment on the top post of r/AskReddit. --Kris int?numReplies = reddit.Subreddit("AskReddit").Posts.Top[0].Comments.Top[0].NumReplies; }
public static void Main() { System.Console.WriteLine(Assembly.GetExecutingAssembly().GetName().Name); System.Console.WriteLine(Assembly.GetExecutingAssembly().GetName().Version); System.Console.WriteLine("Press any key to stop the execution."); System.Console.WriteLine(); var client = new RedditClient( Settings.AppClientId, Settings.AppClientSecret, Settings.BotUserName, Settings.BotUserPassword, Settings.Subreddits, Settings.TriggerPhrases, Settings.Quotes, Settings.IgnoredUserNames, Settings.ApplicationName, Settings.ApplicationVersion, Settings.Ratelimit, Settings.MaxCommentAge, Settings.CommentLimit, Settings.RateComment); var tokenSource = new CancellationTokenSource(); var task = client.RunAsync(tokenSource.Token); System.Console.ReadKey(true); if (!task.IsCompleted) { System.Console.WriteLine("User cancelled execution."); tokenSource.Cancel(); task.GetAwaiter().GetResult(); } }
public SubredditService Start(ILogger logger, IConfiguration configuration, bool dryRun = false, bool processOldPosts = false) { logger.Information("Application started..."); if (dryRun) { logger.Warning("This is a DRYRUN! No actions will be taken!"); } var redditClient = new RedditClient(appId: configuration["AppId"], appSecret: configuration["AppSecret"], refreshToken: configuration["RefreshToken"]); var service = new SubredditService(logger, configuration, redditClient, subredditName: _subredditName, databaseName: _subredditName, processOldPosts: processOldPosts); foreach (var handler in GetHandlers(typeof(IPostHandler), logger, service, dryRun)) { service.PostHandlers.Add(handler); } foreach (var handler in GetHandlers(typeof(ICommentHandler), logger, service, dryRun)) { service.CommentHandlers.Add(handler); } foreach (var handler in GetHandlers(typeof(IMessageHandler), logger, service, dryRun)) { service.MessageHandlers.Add(handler); } service.SubscribeToPostFeed(); service.SubscribeToCommentFeed(); service.SubscribeToMessageFeed(); service.RegisterRepeatForCommentAndPostDataPull(); return(service); }
public SubredditService( ILogger logger, IConfiguration configuration, RedditClient redditClient, string subredditName, string databaseName, Func <string, Task> callback = null, bool processOldPosts = true) { _logger = logger; _configuration = configuration; RedditClient = redditClient; _subredditName = subredditName; _callback = callback; _processOldPosts = processOldPosts; Subreddit = redditClient.Subreddit(subredditName); Account = redditClient.Account; RedditPostDatabase = new DatabaseService <SubredditBot.Data.Post>( configuration["ConnectionString"], databaseName: databaseName, collectionName: DatabaseConstants.PostsCollectionName); RedditCommentDatabase = new DatabaseService <SubredditBot.Data.Comment>( configuration["ConnectionString"], databaseName: databaseName, collectionName: DatabaseConstants.CommentsCollectionName); SelfCommentDatabase = new DatabaseService <SelfComment>( configuration["ConnectionString"], databaseName: databaseName, collectionName: DatabaseConstants.SelfCommentsCollectionName); }
public void init() { credentials credentials; using (StreamReader stream = new StreamReader("credentials.json")) { string json = stream.ReadToEnd(); credentials = JsonConvert.DeserializeObject <credentials>(json); } CheckTools(); var r = new RedditClient(appId: Convert.ToString(credentials.appId), appSecret: Convert.ToString(credentials.appSecret), refreshToken: Convert.ToString(credentials.refreshToken)); var sub = r.Subreddit(Convert.ToString(credentials.SUBREDDIT)); Console.WriteLine("waiting for posts..."); if (credentials.Hot) { Console.WriteLine("HOT"); _ = sub.Posts.GetHot(); sub.Posts.HotUpdated += C_postsUpdated; sub.Posts.MonitorHot(); } else { Console.WriteLine("NEW"); _ = sub.Posts.GetNew(); sub.Posts.NewUpdated += C_postsUpdated; sub.Posts.MonitorNew(); } }
public async Task RunAsync() { await socketClient.LoginAsync(TokenType.Bot, ConfigManager.config.token); await socketClient.StartAsync(); await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services); RedditClient redditClient = new RedditClient( appId: ConfigManager.config.redditAppId, appSecret: ConfigManager.config.redditAppSecret, refreshToken: ConfigManager.config.redditRefreshToken); foreach (string sub in ConfigManager.config.subredditsWatched) { Subreddit subreddit = redditClient.Subreddit(sub); subreddit.Posts.GetNew(limit: 100000); subreddit.Posts.NewUpdated += NewRedditPost; subreddit.Posts.MonitorNew(monitoringDelayMs: 60000); //subreddit.Posts.MonitorNew(); } await socketClient.SetGameAsync( name : $"prefix: {ConfigManager.config.botPrefix}", streamUrl : null, type : ActivityType.Listening); await Task.Delay(-1); }
static void Main(string[] args) { var reddit = new RedditClient("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 }
public UserFlairContextFactory(BerbotConnectionFactory connectionFactory) { this.connectionFactory = connectionFactory; this.auditClient = connectionFactory.CreateAuditClient(); this.modRedditClient = connectionFactory.CreateModRedditClient(); this.subreddit = modRedditClient.Subreddit(BerbotConfiguration.RedditSubredditName); }
static async Task Main(string[] args) { IAuthenticationService authService = OauthAuthenticationService.GetAuthenticationService(); var token = await authService.Authenticate(REDDIT_USER, REDDIT_PASSWORD, REDDIT_APP_ID, REDDIT_APP_SECRET); Console.WriteLine($"Granted token: {token.token.ToString()}\nExpires At: {token.expiresAt.ToShortTimeString()}"); IRedditClient client = new RedditClient(token); var me = await client.me(); Console.WriteLine($"Begin processing for /u/{me.name}\nHas {me.link_karma} link karma, and {me.comment_karma} comment karma."); var comments = await client.comments(REDDIT_USER, null, null, 25); Console.WriteLine($"Request Success: {comments.IsSuccess}"); while (!string.IsNullOrEmpty(comments.after) && comments.children.Length != 0) { Console.WriteLine($"Processing {comments.children.Length} comments."); foreach (var comment in comments.children) { if (comment.ups < 0) { Console.WriteLine($"Comment {comment.id}, created at {comment.createdDt} has a score of {comment.score}"); } } comments = await client.comments(REDDIT_USER, null, comments.after, 25); Console.WriteLine($"Request Success: {comments.IsSuccess}"); Console.WriteLine($"After is: {comments.after}"); } }
public BaseAccount(RedditSettings options, Credentials credentials) { _client = new RedditClient(appId: credentials.AppID, accessToken: credentials.AccessToken, refreshToken: credentials.RefreshToken, userAgent: options.UserAgent); }
public override TaskStatus Run() { Info("Retrieving post history..."); Status status = Status.Success; RedditClient reddit; try { reddit = new RedditClient(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)); }
static void Main(string[] args) { var reddit = new RedditClient("YourRedditAppID", "YourBotUserRefreshToken"); Console.WriteLine("Username: "******"Cake Day: " + reddit.Account.Me.Created.ToString("D")); }
public TwitterJob(IServiceScopeFactory scopeFactory, DiscordClient dClient, RedditClient redditAPI, BloonLog bloonLog) { this.dClient = dClient; this.bloonLog = bloonLog; this.twitterService = new TwitterService(scopeFactory); this.twitterService.Authenticate(); this.redditAPI = redditAPI; }
public override TaskStatus Run() { Info("Retrieving comment history..."); WorkflowStatus status = WorkflowStatus.Success; RedditClient reddit; try { reddit = new RedditClient(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(WorkflowStatus.Error)); } try { // Retrieve the authenticated user's recent comment history. var comments = reddit.Account.Me.GetCommentHistory(sort: "new", limit: MaxResults, show: "all"); var xdoc = new XDocument(new XElement("Comments")); foreach (var comment in comments) { var xcomment = new XElement("Comment", new XAttribute("id", SecurityElement.Escape(comment.Id)), new XAttribute("subreddit", SecurityElement.Escape(comment.Subreddit)), new XAttribute("author", SecurityElement.Escape(comment.Author)), new XAttribute("upvotes", comment.UpVotes), new XAttribute("downvotes", comment.DownVotes), new XCData(comment.BodyHTML)); xdoc.Root.Add(xcomment); } var xmlPath = Path.Combine(Workflow.WorkflowTempFolder, string.Format("{0}_{1:yyyy-MM-dd-HH-mm-ss-fff}.xml", "RedditListComments", DateTime.Now)); xdoc.Save(xmlPath); Files.Add(new FileInf(xmlPath, Id)); InfoFormat("Comment history written in {0}", xmlPath); } catch (ThreadAbortException) { throw; } catch (Exception e) { ErrorFormat("An error occured while retrieving comment history: {0}", e.Message); status = WorkflowStatus.Error; } Info("Task finished."); return(new TaskStatus(status)); }
public RedditClientWrapper(IRedditClientConfiguration redditClientConfiguration) { Console.WriteLine($"Creating RedditClient..."); _redditClient = new RedditClient( redditClientConfiguration.GetAppId(), redditClientConfiguration.GetRefreshToken(), redditClientConfiguration.GetAppSecret()); Console.WriteLine($"RedditClient created for user: {_redditClient.Account.Me.Name}"); }
public HomeController(ILogger <HomeController> logger, BinanceClient binanceClient, RedditClient redditClient, ApplicationDbContext dbContext, UserManager <IdentityUser> userManager, SignInManager <IdentityUser> signInManager) { _userManager = userManager; _signInManager = signInManager; _binanceClient = binanceClient; _redditClient = redditClient; _logger = logger; _db = dbContext; }
public void PullCommentsAndPosts(int postCount = 100, int commentCount = 500) { _logger.Information($"Pulling {postCount} posts and {commentCount} comments. Interval: {_commentAndPostPullIntervalMinutes} minutes"); var redditReader = new RedditHttpsReader(subreddit: Subreddit.Name); var recentPosts = redditReader.GetRecentPosts(numPosts: postCount); foreach (var postToUpdate in recentPosts) { var updatedPost = RedditPostDatabase.Upsert(postToUpdate); // If process old posts is enabled, re-trigger the handlers for those posts if (_processOldPosts) { if (updatedPost != null && postToUpdate.Flair != updatedPost.Flair) { PostHandlers.ForEach(c => { _logger.Information($"Reprocessing post {postToUpdate.Title} from original flair: {updatedPost.Flair} to new flair: {postToUpdate.Flair}"); var postController = RedditClient.Post(updatedPost.Fullname).Info(); c.Process(postController); }); } } } var recentComments = redditReader.GetRecentComments(numComments: commentCount); RedditCommentDatabase.Upsert(recentComments); var tries = 0; var count = 0; var oldestComment = recentComments.First(); while (count < commentCount && tries < 10) { var newComments = new List <SubredditBot.Data.Comment>(); foreach (var comment in recentComments) { if (comment.CreateDate < oldestComment.CreateDate) { oldestComment = comment; } newComments.Add(comment); count++; } RedditCommentDatabase.Upsert(newComments); recentComments = redditReader.GetRecentComments(numComments: commentCount, after: oldestComment.Fullname); tries++; } _logger.Information($"Finished pulling posts and comments."); }
private bool CreateRedditClient() { if (!(RedditClient is null)) { return(true); } try { string configPath = _configuration.GetConnectionString("PythonScriptDirectory") + @"\Config.json"; string id = ""; string secretId = ""; string userAgent = ""; string refreshToken = ""; using (StreamReader file = System.IO.File.OpenText(configPath)) { using (JsonTextReader reader = new JsonTextReader(file)) { JObject o2 = (JObject)JToken.ReadFrom(reader); foreach (var element in o2) { switch (element.Key) { case "Id": id = element.Value.ToString(); break; case "Secret": secretId = element.Value.ToString(); break; case "User Agent": userAgent = element.Value.ToString(); break; case "Refresh Token": refreshToken = element.Value.ToString(); break; } } } } RedditClient = new RedditClient(appId: id, appSecret: secretId, refreshToken: refreshToken, userAgent: userAgent); } catch (Exception e) { Utility.Print(e.Message); return(false); } return(true); }
public RedditService() { var appSettings = ConfigurationManager.AppSettings; string app_id = appSettings["app_id"]; string app_secret = appSettings["app_secret"]; string refresh_token = appSettings["refresh_token"]; subreddits = appSettings["subreddits"]; redditClient = new RedditClient(app_id, refresh_token, app_secret); }
public MainPageViewModel() { //var token = AuthorizeUser("r0R_pygEcI5UDg"); var reddit = new RedditClient("r0R_pygEcI5UDg", Guid.NewGuid().ToString()); // Get info on another subreddit. var askReddit = reddit.Subreddit("AskReddit").About(); // Get the top post from a subreddit. ListTop = askReddit.Posts.Top.Take(50); }
public RedditMonitoring( IRabbitPublisher rabbitManager, IServiceConfigurations serviceConfigurations) { _rabbitPublisher = rabbitManager; _serviceConfigurations = serviceConfigurations; _redditClient = new RedditClient( _serviceConfigurations.RedditAppId, _serviceConfigurations.RedditOAuthKey); }
public void GetSports_ShouldNot_EmptyCollection_IfHttpStatusNotOk() { HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.InternalServerError); var httpMessageHandler = new HttpMessageHandlerMock(responseMessage); RedditClient redditCleint = new RedditClient(httpMessageHandler); var redditResponse = redditCleint.GetSports().Result.ToList(); Assert.IsInstanceOfType(redditResponse, typeof(List <SportPost>)); Assert.IsTrue(redditResponse.Count == 0); }
private async void AddSubreddit(string subredditName) { var reddit = new RedditClient(Program.RedditAppId, Program.RedditRefreshToken, Program.RedditAppSecret); using (ETHBotDBContext context = new ETHBotDBContext()) { SubredditManager subManager = new SubredditManager(subredditName, reddit, context); Context.Channel.SendMessageAsync($"{subManager.SubredditName} was added to the list", false); // NSFW: {subManager.SubredditInfo.IsNSFW} } }
/// <summary> /// Creates a new instance of the reddit client class /// </summary> /// <param name="redditSettings"></param> /// <returns></returns> private RedditClient GetRedditClient(BotSettings redditSettings) { // Get the settings var subreddit = redditSettings.Subreddit; var upvoteThreshold = redditSettings.UpvoteThreshold; var redditClient = new RedditClient(subreddit, upvoteThreshold); return(redditClient); }
private async Task ProcessModLog() { var yt = new YouTubeService(new BaseClientService.Initializer { ApiKey = YouTubeAPIKey }); var req = yt.Videos.List("snippet"); var lastRemoval = PostRemoval.GetLastProcessedRemovalDate(Subreddit); var processedCount = 0; var modActions = RedditClient.GetSubreddit(Subreddit).GetModerationLog(ModActionType.RemoveLink).GetListing(300, 100); var newPosts = new Dictionary <string, List <UserPost> >(); foreach (var modAct in modActions) { if (modAct.TimeStamp <= lastRemoval || processedCount > 100) { break; //probably dumb and unnecessary } processedCount++; var post = RedditClient.GetThingByFullname(modAct.TargetThingFullname) as Post; var userPost = new UserPost(); userPost.ThingID = post.Id; userPost.Link = post.Url.ToString(); userPost.PostTime = post.CreatedUTC; userPost.UserName = post.AuthorName; userPost.Subreddit = Subreddit; var removal = new PostRemoval(modAct); removal.Post = userPost; var newPost = PostRemoval.AddRemoval(removal); if (newPost != null) { var ytID = YouTubeHelpers.ExtractVideoId(post.Url.ToString()); if (!string.IsNullOrEmpty(ytID)) { if (!newPosts.ContainsKey(ytID)) { newPosts.Add(ytID, new List <UserPost>()); } newPosts[ytID].Add(newPost); } } if (processedCount % 75 == 0) { await UpdateChannels(newPosts, req); newPosts.Clear(); } } await UpdateChannels(newPosts, req); }
public RedditBaseService(IOptions <RedditConfig> config, IHttpContextAccessor httpContextAccessor) { this.config = config; this.httpContextAccessor = httpContextAccessor; this.redditClient = new RedditClient( appId: this.config.Value.AppId, appSecret: this.config.Value.AppSecret, accessToken: this.LoggedInUserAccessToken ?? this.config.Value.DefaultAccessToken, refreshToken: this.LoggedInUserRefreshToken ?? this.config.Value.DefaultRefreshToken); }
public CheerfulBot( ILogger <CheerfulBot> logger, IHostEnvironment env, IOptions <MonitorSettings> monitorSettings) { _logger = logger; _env = env; _botSetting = monitorSettings.Value.Settings.Find(ms => ms.BotName == nameof(CheerfulBot)) ?? throw new ArgumentNullException("No bot settings found"); _redditClient = new RedditClient(_botSetting.AppId, _botSetting.RefreshToken, _botSetting.AppSecret); }
static void Main(string[] args) { var reader = new RedditClient(30); reader.AddSource("nsx"); reader.AddSource("acura"); reader.Next().ContinueWith(x => { foreach (var redditItem in x.Result) { Console.WriteLine("{0}:\t{1}" , (string.IsNullOrWhiteSpace(redditItem.Thumbnail)) ? "TEXT" : "IMAGE" , redditItem.Title); } }); Console.WriteLine("Please wait for async operation to complete. Press Enter to close console."); Console.ReadLine(); }
public async Task Initialize() { this.client = new RedditClient(); this.fakeHttpServer = new FakeHttpServer(); await this.fakeHttpServer.Initialize(); }
public void Cleanup() { this.client = null; this.fakeHttpServer.Cleanup(); }