当前位置: 首页>>代码示例>>Python>>正文


Python Reddit.get_info方法代码示例

本文整理汇总了Python中praw.Reddit.get_info方法的典型用法代码示例。如果您正苦于以下问题:Python Reddit.get_info方法的具体用法?Python Reddit.get_info怎么用?Python Reddit.get_info使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在praw.Reddit的用法示例。


在下文中一共展示了Reddit.get_info方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: update_procedure

# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_info [as 别名]
    def update_procedure(self, thing_id, created, lifetime, last_updated, interval):
        pass

    def general_action(self, body, thing_id, subreddit, username):
        if not subreddit.lower() in self.APPROVE or 'leafeator' in username.lower():
            # filtering out all other stuff
            return False

        result = self.REGEX.search(body)
        if result:
            self.oauth.refresh()
            self.session._add_comment(thing_id, self.RESPONSE)
            return True
        return False

    def on_new_message(self, message):
        pass


def init(database):
    """Init Call from module importer to return only the object itself, rather than the module."""
    return LeafeatorBot(database)


if __name__ == '__main__':
    from praw import Reddit
    r = Reddit(user_agent='Manual Testing')
    cmt = r.get_info(thing_id='t1_cud1d76')
    lb = LeafeatorBot(None)
    lb.execute_comment(cmt)
开发者ID:minogame,项目名称:Massdrop-Reddit-Bot,代码行数:32,代码来源:LeafeatorBot.py

示例2: OAuth2RedditTest

# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_info [as 别名]

#.........这里部分代码省略.........
        self.r.refresh_access_information(self.refresh_token['mysubreddits'])
        self.assertTrue(list(self.r.get_my_moderation()))

    @betamax()
    def test_scope_creddits(self):
        # Assume there are insufficient creddits.
        self.r.refresh_access_information(
            self.refresh_token['creddits'])
        redditor = self.r.get_redditor('bboe')
        sub = self.r.get_submission(url=self.comment_url)

        # Test error conditions
        self.assertRaises(TypeError, sub.gild, months=1)
        for value in (False, 0, -1, '0', '-1'):
            self.assertRaises(TypeError, redditor.gild, value)

        # Test object gilding
        self.assertRaises(errors.InsufficientCreddits, redditor.gild)
        self.assertRaises(errors.InsufficientCreddits, sub.gild)
        self.assertRaises(errors.InsufficientCreddits, sub.comments[0].gild)

    @betamax()
    def test_scope_privatemessages(self):
        self.r.refresh_access_information(
            self.refresh_token['privatemessages'])
        self.assertTrue(list(self.r.get_inbox()))

    @betamax()
    def test_scope_read(self):
        self.r.refresh_access_information(self.refresh_token['read'])
        self.assertTrue(self.r.get_subreddit(self.priv_sr).subscribers > 0)
        fullname = '{0}_{1}'.format(self.r.config.by_object[Submission],
                                    self.priv_submission_id)
        method1 = self.r.get_info(thing_id=fullname)
        method2 = self.r.get_submission(submission_id=self.priv_submission_id)
        self.assertEqual(method1, method2)

    @betamax()
    def test_scope_read_get_front_page(self):
        self.r.refresh_access_information(self.refresh_token['mysubreddits'])
        subscribed = list(self.r.get_my_subreddits(limit=None))
        self.r.refresh_access_information(self.refresh_token['read'])
        for post in self.r.get_front_page():
            self.assertTrue(post.subreddit in subscribed)

    @betamax()
    def test_scope_read_get_sub_listingr(self):
        self.r.refresh_access_information(self.refresh_token['read'])
        subreddit = self.r.get_subreddit(self.priv_sr)
        self.assertTrue(list(subreddit.get_top()))

    @betamax()
    def test_scope_read_get_submission_by_url(self):
        url = ("https://www.reddit.com/r/reddit_api_test_priv/comments/16kbb7/"
               "google/")
        self.r.refresh_access_information(self.refresh_token['read'])
        submission = Submission.from_url(self.r, url)
        self.assertTrue(submission.num_comments != 0)

    @betamax()
    def test_scope_read_priv_sr_comments(self):
        self.r.refresh_access_information(self.refresh_token['read'])
        self.assertTrue(list(self.r.get_comments(self.priv_sr)))

    @betamax()
    def test_scope_wikiread_wiki_page(self):
