예제 #1
0
        protected override async Task StartService(CancellationToken cancellationToken)
        {
            RedditCredentials credentials = await CredentialGetter.GetCredentials().ConfigureAwait(false);

            _userName = credentials.Username;

            do
            {
                try
                {
                    _webAgent = new BotWebAgent(credentials.Username, credentials.Password, credentials.ClientId,
                                                credentials.ClientSecret, credentials.RedirectUrl);
                    _webAgent.RateLimiter = new RateLimitManager(RateLimitMode.Pace);
                    //This actually authenticates with reddit, that's why it's in a try/catch while loop
                    _client = new RedditSharp.Reddit(_webAgent, true);
                    break;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    await Task.Delay(TimeSpan.FromMinutes(2)).ConfigureAwait(false);

                    Logger.LogCritical(e.Message, e);
                }
            } while (true);

            StartReddit(cancellationToken);
            Logger.LogInformation($"{Platform} started on account '{_userName}'");

            await Task.Delay(-1, cancellationToken);
        }
예제 #2
0
파일: Reddit.cs 프로젝트: sycomix/Canaan
        public async Task <IEnumerable <NewsThread> > GetThreads(string board)
        {
            using (var op = Begin("Get threads for board {0}", board))
            {
                var source   = $"r.{board}";
                var webAgent = new BotWebAgent(Config("Reddit:User"), Config("Reddit:Pass"), Config("Reddit:ClientId"), Config("Reddit:ClientSecret"), "https://github.com/allisterb/Canaan");
                webAgent.UserAgent = "Canaan/0.1";
                var reddit  = new RedditSharp.Reddit(webAgent);
                var threads = new List <NewsThread>();
                var r       = await reddit.GetSubredditAsync(board);

                await r.GetPosts(Subreddit.Sort.Top, 400).ForEachAsync((post, p) =>
                {
                    var text          = post.IsSelfPost ? post.SelfText : string.Empty;
                    var html          = post.IsSelfPost ? post.SelfTextHtml : null;
                    NewsThread thread = new NewsThread()
                    {
                        Id            = post.Id + "-" + YY,
                        Source        = source,
                        Position      = p + 1,
                        Subject       = post.Title,
                        DatePublished = post.CreatedUTC,
                        User          = post.AuthorName,
                        Text          = text,
                        Links         = post.IsSelfPost ? WebScraper.ExtractLinksFromHtmlFrag(html) : new Link[] { new Link()
                                                                                                                   {
                                                                                                                       Uri = post.Url
                                                                                                                   } }
                    };
                    threads.Add(thread);
                });

                return(threads);
            }
        }
예제 #3
0
        public bool Start(RedditOptions options, string prefix = null)
        {
            try
            {
                Options = options;

                if (!options.Valid())
                {
                    Error(new Exception("Invalid options. Please make sure all options are specified."));
                    return(false);
                }

                Prefix = prefix;

                Agent = new BotWebAgent(options.Username, options.Password, options.ClientId, options.ClientSecret, options.RedirectUrl)
                {
                    UserAgent = options.UserAgent
                };
                Connection   = new Red(Agent, true);
                _userprofile = new User(Connection.User);
                return(true);
            }
            catch (Exception ex)
            {
                Error(ex);
                return(false);
            }
        }
예제 #4
0
        public static void Main(string[] args)
        {
            String logFileName = args.Length > 1 ? args[1] : defaultLogFileName;

            Console.WriteLine("Loading logging...");
            ILogger log;

            try
            {
                log = LoadLogConfig(logFileName);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to load log. Cannot continue.");
                Console.WriteLine(ex);
                return;
            }
            log.Information("Loading configuration file...");
            String fileName             = args.Length != 0 ? args[0] : defaultFileName;
            AuthenticationConfig config = LoadConfigJsonFlatfile(fileName);

            config.ValidateSupportedVersion(minSupportedAuthConfigVersion, maxSupportedAuthConfigVersion);
            BotWebAgent botWebAgent = new BotWebAgent(config.Username, config.Password, config.ClientId, config.ClientSecret, config.RedirectUri)
            {
                //UserAgent = "BotTerminator v1.0.0.0 - /r/" + config.SrName,
            };
            Reddit        r          = new Reddit(botWebAgent, true);
            BotTerminator terminator = new BotTerminator(botWebAgent, r, config, log);

            terminator.StartAsync().ConfigureAwait(false).GetAwaiter().GetResult();
        }
