private IEnumerable <TeamEntry> FindTeamComments(string thread, Reddit reddit) { var teams = new List <TeamEntry>(); Post post = null; try { post = reddit.GetPost(thread.GetThreadUri()); } catch { // ... eat it } if (post != null) { teams.AddRange(GetTeamsFromComment(_thread.Name, _thread.StageId, post.AuthorName, post.SelfText, post.Shortlink)); var comments = post.Comments; foreach (var comment in comments) { teams.AddRange(GetTeamsFromComment(_thread.Name, _thread.StageId, comment.AuthorName, comment.Body, comment.Shortlink)); } } return(teams); }
/// <summary> /// Edits the thread designated in the "thread_uri" field from settings.txt. /// </summary> /// <param name="content">New text to post.</param> /// <returns>Returns <c>true</c> when the post is successfully updated.</returns> internal bool PostUpdate(string content) { // Init Reddit class with bearer token. var reddit = new Reddit(_bearerToken); reddit.InitOrUpdateUser(); // Verify user is authenticated and valid. if (reddit.User == null) { throw new AuthenticationException("User not authenticated."); } // Grab the post from settings.txt, and update the content. var post = reddit.GetPost(_threadUri); try { post.EditText(content); } catch (Exception e) { throw new InvalidOperationException("An error occurred while posting to Reddit,", e); } return(true); }
public void Comment(Dto.Post postDto, string message) { IsConnected(); var post = _client.GetPost(postDto.Url); post.Comment(message); }
/// <summary> /// Youtube upload complete event /// </summary> /// <param name="video">Youtube video</param> /// <param name="postId">Reddit post id that the link was taken from</param> void videosInsertRequest_ResponseReceived(Video video, string postId) { mLog.Write(Log.LogLevel.Success, $"Video id {video.Id} was successfully uploaded!"); /*Upload was successful, so now we'll find the reddit post that the video was * taken from and submit a comment containing the youtube link*/ Post redditPost = null; for (int i = 0; i < 5; i++) { redditPost = mReddit.GetPost(new Uri($"https://www.reddit.com/{postId}/")); if (redditPost != null) { redditPost.Comment(Functions.FormatComment(video.Id)); mLog.Write(Log.LogLevel.Success, $"Comment posted to thread {postId}"); break; } Thread.Sleep(500); } }
public Task StartAsync(CancellationToken cancellationToken) { // Populate the ledger with existing data using (var dbContext = new MemeEconomyContext(_config)) { dbContext.Opportunities .Include(q => q.Investments) .Where(q => q.Timestamp > DateTime.UtcNow.AddDays(-1)) .ToList() .ForEach(q => _ledger.AddOpportunity(q)); } _memeInvestorBot = _reddit.GetUser("MemeInvestor_bot"); _ = Task.Run(() => { foreach (var comment in _memeInvestorBot.Comments.GetListingStream()) { try { var match = _checkInvestment.Match(comment.Body); var postId = comment.LinkId.Split('_')[1]; //Guid opportunityId = Guid.Empty; using (var store = new MemeEconomyContext(_config)) { if (comment.Body.Contains("**INVESTMENTS GO HERE - ONLY DIRECT REPLIES TO ME WILL BE PROCESSED**")) { var opportunity = new Opportunity { Id = Guid.NewGuid(), Title = comment.LinkTitle, Timestamp = comment.Created.UtcDateTime, PostId = postId, MemeUri = _reddit.GetPost(new Uri(comment.Shortlink)).Url.ToString() }; _ledger.AddOpportunity(opportunity); Program.Opportunities.OnNext(opportunity); store.Opportunities.Add(opportunity); store.SaveChanges(); } else if (match.Success) { var opportunityId = store .Opportunities ?.SingleOrDefault(q => q.PostId == postId) ?.Id ?? Guid.Empty; if (opportunityId == Guid.Empty) { var opportunity = new Opportunity { Id = Guid.NewGuid(), Title = comment.LinkTitle, Timestamp = comment.Created.UtcDateTime, PostId = postId, MemeUri = _reddit.GetPost(new Uri(comment.Shortlink)).Url.ToString() }; _ledger.AddOpportunity(opportunity); store.Opportunities.Add(opportunity); store.SaveChanges(); opportunityId = opportunity.Id; } var investment = new Investment { Id = Guid.NewGuid(), OpportunityId = opportunityId, Timestamp = comment.Created.UtcDateTime, Amount = Convert.ToInt64(match.Groups[1].Value.Replace(",", "")), Upvotes = Convert.ToInt32(match.Groups[2].Value.Replace(",", "")) }; _ledger.AddTransaction(investment); Program.Investments.OnNext(investment); store.Investments.Add(investment); store.SaveChanges(); } } } catch (Exception) { } } }, cancellationToken); return(Task.CompletedTask); }
public RedditSharp.Things.Post GetPost(Uri uri) { return(reddit.GetPost(uri)); }
private void button1_Click(object sender, EventArgs e) { DisplayTextbox displayTextBox = new DisplayTextbox(textBox2); displayTextBox.Clear(); var reddit = new Reddit(); Post giveawayPost = null; int? randomNumber = null; Regex numberPost = new Regex(@"(\d{1,6})"); try { displayTextBox.Write("Getting giveaway post..."); giveawayPost = reddit.GetPost(new Uri(textBox1.Text)); } catch (Exception ex) { displayTextBox.Write("Failed getting giveaway post", "You sure that's the right URI (alsomake sure to get the full uri from the address bar)"); return; } displayTextBox.Write("Post title: ", giveawayPost.Title, "Comment count: ", giveawayPost.CommentCount); try { displayTextBox.Write("Getting random number from random.org..."); WebRequest randomDotOrgRequest = WebRequest.Create(string.Format(RANDOM_ORG_URI, decimal.Round(randomMin.Value, 0), decimal.Round(randomMax.Value, 0))); using (WebResponse resp = randomDotOrgRequest.GetResponse()) { using (StreamReader sr = new StreamReader(resp.GetResponseStream())) { randomNumber = int.Parse(sr.ReadToEnd()); } } } catch (Exception ex) { displayTextBox.Write("Failed getting giveaway post", ex); return; } displayTextBox.Write("Random Number: ", randomNumber, "Getting winning comment...", "This might take a while..."); Dictionary <string, int> nums = giveawayPost.Comments.Where(c => c.Body != null && numberPost.IsMatch(c.Body)).ToDictionary(k => k.Shortlink, elementSelector: x => int.Parse(numberPost.Match(x.Body).Captures[0].Value)); string winningNumKey = null; int? winningNumVal = null; int? diff = null; for (int i = 0; (winningNumKey == null && winningNumVal == null) && (randomNumber + i < decimal.Round(randomMax.Value, 0) || randomNumber - i > 0); i++) { foreach (var x in nums) { if ((x.Value == randomNumber + i && randomNumber + i < decimal.Round(randomMax.Value, 0)) || (x.Value == randomNumber - i && randomNumber - i > decimal.Round(randomMin.Value, 0))) { winningNumKey = x.Key; winningNumVal = x.Value; diff = i; break; } //stop if we're out of range if (randomNumber + i > decimal.Round(randomMax.Value, 0) && randomNumber - i < decimal.Round(randomMin.Value, 0)) { break; } } } if (!string.IsNullOrEmpty(winningNumKey) && winningNumVal.HasValue) { Comment winningComment = giveawayPost.Comments.FirstOrDefault(w => w.Shortlink == winningNumKey); displayTextBox.Write("Winning comment (link): ", winningNumKey, "Winning comment (body): ", winningComment.Body, "Winning comment (commenter): ", winningComment.Author, "Diff: ", diff ); } else { displayTextBox.Write("What the heck?? not one post in the range? you sure you have that range right?"); } }
static void Main(string[] args) { /* * This bot checks if a twich streamer is online, and if this is the case, makes a sticky post * in your subreddit and eddits the sidebar to "online". Once the streamer is offline, the post * is unstickied and the sidebar updated to offline. * * The bot will also continuously update the post with viewers and streaming time. * * This program runs continuously. You can add it as a scheduled task if you want it to run in the background. * Check out the configurator class and edit it for your config. * * You must add the original RedditSharp (https://github.com/SirCmpwn/RedditSharp), which is now unmaintained, * but you can download and it from GitHub and it still works. Compile it and add the dll as a reference. * * Made by /u/Hammond-Of-Texas, F. Kupferschmid * Licensed under the MIT license. */ while (true) // Busy-waiting { try // Sometimes reddit or twicht is glitching out, so just try it at the next run. { // Connect to reddit var reddit = new Reddit(); reddit.LogIn(Configurator.BotName, Configurator.BotPassword, true); var subreddit = reddit.GetSubreddit(Configurator.SubredditName); var settings = subreddit.Settings; // Connect to twitch stream channel string twitchResponse; string url = $"https://api.twitch.tv/kraken/streams/{Configurator.TwitchChannelName}?client_id={Configurator.ClientSecret}"; using (WebResponse wr = WebRequest.Create(url).GetResponse()) using (StreamReader sr = new StreamReader(wr.GetResponseStream())) { twitchResponse = sr.ReadToEnd(); } // Get channel Info var twitchObject = JsonConvert.DeserializeObject <ChannelInfo>(twitchResponse); // Get last post by bot var lastPost = reddit.User.Posts.FirstOrDefault(); // If the bot never posted anything before, create a welcome post. Not sure if it works. if (lastPost == null) { Console.WriteLine("Creating welcome post..."); string titleName = "Hello, Im your new twich2reddit bot!"; string bodyText = "Hi,\nI will sticky a post whenever your favourite streamer is online!"; Uri id = subreddit.SubmitTextPost(titleName, bodyText).Url; var post = reddit.GetPost(id); post.SetFlair("Info", ""); post.Distinguished = VotableThing.DistinguishType.Moderator; post.Save(); return; } // Stream is offline if (twitchObject.Stream == null) { Console.WriteLine("Not streaming right now"); // Unsticky post, update text and flair as offine if (string.IsNullOrEmpty(lastPost.LinkFlairText)) { lastPost.EditText($"{Configurator.OfflinePostText}{lastPost.SelfText}"); lastPost.SetFlair($"Stream ended {DateTime.Now.ToUniversalTime():R}", ""); lastPost.StickyMode(false); lastPost.Save(); // Update sidebar if (settings.Sidebar.Contains(Configurator.OnlineText)) { Console.WriteLine("Updating sidebar to offline..."); string replace = settings.Sidebar.Replace(Configurator.OnlineText, Configurator.OfflineText); settings.Sidebar = replace; settings.UpdateSettings(); } } Console.WriteLine("Updated post to offline."); } else // Stream is online { // Assemble body text and make a new post or update the last one string streamerName = twitchObject.Stream.Channel.DisplayName; string titleName = $"{streamerName} is streaming {twitchObject.Stream.Game} right now [{twitchObject.Stream.CreatedAt.ToUniversalTime():R}]"; Console.WriteLine(titleName); string bodyText = $"#{streamerName} is streaming right now! \n\nWatch [here]({twitchObject.Stream.Channel.Url})\n\n"; bodyText += $"---\nCurrent viewers: {twitchObject.Stream.Viewers}\n\nUptime: {Math.Round((DateTime.UtcNow - twitchObject.Stream.CreatedAt.ToUniversalTime()).TotalHours, 2)} hours.\n\n"; if (lastPost.Title != titleName) { // New stream (or streamer changed game), create new post Console.WriteLine("Creating new post..."); Uri id = subreddit.SubmitTextPost(titleName, bodyText).Url; var post = reddit.GetPost(id); post.StickyMode(true); lastPost.StickyMode( false); // Unsticky old post if streamer is still streaming but changed game post.Save(); lastPost.Save(); // Update sidebare if (settings.Sidebar.Contains(Configurator.OfflineText)) { Console.WriteLine("Updating sidebar to online.."); string replace = settings.Sidebar.Replace(Configurator.OfflineText, Configurator.OnlineText); settings.Sidebar = replace; settings.UpdateSettings(); } } else { // Otherwise, update post (viewers, streaming time) Console.WriteLine("Updating post..."); lastPost.EditText(bodyText); lastPost.Save(); Console.WriteLine("Run complete."); Thread.Sleep(5000); } } } catch (Exception e) { Console.WriteLine(e); } } }