开发者ID:andrewalexander,项目名称:praw,代码行数:70,代码来源:test_oauth2_reddit.py

示例3: OAuth2RedditTest

# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_info [as 别名]

#.........这里部分代码省略.........
            raise errors.OAuthException(oerrormessage, oerrorurl)

        self.assertRaises(errors.OAuthException, raise_oauth_exception)
        oauth_exception = errors.OAuthException(oerrormessage, oerrorurl)
        self.assertEqual(oauth_exception.message +
                         " on url {0}".format(oauth_exception.url),
                         str(oauth_exception))

    def test_raise_redirect_exception(self):
        apiurl = "http://api.reddit.com/"
        oauthurl = "http://oauth.reddit.com/"

        def raise_redirect_exception():
            raise errors.RedirectException(apiurl, oauthurl)

        self.assertRaises(errors.RedirectException, raise_redirect_exception)
        redirect_exception = errors.RedirectException(apiurl, oauthurl)
        self.assertEqual(redirect_exception.message, str(redirect_exception))

    @betamax()
    def test_scope_history(self):
        self.r.refresh_access_information(self.refresh_token['history'])
        self.assertTrue(list(self.r.get_redditor(self.un).get_upvoted()))

    @betamax()
    def test_scope_identity(self):
        self.r.refresh_access_information(self.refresh_token['identity'])
        self.assertEqual(self.un, self.r.get_me().name)

    @betamax()
    def test_scope_mysubreddits(self):
        self.r.refresh_access_information(self.refresh_token['mysubreddits'])
        self.assertTrue(list(self.r.get_my_moderation()))

    @betamax()
    def test_scope_creddits(self):
        # Assume there are insufficient creddits.
        self.r.refresh_access_information(
            self.refresh_token['creddits'])
        redditor = self.r.get_redditor('bboe')
        sub = self.r.get_submission(url=self.comment_url)

        # Test error conditions
        self.assertRaises(TypeError, sub.gild, months=1)
        for value in (False, 0, -1, '0', '-1'):
            self.assertRaises(TypeError, redditor.gild, value)

        # Test object gilding
        self.assertRaises(errors.InsufficientCreddits, redditor.gild)
        self.assertRaises(errors.InsufficientCreddits, sub.gild)
        self.assertRaises(errors.InsufficientCreddits, sub.comments[0].gild)

    @betamax()
    def test_scope_privatemessages(self):
        self.r.refresh_access_information(
            self.refresh_token['privatemessages'])
        self.assertTrue(list(self.r.get_inbox()))

    @betamax()
    def test_scope_read(self):
        self.r.refresh_access_information(self.refresh_token['read'])
        self.assertTrue(self.r.get_subreddit(self.priv_sr).subscribers > 0)
        fullname = '{0}_{1}'.format(self.r.config.by_object[Submission],
                                    self.priv_submission_id)
        method1 = self.r.get_info(thing_id=fullname)
        method2 = self.r.get_submission(submission_id=self.priv_submission_id)
        self.assertEqual(method1, method2)

    @betamax()
    def test_scope_read_get_front_page(self):
        self.r.refresh_access_information(self.refresh_token['mysubreddits'])
        subscribed = list(self.r.get_my_subreddits(limit=None))
        self.r.refresh_access_information(self.refresh_token['read'])
        for post in self.r.get_front_page():
            self.assertTrue(post.subreddit in subscribed)

    @betamax()
    def test_set_access_credentials(self):
        self.assertTrue(self.r.user is None)
        result = self.r.refresh_access_information(
            self.refresh_token['identity'], update_session=False)
        self.assertTrue(self.r.user is None)
        self.r.set_access_credentials(**result)
        self.assertFalse(self.r.user is None)

    @betamax()
    def test_solve_captcha(self):
        # Use the alternate account because it has low karma,
        # so we can test the captcha.
        self.r.refresh_access_information(self.other_refresh_token['submit'])
        original_stdin = sys.stdin
        sys.stdin = FakeStdin('ljgtoo')  # Comment this line when rebuilding
        self.r.submit(self.sr, 'captcha test', 'body')
        sys.stdin = original_stdin

    @betamax()
    def test_oauth_without_identy_doesnt_set_user(self):
        self.assertTrue(self.r.user is None)
        self.r.refresh_access_information(self.refresh_token['edit'])
        self.assertTrue(self.r.user is None)