예제 #5
0
파일: Reddit.cs 프로젝트: sycomix/Canaan
        public async Task <IDictionary <NewsThread, List <Post> > > GetPosts(string board, IEnumerable <NewsThread> threads)
        {
            using (var op = Begin("Get posts for {0} threads for board {1}", threads.Count(), board))
            {
                var source   = $"r.{board}";
                var webAgent = new BotWebAgent(Config("Reddit:User"), Config("Reddit:Pass"), Config("Reddit:ClientId"), Config("Reddit:ClientSecret"), "https://github.com/allisterb/Canaan");
                webAgent.UserAgent = "Canaan/0.1";
                var reddit      = new RedditSharp.Reddit(webAgent);
                var threadPosts = new Dictionary <NewsThread, List <Post> >();
                var redditPosts = new Dictionary <RedditSharp.Things.Post, List <Post> >();
                var r           = await reddit.GetSubredditAsync(board);

                await r.GetPosts(Subreddit.Sort.Top, 400).ForEachAsync(async(post, p) =>
                {
                    var thread = threads.SingleOrDefault(t => t.Id == post.Id + "-" + YY);
                    if (thread != null)
                    {
                        var comments = await post.GetCommentsAsync();
                        var posts    = comments.Select((c, cp) => GetPostsFromComment(board, cp, thread.Id, c, null)).SelectMany(x => x).ToList();
                        threadPosts.Add(thread, posts);
                    }
                });

                return(threadPosts);
            }
        }
예제 #6
0
        private static async Task <IEnumerable <RedditCrossViewPost> > GetPosts()
        {
            var webAgent = new BotWebAgent(Configuration.Instance["reddit-username"], Configuration.Instance["reddit-password"], Configuration.Instance["reddit-token"], Configuration.Instance["reddit-secret"], Configuration.Instance["reddit-url"]);
            //This will check if the access token is about to expire before each request and automatically request a new one for you
            //"false" means that it will NOT load the logged in user profile so reddit.User will be null
            var reddit = new Reddit(webAgent, false);
            await reddit.InitOrUpdateUserAsync();

            var authenticated = reddit.User != null;

            if (!authenticated)
            {
                Console.WriteLine("Invalid token");
            }

            var subreddit = await reddit.GetSubredditAsync("/r/crossview");

            var posts = new List <RedditCrossViewPost>();
            //await subreddit.GetTop(RedditSharp.Things.FromTime.All).Where(n => n.CreatedUTC.Year == 2016).Take(50).ForEachAsync(post => {
            //await subreddit.GetTop(RedditSharp.Things.FromTime.Month).Take(50).ForEachAsync(post => {
            await reddit.GetPostAsync(new Uri(@"https://www.reddit.com/r/CrossView/comments/1ujpnj/some_1920s_stereograms/?ref=share&ref_source=link")).ToAsyncEnumerable().ForEachAsync(post => {
                var data = new RedditCrossViewPost(post.Url, null, post.Title, post.Shortlink, post.Score, post.CreatedUTC);
                Console.WriteLine(post.Title);
                posts.Add(data);
            });

            return(posts);
        }
예제 #7
0
        static async Task Main(string[] args)
        {
            dynamic d;

            var directory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

            using (StreamReader r = new StreamReader($"{directory}/credentials.json"))
            {
                var json = r.ReadToEnd();
                d = JObject.Parse(json);
            }

            var webAgent = new BotWebAgent(d.username.ToString(), d.password.ToString(), d.clientID.ToString(), d.clientSecret.ToString(), d.redirectURI.ToString());

            var reddit    = new Reddit(webAgent, false);
            var subreddit = await reddit.GetSubredditAsync("/r/nashville");

            var commentsStream = subreddit.GetComments().Stream();

            var observer = new CommentObserver();

            commentsStream.Subscribe(observer);

            var cancellationToken = new CancellationToken();

            await commentsStream.Enumerate(cancellationToken);
        }
