static void Main(string[] args) { var reddit = new RedditClient("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 } }
public static async Task <List <Post> > GetHot(string subredditName, int limit = 15) { try { var sub = Client.Subreddit(subredditName); List <Post> posts = null; await Task.Run(() => posts = sub.Posts.GetHot(limit: limit)); return(posts); } catch { return(null); } }
public Task SendPostMessage(SocketMessage message) { if (message.Author.IsBot) { return(Task.CompletedTask); } if (message.Channel.Name != "bot-things") { return(Task.CompletedTask); } if (message.Content.ToLower() != "!check") { return(Task.CompletedTask); } #region Watch Exchange List <Post> we = RedditHelper.CheckSubbredditByTitle(reddit.Subreddit("WatchExchange"), "Spaceview"); foreach (Post post in we) { EmbedBuilder url = new EmbedBuilder(); url.Url = $@"https://www.reddit.com{post.Permalink}"; url.Title = post.Title; message.Channel.SendMessageAsync(text: $@"Post found on /r/WatchExchange at {post.Created.ToShortTimeString()}: {post.Title}.", embed: url.Build()); } if (we.Count == 0) { message.Channel.SendMessageAsync("No Posts found on /r/WatchExchange for SpaceView."); } #endregion #region BuildAPcSales List <Post> bpc = RedditHelper.CheckSubbredditByTitle(reddit.Subreddit("Buildapcsales"), "Laptop"); foreach (Post post in bpc) { EmbedBuilder url = new EmbedBuilder(); url.Url = $@"https://www.reddit.com{post.Permalink}"; url.Title = post.Title; message.Channel.SendMessageAsync(text: $@"Post found on /r/buildapcsales at {post.Created.ToShortTimeString()}: {post.Title}.", embed: url.Build()); } if (we.Count == 0) { message.Channel.SendMessageAsync("No Posts found on /r/buildapcsales for Laptop."); } #endregion return(Task.CompletedTask); }
public UserFlairContextFactory(BerbotConnectionFactory connectionFactory) { this.connectionFactory = connectionFactory; this.auditClient = connectionFactory.CreateAuditClient(); this.modRedditClient = connectionFactory.CreateModRedditClient(); this.subreddit = modRedditClient.Subreddit(BerbotConfiguration.RedditSubredditName); }
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 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); }
private void _postToCSharpMonthlyThread(DateTime now) { var posts = _redditClient.Subreddit("CSharp").Posts.Hot; var post = posts.FirstOrDefault(p => p.Author == "AutoModerator" && p.Title.Contains($"[{now:MMMM yyyy}]") && p.Title.Contains("your side projects!")); if (post == null) { _logger.LogWarning("Could not find Thread of monthly projects on /r/CSharp"); return; } var replyText = new StringBuilder() .Append("I've been working on a Console Application that can run multiple reddit bots (now also with a discord bot) AND have the logs streamed to a web app, which you can monitor live.") .Append("The bots themselves are not that interesting but building them has been fun. It currently has 3 bots running on it and it's hosted on a Raspberry Pi") .Append("\n\n") .Append("Each bot is a BackgroundService and with a custom ILogger i send all logs via http to a site, which streams it to a client with SignalR, of course everything in .NET 5") .Append("\n\n") .Append($"The Console is hosted in Docker and auto-deployed to the pi") .Append("\n\n") .Append($"The repo is here: https://github.com/Marcel0024/RedditBots and the live logs can be viewed here: https://reddit.croes.io") .Append("\n\n") .Append($"Any feedback is welcome!") .ToString(); post.Reply(replyText); _logger.LogInformation($"Posted comment in r/{post.Subreddit} - {post.Title}"); }
private void _postToCSharpMonthlyThread(DateTime now) { var posts = _redditClient.Subreddit("CSharp").Posts.Hot; var post = posts.FirstOrDefault(p => p.Author == "AutoModerator" && p.Title.Contains($"[{now:MMMM yyyy}]") && p.Title.Contains("your side projects!")); if (post == null) { _logger.LogWarning("Could not find Thread of monthly projects on /r/CSharp"); return; } var replyText = new StringBuilder() .Append("I've been working on a Console Application that can run multiple reddit bots (now also with a discord bot) AND have the logs streamed to a web app (an angular app), which you can monitor live.") .Append("The bots themselves are not that interesting but building them has been fun. It currently has 3 bots running on it and it's hosted on a Raspberry Pi") .Append("\n\n") .Append("Each bot is a BackgroundService and with a custom ILogger i send all logs via http to a site, which streams it to a client with SignalR, of course everything in .NET 5") .Append("\n\n") .Append($"The Console is hosted in Docker and auto-deployed to the pi via Azure Pipelines") .Append("\n\n") .Append($"The logs website is deployed with the help of Bicep templates to Azure with Github Actions") .Append("\n\n") .Append($"The repo is here: https://github.com/Marcel0024/RedditBots and the live logs can be viewed here: https://redditbots.azurewebsites.net") .Append("\n\n") .Append("Things i dipped my toe in so far: A bit a of docker, Angular (still beginner), typescript, npm in it's whole, RxJs, YAML, Github Actions, Azure Devops pipelines, Reddit API, .NET Generic Host Builder, some threading issues, SignalR, how ILogger works, some Bootstrap and css stuff, localstorage, I also had to setup my Rasperry Pi as a build agent on Azure, Bicep (big one), Azure CLI, also some linux.") .Append("Most of this is just built for learning purposes, if i can only get a nice a idea for a bot....") .Append("\n\n") .Append($"Any feedback is welcome!") .ToString(); post.Reply(replyText); _logger.LogInformation($"Posted comment in r/{post.Subreddit} - {post.Title}"); }
public async Task GiveRandomMeme() { Random rand = new Random(); if (MemeList.SubredditList.Count == 0) { await Context.Channel.SendMessageAsync("No subreddits added to the list! Use !memeadd followed by a subreddit name."); return; } var randomSubreddit = MemeList.SubredditList[rand.Next(MemeList.SubredditList.Count)]; var randomMeme = r.Subreddit(randomSubreddit.subredditName).Posts.Hot[rand.Next(50)]; var memeImage = randomMeme.Listing.URL; await Context.Channel.SendMessageAsync(memeImage); }
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; }
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"); }
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 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 Plugin() { Routes = new List<Route>() { new PathRoute() { Path = "r", Handler = async () => { var posts = client.Subreddit("AskReddit").Posts.New; var uw = new PostsPage() { Version = 0.1f, Title = "r/all", Data = new Pagination<List<Post>>() { Items = (List<Post>)posts.Select((post, index) => { return new Post() { Id = post.Id, Title = post.Title, Nsfw = post.NSFW, Likes = post.UpVotes, Authors = new List<User>() { new User() { Username = post.Author, } } }; }) } }; return new UniviewResponse() { Mime = "application/uniview+json", Data = uw }; } } }; }
public Subreddit GetSubreddit(SubredditNames subredditNames) { var js = Enum.GetName(typeof(SubredditNames), subredditNames); Subreddit subreddit; subreddit = _client.Subreddit(js).About(); return(subreddit); }
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 async Task Meme(CommandContext ctx) { var r = new RedditClient(); var sub = r.Subreddit("dankmemes"); var topPost = sub.Posts.Top[0]; var PostEmbed = new DiscordEmbedBuilder { Title = string.Join(" ", topPost) }; await ctx.Channel.SendMessageAsync(embed : PostEmbed).ConfigureAwait(false); }
public async Task Meme(CommandContext ctx) { var r = new RedditClient("PlaceHolder App ID", "PlaceHolder Refresh token", "PlaceHolder App Secret"); var subreddit = r.Subreddit("memes").About(); var rnd = new Random(); var toppost = subreddit.Posts.Hot[rnd.Next(0, 100)]; var post = toppost.Listing; var ratio = toppost.UpvoteRatio.ToString(); var author = toppost.Author; await ctx.Channel.SendMessageAsync("This post has an upvote ratio of " + ratio + " and the author is" + author).ConfigureAwait(false); await ctx.Channel.SendMessageAsync(post.URL).ConfigureAwait(false); if (toppost.IsUpvoted == false && toppost.IsDownvoted == false) { await ctx.Channel.SendMessageAsync("Do you like this post? (Y/N)").ConfigureAwait(false); Thread.Sleep(20); var interactivity = ctx.Client.GetInteractivity(); var message = await interactivity.WaitForMessageAsync(x => x.Channel == ctx.Channel && x.Author == ctx.User).ConfigureAwait(false); if (message.Result.Content == "Y") { await toppost.UpvoteAsync().ConfigureAwait(false); await ctx.Channel.SendMessageAsync("Upvoting...").ConfigureAwait(false); } else if (message.Result.Content == "N") { await toppost.DownvoteAsync().ConfigureAwait(false); await ctx.Channel.SendMessageAsync("Downvoting...").ConfigureAwait(false); } else { await ctx.Channel.SendMessageAsync("Entered incorrect response, I wont do anything b-b-b-b-baka!").ConfigureAwait(false); } } else { await ctx.Channel.SendMessageAsync("Hey " + ctx.User.Mention + ", This post is already voted, No need to vote :)").ConfigureAwait(false); } }
private void _startMonitoringSubreddits() { foreach (var subredditToMonitor in _botSetting.Subreddits) { var subreddit = _redditClient.Subreddit(subredditToMonitor); subreddit.Comments.GetNew(); subreddit.Comments.MonitorNew(); subreddit.Comments.NewUpdated += C_NewCommentsUpdated; Logger.LogDebug($"Started monitoring {subredditToMonitor}"); } }
public SubRedditItem[] GetSubReddits(string[] names) { List <SubRedditItem> items = new List <SubRedditItem>(); foreach (string name in names) { Subreddit subreddit = redditClient.Subreddit(name).About(); SubRedditItem item = new SubRedditItem { Label = subreddit.Name, Name = subreddit.Title, Subreddit = subreddit }; items.Add(item); } return(items.ToArray()); }
public void GetNew() { // Gets the Reddit client and channel where to send the notification RedditClient r = new RedditClient("bt3vamB2ZuUtow", "12447532163-GfU33RHOqQK7-haad5nOcJG0j-Gn3w", "123", "12447532163-yeStxU5OITVsfhqRVOpWSXBThCRrcg"); gamesChannel = _Client.GetChannel(829403362029862922) as SocketTextChannel; //Monitors the defined subreddit var subreddit = r.Subreddit("FreeGamesOnSteam").About(); subreddit.Posts.GetNew(); subreddit.Posts.NewUpdated += C_NewPostsUpdated; subreddit.Posts.MonitorNew(2000, 1500); }
static void Main(string[] args) { var reddit = new RedditClient("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) { } }
public async Task MonitorPostsAsync() { await Task.Factory.StartNew(() => { foreach (var subreddit in Enum.GetValues(typeof(SubReddit))) { var newSubredditClient = _redditClient.Subreddit(subreddit.ToString()); newSubredditClient.Comments.GetNew(); newSubredditClient.Comments.MonitorNew(); newSubredditClient.Comments.NewUpdated += C_AddNewCommentToQueue; newSubredditClient.Posts.GetNew(); newSubredditClient.Posts.MonitorNew(); newSubredditClient.Posts.NewUpdated += C_AddNewPostToQueue; } }); }
static void Main(string[] args) { var reddit = new RedditClient("YourRedditAppID", "YourBotUserRefreshToken"); IDictionary <string, IList <Post> > Posts = new Dictionary <string, IList <Post> >(); foreach (Post post in reddit.Subreddit("all").Posts.New) { if (!Posts.ContainsKey(post.Subreddit)) { Posts.Add(post.Subreddit, new List <Post>()); } Posts[post.Subreddit].Add(post); } }
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(); } }
static void Main(string[] args) { var reddit = new RedditClient("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; }
private static async Task SeedFor(string subredditName) { var redditClient = new RedditClient(appId: _configuration["AppId"], appSecret: _configuration["AppSecret"], refreshToken: _configuration["RefreshToken"]); var subreddit = redditClient.Subreddit(subredditName); var postDatabase = new DatabaseService <Data.Post>( _configuration["ConnectionString"], databaseName: subredditName, collectionName: DatabaseConstants.PostsCollectionName); var commentDatabase = new DatabaseService <Data.Comment>( _configuration["ConnectionString"], databaseName: subredditName, collectionName: DatabaseConstants.CommentsCollectionName); var postSeedUtility = new PostSeedUtility(subreddit, postDatabase); await postSeedUtility.Execute(); var commentSeedUtility = new CommentSeedUtility(redditClient, postDatabase, commentDatabase); await commentSeedUtility.Execute(); }
static void Main(string[] args) { var reddit = new RedditClient("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 }
static void Main(string[] args) { string appId = "xxxxxxxxxxxxxxxx"; string refreshToken = "xxxxxxxxxxxxxx-xxxxxxxxxxxx"; string accessToken = "682682646623-xxxxxxxxxx-xxxxxxxxxxxxxxx"; RedditClient reddit = new RedditClient(appId: appId, refreshToken: refreshToken, accessToken: accessToken); dataAccess = new MyRedditDataAccessor(); List <Post> newPosts = new List <Post>(); List <Comment> newComments = new List <Comment>(); foreach (var s in dataAccess.GetAllSubReddits()) { var sub = reddit.Subreddit(s.Name).About(); sub.Posts.NewUpdated += C_NewPostsUpdated; sub.Posts.MonitorNew(30 * 1000); // Toggle on. foreach (var newPost in sub.Posts.GetNew()) { if (!(s.Posts.Where(p => p.Equals(newPost)).Count() > 0)) { newPosts.Add(Utility.GetPostModel(newPost)); } foreach (var newComment in newPost.Comments.GetNew()) { if (!(dataAccess.GetAllComments().Where(c => c.Equals(newComment)).Count() > 0)) { newComments.Add(Utility.GetCommentModel(newComment)); } newPost.Comments.MonitorNew(30 & 1000); // Toggle on. newPost.Comments.NewUpdated += C_NewCommentsUpdated; } } } dataAccess.AddNewPost(newPosts); dataAccess.AddComment(newComments); }
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 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"); } }