开发者ID:JamieMagee,项目名称:praw,代码行数:104,代码来源:test_oauth2_reddit.py

示例4: on_new_message

# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_info [as 别名]
                return False

            self.oauth.refresh()
            self.session._add_comment(thing.name, self.RESPONSE)
            self.database.insert_into_storage(thread_id, self.BOT_NAME)
            return True
        return False

    def on_new_message(self, message):
        pass


def init(database):
    """Init Call from module importer to return only the object itself, rather than the module."""
    return LeafeatorBot(database)


if __name__ == "__main__":
    from praw import Reddit
    from core.DatabaseProvider import DatabaseProvider
    from core import LogProvider

    logger = LogProvider.setup_logging(log_level="DEBUG")
    db = DatabaseProvider()
    r = Reddit(user_agent="Manual Testing")
    subm = r.get_info(thing_id="t3_3ik036")
    cmt = r.get_info(thing_id="t1_cuilwo5")
    lb = LeafeatorBot(db)
    lb.execute_comment(cmt)
    # lb.execute_submission(subm)
开发者ID:ahmadmu,项目名称:RedditRover,代码行数:32,代码来源:LeafeatorBot.py

示例5: __init__

# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_info [as 别名]
class Reddit_Cleverbot:

  def __init__(self, username, password, subreddit='all', useragent=USERAGENT):
    self.username = username
    self.password = password
    self.useragent = useragent
    self.subreddit = subreddit
    self.reddit = Reddit(useragent)
    self.reddit.login(username, password)
    self.stopped = True
    self.thread = None
    self.done = set()
    self.conversations = dict()

  def random_hot_comment(self):
    sub = self.reddit.get_subreddit(self.subreddit)
    hot = [post for post in sub.get_hot(limit=25)]
    post = random.choice(hot)
    comments = praw.helpers.flatten_tree(post.comments)
    # filter the comments to remove already-replied ones
    comments = [comment for comment in comments if comment not in self.done and isinstance(comment, praw.objects.Comment)]
    return random.choice(comments[0:100])

  def random_comment(self):
    comments = self.reddit.get_comments(self.subreddit)
    # filter the comments to remove already-replied ones
    comments = [comment for comment in comments if comment not in self.done]
    return random.choice(comments)

  def get_summoned_comments(self):
    comments = self.reddit.get_comments(self.subreddit)
    children = [comment for comment in comments 
      if comment not in self.done and SUMMON in comment.body]
    # print "--> " + str(len(children)) + " summons found!"
    return [self.reddit.get_info(thing_id=comment.parent_id) for comment in children]

  def reply(self, comment):
    if self.reddit.get_info(thing_id=comment.parent_id).author.name == self.username:
      # TODO: handle a threaded conversation over restarts. will need a DB. ugh
      pass
    if comment.parent_id in self.conversations:
      cleverbot = self.conversations[comment.parent_id]
    else:
      cleverbot = Cleverbot()
    response = cleverbot.ask(comment.body)
    post = comment.reply(response)
    self.done.add(comment.id)
    self.conversations[post.id] = copy(cleverbot)

  def reply_unread(self, interval):
    for item in self.reddit.get_unread():
      if item.parent_id not in self.conversations:
        print "Could not find conversation! Ignoring for now."
        pass
      self.reply(item)
      item.mark_as_read()
      time.sleep(interval)

  def reply_to_summons(self):
    summons = self.get_summoned_comments()
    for comment in summons:
      self.reply(comment)

  def _run_random(self, interval):
    while not self.stopped:
      self.reply_unread(interval)
      self.reply(self.random_hot_comment())
      time.sleep(interval)

  def run_random(self, interval):
    self.stopped = False
    self.thread = Thread(target=self._run_random, args=(interval,))
    self.thread.start()

  def stop(self):
    self.stopped = True
    #self.thread.join()