예제 #8
0
        private static async Task Main(string[] args)
        {
            var config = JsonConvert.DeserializeObject <AlerterConfig>(await File.ReadAllTextAsync("config.json"));

            TwilioClient.Init(config.TwilioAccountSid, config.TwilioAuthToken);

            var webAgent = new BotWebAgent(config.RedditUsername, config.RedditPassword, config.AppClientId, config.AppClientSecret, "https://localhost:8080");
            var reddit   = new Reddit(webAgent, false);

            var listeners         = new List <Task>();
            var cancellationToken = new CancellationToken();

            foreach (var subreddit in config.Subreddits)
            {
                var sr = await reddit.GetSubredditAsync(subreddit.Name);

                var stream = sr.GetPosts(Subreddit.Sort.New).Stream();
                stream.Subscribe(ProcessNewPost);
                listeners.Add(stream.Enumerate(cancellationToken));
                Console.WriteLine($"subscribed to /r/{subreddit.Name}");
            }

            Console.WriteLine("listening for new posts");

            await Task.WhenAll(listeners.ToArray());
        }
예제 #9
0
        static async Task MainAsync(string[] args)
        {
            var    login     = File.ReadAllLines(args[0]);
            string subreddit = args[1];

            var    wa     = new BotWebAgent(login[0], login[1], login[2], login[3], login[4]);
            Reddit reddit = new Reddit(wa, true);

            ChapterDictionary dict = new ChapterDictionary(subreddit + ".json");

            Console.WriteLine("Current State: ");
            dict.PrintState();

            while (true)
            {
                await AddNewPostsAsync(dict, reddit, subreddit);

                dict.Save();

                await UpdateChaptersAsync(dict, reddit, subreddit);

                dict.Save();

                await UpdatePoisonedChaptersAsync(dict, reddit, subreddit);

                dict.Save();


                Console.WriteLine("Sleeping.");
                Thread.Sleep(2000);
            }
        }
예제 #10
0
파일: Program.cs 프로젝트: ajryan/podcloud
        private static async Task UpdateReddit(Podcast podcast, string subreddit, string username, string password)
        {
            Console.WriteLine("Updating Reddit wiki");

            var botAgent = new BotWebAgent(
                username, password, "Y4oVLWwzPuymNQ", "_I9Y3z_wIoLWSYT9Y0piHA2-hKI", "https://github.com/ajryan/podcloud");

            var reddit = new Reddit(botAgent, false);
            var sub    = await reddit.GetSubredditAsync(subreddit);

            var wikiPageContent = (await sub.GetWiki.GetPageAsync("index")).MarkdownContent;

            var contentLines        = wikiPageContent.Split(Environment.NewLine).ToList();
            var tableSeparatorIndex = contentLines.IndexOf(":--|:-:|:--|:--");
            var newEpisodeLine      = $"[{podcast.Title.Replace("’", "'")}]({podcast.EpisodeUrl})|{podcast.ReleaseDate:d}|{podcast.Description.Replace("\r", null).Replace("\n", null)}|[Mp3]({podcast.Mp3Url})";

            contentLines.Insert(tableSeparatorIndex + 1, newEpisodeLine);

            Console.WriteLine("New wiki line: " + newEpisodeLine);

            try
            {
                sub.GetWiki.EditPageAsync("index", String.Join(Environment.NewLine, contentLines), reason: podcast.Title.Left(256)).Wait();
            }
            catch (Exception exception)
            {
                Console.WriteLine("Wiki edit failed: " + exception);
            }

            var post    = sub.SubmitPostAsync(podcast.Title, podcast.EpisodeUrl).Result;
            var comment = post.CommentAsync($"Official description:\r\n>{podcast.Description}").Result;

            comment.DistinguishAsync(ModeratableThing.DistinguishType.Moderator).Wait();
        }
