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


Python Reddit.get_comments方法代码示例

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


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

示例1: OAuth2RedditTest

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

#.........这里部分代码省略.........
        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'])
        self.assertTrue(self.r.get_wiki_page(self.sr, 'index'))

    @betamax()
    def test_scope_read_priv_sub_comments(self):
        self.r.refresh_access_information(self.refresh_token['read'])
        submission = Submission.from_id(self.r, self.priv_submission_id)
        self.assertTrue(submission.comments)

    @betamax()
    def test_scope_submit(self):
        self.r.refresh_access_information(self.refresh_token['submit'])
        result = self.r.submit(self.sr, 'OAuth Submit', text='Foo')
        self.assertTrue(isinstance(result, Submission))

    @betamax()
    def test_scope_subscribe(self):
        self.r.refresh_access_information(self.refresh_token['subscribe'])
        self.r.get_subreddit(self.sr).subscribe()

    @betamax()
    def test_scope_vote(self):
        self.r.refresh_access_information(self.refresh_token['vote'])
        submission = Submission.from_id(self.r, self.submission_edit_id)
        submission.clear_vote()

    @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_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:andrewalexander,项目名称:praw,代码行数:104,代码来源:test_oauth2_reddit.py

示例2: OAuth2RedditTest

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

#.........这里部分代码省略.........
        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"])
        self.assertTrue(self.r.get_wiki_page(self.sr, "index"))

    @betamax()
    def test_scope_read_priv_sub_comments(self):
        self.r.refresh_access_information(self.refresh_token["read"])
        submission = Submission.from_id(self.r, self.priv_submission_id)
        self.assertTrue(submission.comments)

    @betamax()
    def test_scope_submit(self):
        self.r.refresh_access_information(self.refresh_token["submit"])
        result = self.r.submit(self.sr, "OAuth Submit", text="Foo")
        self.assertTrue(isinstance(result, Submission))

    @betamax()
    def test_scope_subscribe(self):
        self.r.refresh_access_information(self.refresh_token["subscribe"])
        self.r.get_subreddit(self.sr).subscribe()

    @betamax()
    def test_scope_vote(self):
        self.r.refresh_access_information(self.refresh_token["vote"])
        submission = Submission.from_id(self.r, self.submission_edit_id)
        submission.clear_vote()

    @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_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:andresrestrepo,项目名称:praw,代码行数:104,代码来源:test_oauth2_reddit.py

示例3: __init__

# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_comments [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

示例4: __init__

# 需要导入模块: from praw import Reddit [as 别名]
# 或者: from praw.Reddit import get_comments [as 别名]
class FetchBot:
    """Bot to fetch the subreddit data."""

    def __init__(self, user_agent, subreddit, data_file):
        """Basic constructor"""
        self._user_agent = user_agent
        self._subreddit = subreddit
        self._data_file = data_file
        try:
            with open(self._data_file) as df:
                self._data = json.load(df)
        except (FileNotFoundError,json.decoder.JSONDecodeError):
            self._data = json.loads('{"comments":{},"posts":{}}')

        try:
            if self._data['subreddit'] != self._subreddit:
                raise ValueError('The data file does not correspond the subreddit r/'+self._subreddit+' (found "'+self._data['subreddit']+'")')
        except KeyError:
            self._data['subreddit'] = self._subreddit

        self._praw = Reddit(self._user_agent)

    def __del__(self):
        """Destructor"""
        if not os.path.exists(os.path.dirname(self._data_file)):
            os.makedirs(os.path.dirname(self._data_file))
        with open(self._data_file, 'w') as df:
            json.dump(self._data, df)

    def fetch(self):
        """Fetching function"""
        self._fetch(self._praw.get_comments(self._subreddit, limit=500), 'comments')
        self._fetch(self._praw.get_subreddit(self._subreddit).get_new(limit=500), 'posts')

    def _fetch(self, submissions, key):
        """Generic fetching function"""

        is_first = True

        storage.dict_check_key(self._data[key], 'first', float(round(time.time())))

        try:
            new_creation_limit = self._data[key]['last']
        except:
            self._data[key]['last'] = new_creation_limit = 0

        for it in submissions:
            if is_first:
                is_first = False
                new_creation_limit = it.created
            if it.created <= self._data[key]['last']:
                break

            storage.dictvar(self._data[key], 'count', 1, 1)

            try:
                if str(it.author) not in self._data['unique-users']:
                    self._data['unique-users'][str(it.author)] = {'flair': it.author_flair_text, key: 1}
                else:
                    try:
                        self._data['unique-users'][str(it.author)][key] += 1
                    except KeyError:
                        self._data['unique-users'][str(it.author)][key] = 1
            except KeyError:
                self._data['unique-users'] = dict()
                self._data['unique-users'][str(it.author)] = {'flair': it.author_flair_text, key: 1}
                

            if it.author_flair_text:
                storage.dict_check_key(self._data[key], 'flair-presence', dict())

                storage.dictvar(self._data[key]['flair-presence'], str(it.author_flair_text), 1, 1)

            if key == 'posts':
                storage.dict_check_key(self._data[key], 'subject-presence', dict())

                storage.dictvar(self._data[key]['subject-presence'], str(it.link_flair_text), 1, 1)

                storage.dict_check_key(self._data['unique-users'][str(it.author)], 'subject-presence', dict())

                storage.dictvar(self._data['unique-users'][str(it.author)]['subject-presence'], str(it.link_flair_text), 1, 1)
                storage.dict_check_key(self._data[key], 'domain-presence', dict())
                storage.dictvar(self._data[key]['domain-presence'], str(it.domain), 1, 1)

            storage.dict_check_key(self._data[key], 'time', dict())
            storage.dict_check_key(self._data[key]['time'], 'all', dict())
            storage.dict_check_key(self._data[key]['time'], '0', dict())
            storage.dict_check_key(self._data[key]['time'], '1', dict())
            storage.dict_check_key(self._data[key]['time'], '2', dict())
            storage.dict_check_key(self._data[key]['time'], '3', dict())
            storage.dict_check_key(self._data[key]['time'], '4', dict())
            storage.dict_check_key(self._data[key]['time'], '5', dict())
            storage.dict_check_key(self._data[key]['time'], '6', dict())
            time_datetime = datetime.datetime.fromtimestamp(float(it.created_utc))
            time_str = str(time_datetime.hour).zfill(2)+str(time_datetime.minute).zfill(2)
            storage.dictvar(self._data[key]['time']['all'], time_str, 1, 1)
            storage.dictvar(self._data[key]['time'][str(time_datetime.weekday())], time_str, 1, 1)
        
        self._data[key]['last'] = new_creation_limit
开发者ID:dopsi,项目名称:flairstats,代码行数:101,代码来源:fetchbot.py


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