开发者ID:damianw,项目名称:Reddit_Cleverbot,代码行数:79,代码来源:reddit_cleverbot.py

示例6: __init__

# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_info [as 别名]
class StatisticsFeeder:
    """
    :type db: Database
    :type session: Reddit
    """
    def __init__(self, database, handler, path='../html/'):
        self.db = database
        self.path = path
        self.session = Reddit(user_agent='Statistics poller for RedditRover', handler=handler)
        self.config = ConfigParser()
        self.config.read(resource_filename('config', 'bot_config.ini'))
        self.authors = self.get_authors()
        self.status_online()
        atexit.register(self.status_offline)

    def _set_status(self, state, message):
        template_info = '''<span class="label label-{type}">Status: {title}</span>'''
        if state == 'online':
            info = template_info.format(type='success', title='Online', content=message)
        elif state == 'offline':
            info = template_info.format(type='danger', title='Offline', content=message)
        elif state == 'warning':
            info = template_info.format(type='warn', title='Warning', content=message)
        else:
            info = ''
        self._write_meta(info=info)

    def _write_meta(self, info):
        meta_stats = self.db.select_day_from_meta(time())
        if meta_stats:
            date, subm, comments, cycles = meta_stats
            reacted = self.db.get_total_responses_per_day(time())[0]
            rate = reacted * 100 / (comments + subm)
        else:
            subm, comments, cycles, rate = 0, 0, 0, 0
        with open(self.path + '_data/_meta.json', 'w') as f:
            f.write(json.dumps(
                {'status': info, 'submissions': subm, 'comments': comments, 'cycles': cycles,
                 'rate': '{:.5f}'.format(rate)}
            ))

    def status_online(self):
        self._set_status('online', 'The bot is currently running, last update was {}'.format(time()))

    def status_offline(self):
        self._set_status('offline', 'The bot is currently offline.')

    def status_warning(self, traceback=None):
        if traceback:
            self._set_status('warning', 'Here is the latest traceback: <br /><pre>{}</pre>'.format(traceback))
        else:
            self._set_status('warning', 'Check the console, there is maybe an error. (no traceback given)')

    def get_authors(self):
        carelist = []
        for section in self.config.sections():
            for option in self.config.options(section):
                if option == 'username':
                    carelist.append(self.config.get(section, option).lower())
        return carelist

    def get_old_comment_karma(self):
        threads = self.db.get_karma_loads()
        for thread in threads:  # tuple of tuple
            thing_id = thread[0]
            thing = self.session.get_info(thing_id=thing_id)
            author_votes = thing.score
            if type(thing) is Comment:
                replies = thing.replies
            elif type(thing) is Submission:
                thing.replace_more_comments(limit=None, threshold=1)
                replies = thing.comments
            elif type(thing) is MoreComments:
                replies = thing.comments(update=True)
            for comment in replies:
                if comment.author and comment.author.name.lower() in self.authors:
                    self.db.update_karma_count(thing_id, author_votes, comment.score)
                    break
            else:
                self.db.update_karma_count_with_null(thing_id, author_votes)

    def _write_filler_karma(self):
        from random import randint
        threads = self.db.get_karma_loads()
        for thread in threads:
            thread_id = thread[0]
            self.db.update_karma_count(thread_id, randint(-50, 350), randint(-50, 350))

    def render_overview(self):
        self.status_online()
        self._table_rows()
        self._plugin_activity()
        self._subreddit_activity()
        self._post_histogram()

    def _table_rows(self):
        dataset = self.db.get_all_stats()
        carelist = []
        title = '<a href="{url}" target="_blank" class="text-primary"> {text} </a>'
        subreddit = '<a href="http://reddit.com/r/{sub}" target="_blank" class="text-warning"> {sub} </a>'