예제 #11
0
        public void StartBot()
        {
            var webAgent = new BotWebAgent(_username, _password, _publicKey, _privateKey, @"https://github.com/Fluzzarn/EternalCardFetcher/tree/master");

            reddit = new Reddit(webAgent, true);

            logger.Info("Logged into reddit");
        }
        public void Register(IModularContainer container)
        {
            var appConfiguration = new AppConfiguration();

            // Register the logger for the application immediately
            container.RegisterLogger(appConfiguration.LogFilename);

            // Actual login is performed here.
            var botWebAgent = new BotWebAgent
                              (
                appConfiguration.DB4Username,
                appConfiguration.DB4Password,
                appConfiguration.DB4ClientId,
                appConfiguration.DB4ClientSecret,
                "http://localhost"
                              );

            var reddit    = new RedditSharp.Reddit(botWebAgent, true);
            var subreddit = reddit.GetSubredditAsync($"/r/{appConfiguration.SubredditName}").Result;

            // Register core / shared classes
            container.RegisterSingleton(appConfiguration);
            container.RegisterSingleton <AutoRestartManager>();
            container.RegisterSingleton(botWebAgent);
            container.RegisterSingleton(reddit);
            container.RegisterSingleton(subreddit);
            container.RegisterSingleton <RedditState>();

            // Register shared services
            container.Register <IDB4Queue, DB4MemoryQueue>();

            // Register persistence services
            container.Register <IDB4Repository, DB4Repository>();

            // Register Reddit Services
            container.Register <IActivityDispatcher, RedditSharpActivityDispatcher>();
            container.Register <IActivityMonitor, RedditSharpActivityMonitor>();
            container.Register <IRedditService, RedditSharpRedditService>();
            container.Register <ISubredditService, RedditSharpSubredditService>();

            // Register functionality implementations
            container.Register <IDB4QueueDispatcher, DB4QueueDispatcher>();
            container.Register <ICommentProcessor, CommentProcessor>();
            container.Register <ICommentBuilder, CommentBuilder>();
            container.Register <ICommentDetector, CommentDetector>();
            container.Register <ICommentValidator, CommentValidator>();
            container.Register <ICommentReplier, CommentReplier>();
            container.Register <IDeltaAwarder, DeltaAwarder>();
            container.Register <IDeltaboardEditor, DeltaboardEditor>();
            container.Register <IDeltaLogEditor, DeltaLogEditor>();
            container.Register <IHealthPinger, HealthPinger>();
            container.Register <IPostBuilder, PostBuilder>();
            container.Register <IPrivateMessageProcessor, PrivateMessageProcessor>();
            container.Register <IPrivateMessageHandlerFactory, PrivateMessageHandlerFactory>();
            container.Register <IStickyCommentEditor, StickyCommentEditor>();
            container.Register <IUserWikiEditor, UserWikiEditor>();
        }
예제 #13
0
        public AuthenticatedFixture()
        {
            IConfigurationRoot Config = Cfg.Config;

            WebAgent = new BotWebAgent(Config["UserName"], Config["UserPassword"],
                                       Config["RedditClientID"], Config["RedditClientSecret"], Config["RedditRedirectURI"]);
            AccessToken = WebAgent.AccessToken;
            UserName    = Config["UserName"];
        }
예제 #14
0
        /// <summary>
        /// Initializes the DI container.
        /// </summary>
        private static async Task InitializeContainerAsync()
        {
            var containerBuilder = new ContainerBuilder();

            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("config.json", true, true)
                                .Build();

            containerBuilder.RegisterInstance(configuration)
            .As <IConfigurationRoot>()
            .As <IConfiguration>();

            var logger = new LoggerConfiguration()
                         .WriteTo.Console()
                         .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day)
                         .CreateLogger();

            containerBuilder.RegisterInstance(logger).As <ILogger>();

            var webAgent = new BotWebAgent(
                configuration["reddit:username"],
                configuration["reddit:password"],
                configuration["reddit:clientId"],
                configuration["reddit:clientSecret"],
                configuration["reddit:redirectUri"]
                );

            var reddit = new Reddit(webAgent, true);

            containerBuilder.RegisterInstance(reddit).As <Reddit>();

            logger.Information($"Logged into Reddit as /u/{reddit.User}.");

            var subreddit = await reddit.GetSubredditAsync(configuration["reddit:subreddit"]);

            containerBuilder.RegisterInstance(subreddit).As <Subreddit>();

            var httpClient = new HttpClient();

            containerBuilder.RegisterInstance(httpClient).As <HttpClient>();

            logger.Information($"Loaded subreddit /r/{subreddit.Name}.");

            containerBuilder.RegisterType <ImagePostTrackerModule>()
            .As <IModule>()
            .As <IPostMonitorModule>();

            containerBuilder.RegisterType <DiscordWebhookModule>()
            .As <IModule>()
            .As <IPostMonitorModule>();

            logger.Information("Container initialization complete.");

            Container = containerBuilder.Build();
        }
예제 #15
0
        public static void Main(string[] args)
        {
            Console.WriteLine("starting");
            JToken        config      = LoadConfigDeprecated();
            BotWebAgent   botWebAgent = new BotWebAgent(config["username"].Value <String>(), config["password"].Value <String>(), config["clientId"].Value <String>(), config["clientSecret"].Value <String>(), config["redirectUri"].Value <String>());
            Reddit        r           = new Reddit(botWebAgent, true);
            BotTerminator terminator  = new BotTerminator(r, config["srName"].Value <String>());

            terminator.StartAsync().ConfigureAwait(false).GetAwaiter().GetResult();
        }
        public Reddit Create(IBotSettings settings)
        {
            var webAgent = new BotWebAgent(settings.Username, settings.Password, settings.ClientId, settings.ClientSecret, settings.RedirectUri);
            //This will check if the access token is about to expire before each request and automatically request a new one for you
            //"false" means that it will NOT load the logged in user profile so reddit.User will be null
            var reddit = new Reddit(webAgent, false);

            reddit.InitOrUpdateUser();
            return(reddit);
        }
예제 #17
0
        public Crawler()
        {
            Settings settings = Settings.Instance;
            var      agent    = new BotWebAgent(
                Settings.Instance.Reddit.Username, Settings.Instance.Reddit.Password,
                Settings.Instance.Reddit.ClientID, Settings.Instance.Reddit.Secret,
                ""
                );

            reddit = new Reddit(agent, false);
        }
예제 #18
0
        public RedditService(string username, string password, string clientId, string clientSecretId)
        {
            m_botUsername    = username;
            m_botPassword    = password;
            m_clientId       = clientId;
            m_secretClientId = clientSecretId;

            BotWebAgent webAgent = new BotWebAgent(m_botUsername, m_botPassword, m_clientId, m_secretClientId, "http://localhost:8080");

            m_activeReddit = new Reddit(webAgent, true);
        }
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            try
            {
                //TODO - Get real redirect URL:
                BotWebAgent webAgent = new BotWebAgent(SettingsManager.RedditUsername(), SettingsManager.RedditPassword(), SettingsManager.RedditAppid(), SettingsManager.RedditAppSecret(), "http://www.example.com/unused/redirect/uri");

                var reddit = new Reddit(webAgent);
                var user   = await reddit.GetUserAsync(SettingsManager.RedditUsername());

                var comments = user.GetComments(-1);

                IList <AnalyseTextRequest> analyseRequests = new List <AnalyseTextRequest>();
                await comments.ForEachAsync(c =>
                {
                    analyseRequests.Add(new AnalyseTextRequest
                    {
                        ContentCreatedOn = c.Created,
                        Medium           = "Reddit",
                        Text             = c.Body
                    });
                });

                SentimentService sentimentService = new SentimentService();

                foreach (var comment in analyseRequests)
                {
                    try
                    {
                        log.Info($"Getting sentiment and saving comment: {comment.Text}");
                        var result = await sentimentService.GetSentiment(comment);

                        await sentimentService.SaveSentimentResult(result);
                    }
                    catch (Exception e)
                    {
                        log.Error($"{e.Message}");
                        log.Error($"Error saving comment {comment.Text}");
                    }
                }

                return(new OkObjectResult("Posts saved successfully"));
            }
            catch (Exception e)
            {
                log.Error("Uncaught exception occurred", e);
                return(new BadRequestObjectResult("An unexpected error occurred processing your request"));
            }
        }
예제 #20
0
        static void Main(string[] args)
        {
            int times;

            //File shit
            if (File.Exists("times.t"))
            {
                StreamReader fr = File.OpenText("times.t");
                times = int.Parse(fr.ReadLine());
                fr.Close();
            }
            else
            {
                times = 0;
            }

            //Reddit code
            var webAgent = new BotWebAgent("Good_Good_GB_BB", "newpass", "1zqbIrqwygfySg", "2oHOvib5wBKMmaHEpW9C4QU3Q7M", "localhost:8080");
            //This will check if the access token is about to expire before each request and automatically request a new one for you
            //"false" means that it will NOT load the logged in user profile so reddit.User will be null
            var reddit    = new Reddit(webAgent, true);
            var subreddit = reddit.RSlashAll;

            while (true)
            {
                foreach (var c in subreddit.Comments)
                {
                    try
                    {
                        Console.Write("Comment author:{0}", c.AuthorName);
                        Console.Write(" || Parent author:{0}\n", ((Comment)reddit.GetThingByFullname(c.ParentId)).AuthorName);
                        if (((Comment)reddit.GetThingByFullname(c.ParentId)).AuthorName == "Good_GoodBot_BadBot")
                        {
                            if (c.Body.ToLower() == "good bot" || c.Body.ToLower() == "good bot.")
                            {
                                times++;
                                var comment = c.Reply(string.Format("You are the {0}^th person calling /u/Good_GoodBot_BadBot a good bot. HE definetly is a little less awesome!", times));
                                Console.WriteLine("Commented: {0}", times);
                                writef(times);
                            }
                        }
                    }
                    catch (InvalidCastException)
                    {
                        Console.WriteLine(" || Not a comment");
                    }
                }
                Thread.Sleep(500);
            }
        }