#.........这里部分代码省略.........
开发者ID:CastleCorp,项目名称:RedditRover,代码行数:103,代码来源:stats.py

示例7: OAuth2RedditTest

# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_info [as 别名]

#.........这里部分代码省略.........
        subreddit.add_wiki_ban(self.other_user_name)
        subreddit.remove_wiki_ban(self.other_user_name)

        subreddit.add_wiki_contributor(self.other_user_name)
        subreddit.remove_wiki_contributor(self.other_user_name)

    @betamax()
    def test_scope_creddits(self):
        # Assume there are insufficient creddits.
        self.r.refresh_access_information(self.refresh_token["creddits"])
        redditor = self.r.get_redditor("bboe")
        sub = self.r.get_submission(url=self.comment_url)

        # Test error conditions
        self.assertRaises(TypeError, sub.gild, months=1)
        for value in (False, 0, -1, "0", "-1"):
            self.assertRaises(TypeError, redditor.gild, value)

        # Test object gilding
        self.assertRaises(errors.InsufficientCreddits, redditor.gild)
        self.assertRaises(errors.InsufficientCreddits, sub.gild)
        self.assertRaises(errors.InsufficientCreddits, sub.comments[0].gild)

    @betamax()
    def test_scope_privatemessages(self):
        self.r.refresh_access_information(self.refresh_token["privatemessages"])
        self.assertTrue(list(self.r.get_inbox()))

    @betamax()
    def test_scope_read(self):
        self.r.refresh_access_information(self.refresh_token["read"])
        self.assertTrue(self.r.get_subreddit(self.priv_sr).subscribers > 0)
        fullname = "{0}_{1}".format(self.r.config.by_object[Submission], self.priv_submission_id)
        method1 = self.r.get_info(thing_id=fullname)
        method2 = self.r.get_submission(submission_id=self.priv_submission_id)
        self.assertEqual(method1, method2)

    @betamax()
    def test_scope_read_get_front_page(self):
        self.r.refresh_access_information(self.refresh_token["mysubreddits"])
        subscribed = list(self.r.get_my_subreddits(limit=None))
        self.r.refresh_access_information(self.refresh_token["read"])
        for post in self.r.get_front_page():
            self.assertTrue(post.subreddit in subscribed)

    @betamax()
    def test_scope_read_get_sub_listingr(self):
        self.r.refresh_access_information(self.refresh_token["read"])
        subreddit = self.r.get_subreddit(self.priv_sr)
        self.assertTrue(list(subreddit.get_top()))

    @betamax()
    def test_scope_read_get_submission_by_url(self):
        url = "https://www.reddit.com/r/reddit_api_test_priv/comments/16kbb7/" "google/"
        self.r.refresh_access_information(self.refresh_token["read"])
        submission = Submission.from_url(self.r, url)
        self.assertTrue(submission.num_comments != 0)

    @betamax()
    def test_scope_read_priv_sr_comments(self):
        self.r.refresh_access_information(self.refresh_token["read"])
        self.assertTrue(list(self.r.get_comments(self.priv_sr)))

    @betamax()
    def test_scope_wikiread_wiki_page(self):
        self.r.refresh_access_information(self.refresh_token["wikiread"])
开发者ID:andresrestrepo,项目名称:praw,代码行数:70,代码来源:test_oauth2_reddit.py


注:本文中的praw.Reddit.get_info方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。