예제 #21
0
        public static Listing <RedditSharp.Things.Post> GetNewSubRedditPosts(string subRedditName)
        {
            var webAgent = new BotWebAgent(
                Credentials.Reddit.Login,
                Credentials.Reddit.Password,
                Credentials.Reddit.Id,
                Credentials.Reddit.Secret,
                Credentials.Reddit.RedirectURI
                );
            var reddit    = new Reddit(webAgent, false);
            var subReddit = reddit.GetSubreddit(subRedditName);

            return(subReddit.New);
        }
예제 #22
0
파일: Get.cs 프로젝트: Bitz/OwO_Bot
        public static Reddit Reddit()
        {
            BotWebAgent webAgent = new BotWebAgent(
                Config.reddit.username,
                Config.reddit.password,
                Config.reddit.client_id,
                Config.reddit.secret_id,
                Config.reddit.callback_url);
            var reddit = new Reddit(webAgent, true);

            //Login to reddit
            reddit.LogIn(Config.reddit.username, Config.reddit.password);

            return(reddit);
        }
예제 #23
0
        public RedditPoster(SettingsKeeper settingsKeeper)
        {
            _settingsKeeper = settingsKeeper;

            if (bool.Parse(_settingsKeeper.GetSetting("EnableReddit").Value))
            {
                var user         = settingsKeeper.GetSetting("RedditUser").Value;
                var password     = settingsKeeper.GetSetting("RedditPassword").Value;
                var clientId     = settingsKeeper.GetSetting("RedditClientId").Value;
                var clientSecret = settingsKeeper.GetSetting("RedditClientSecret").Value;
                var redirectUrl  = settingsKeeper.GetSetting("SiteUrl").Value;

                var botAgent = new BotWebAgent(user, password, clientId, clientSecret, redirectUrl);
                _reddit = new Reddit(botAgent);
            }
        }
예제 #24
0
        /// <summary>
        /// Method used to establish a connection with Reddit and log in.
        /// </summary>
        /// <returns>A Reddit object</returns>
        static Reddit ConnectToReddit()
        {
            var webAgent = new BotWebAgent("USERNAME", "PASSWORD", "CLIENTID", "SECRET", "https://www.nowebsite.com/");
            //This will check if the access token is about to expire before each request and automatically request a new one for you
            //"false" means that it will NOT load the logged in user profile so reddit.User will be null
            var reddit = new Reddit(webAgent, true);

            //Make sure we are not exceeding Reddit API Limits.
            if (SubsToMonitorList.Count > 99)
            {
                throw new Exception("Bots can only monitor up to 100 subreddits at the same time.");
            }

            Log("Successfully connected to Reddit!");
            return(reddit);
        }
예제 #25
0
        void InitializeRedditApi(IRedditCredentials creds)
        {
            if (creds.AreIncomplete())
            {
                throw new InvalidConfigurationException(
                          "You must fill in your Reddit information into the settings page first.");
            }

            string      userAgent   = creds.UserAgent ?? "News Sharer";
            BotWebAgent botWebAgent = new BotWebAgent(creds.Username,
                                                      creds.Password, creds.ClientId, creds.ClientSecret,
                                                      "https://localhost/");

            botWebAgent.UserAgent = $"{userAgent} (/u/{creds.Username})";
            RedditApi             = new RedditSharp.Reddit(botWebAgent, false);
        }
예제 #26
0
        static void Main(string[] args)
        {
            String user         = System.Configuration.ConfigurationSettings.AppSettings["username"];
            String pass         = System.Configuration.ConfigurationSettings.AppSettings["password"];
            String sub          = System.Configuration.ConfigurationSettings.AppSettings["subreddit"];
            String secret       = System.Configuration.ConfigurationSettings.AppSettings["secret"];
            String client       = System.Configuration.ConfigurationSettings.AppSettings["client"];
            String redirect     = System.Configuration.ConfigurationSettings.AppSettings["redirect"];
            String storeDir     = System.Configuration.ConfigurationSettings.AppSettings["storageDir"];
            int    maxBlockSize = Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["maxBlockSize"]);


            var webAgent  = new BotWebAgent(user, pass, client, secret, redirect);
            var reddit    = new Reddit(webAgent, true);
            var subreddit = reddit.GetSubreddit(sub);

            RedditFsStore    store    = new RedditFsStore(subreddit, maxBlockSize);
            RedditFsRetrieve retrieve = new RedditFsRetrieve(reddit, subreddit, storeDir);
            Shell            shell    = new Shell(reddit, subreddit);

            if (args.Length == 2)
            {
                if (args[0] == "store")
                {
                    Console.WriteLine("Attempting to store file at root: " + args[1]);
                    store.storeFile(args[1]);
                }
                else if (args[0] == "retrieve")
                {
                    Console.WriteLine("Attempting to retrive file into current dir: " + args[1]);
                    retrieve.retrieveFile(args[1]);
                }
            }
            else if (args.Length == 1)
            {
                if (args[0] == "shell")
                {
                    Console.WriteLine("h e l l o  r e d d i t");
                    shell.startShell();
                }
            }
            else
            {
                Console.WriteLine("Unsupported op.");
            }
        }
예제 #27
0
        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());
            }
        }
예제 #28
0
        static void Main(string[] args)
        {
            var webagent = new BotWebAgent("Zephandrypus", "meeko011", "KjwX25olhbEI4w", "vVmP-rTXj6EX43iGZkzywi-X4xo", "https://example.com");
            var reddit   = new Reddit(webagent, true);
            var user     = reddit.User;
            var saved    = user.GetSaved(Sort.Top, 100, FromTime.Year).Where(p => p.Kind == "t1");

            saved.SaveAs(@"E:\RedditBots\SavedComments.txt");
            var savedFull = new SortedDictionary <string, Comment[]>(
                saved.Select(
                    p => reddit.GetComment(
                        new Uri(p.Shortlink)
                        )
                    ).GroupBy(
                    c => c.Subreddit.ToLower(),
                    c => c
                    ).ToDictionary(
                    s => s.Key,
                    s => s.ToArray()
                    )
                );

            savedFull.SaveAs(@"E:\RedditBots\SavedCommentsFull.txt");
            var savedAskreddit = savedFull["askreddit"];

            savedAskreddit.SaveAs(@"E:\RedditBots\SavedCommentsAskreddit.txt");
            savedAskreddit = savedAskreddit.Where(
                c => (
                    c.Body.Contains("lottery") ||
                    c.Body.Contains("money")
                    ) && (
                    c.Body.Contains("lawyer") ||
                    c.Body.Contains("broker")
                    )
                ).OrderByDescending(c => c.Body.Length).ToArray();
            savedAskreddit.SaveAs(@"E:\RedditBots\SavedAskredditLottery.txt");
            foreach (var comment in savedAskreddit)
            {
                Console.WriteLine(comment.LinkTitle + " - " + comment.Shortlink + " - " + comment.Score);
            }
            Console.ReadLine();
        }
예제 #29
0
        private static Reddit AuthorizeRedditBot()
        {
            BotWebAgent webAgent = new BotWebAgent(C.Reddit.Username,
                                                   C.Reddit.Password,
                                                   C.Reddit.ClientId,
                                                   C.Reddit.ClientSecret,
                                                   "https://google.com");

            Reddit reddit = new Reddit(webAgent, true);

            reddit.LogIn(C.Reddit.Username, C.Reddit.Password);
            string redditName = reddit.User.FullName;

            if (redditName.ToLower() == C.Reddit.Username.ToLower())
            {
                Console.WriteLine("Logged in!");
            }

            return(reddit);
        }
예제 #30
0
        static void Main(string[] args)
        {
            var configBuilder = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("privateconfig.json", false, true);

            var config = configBuilder.Build();

            config.Bind(Configuration);

            RedditAgent      = new BotWebAgent(Configuration.Username, Configuration.Password, Configuration.ClientID, Configuration.Secret, "");
            SpezzitBotReddit = new Reddit(RedditAgent, true);

            var inboxWatcher = new InboxWatcher();

            inboxWatcher.Run();

            CheckLoggers();

            Console.ReadLine();
        }