• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python reddit.Reddit类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: test_mark_as_read

 def test_mark_as_read(self):
     oth = Reddit(USER_AGENT)
     oth.login('PyApiTestUser3', '1111')
     # pylint: disable-msg=E1101
     msg = six_next(oth.user.get_unread(limit=1))
     msg.mark_as_read()
     self.assertTrue(msg not in oth.user.get_unread(limit=5))
开发者ID:Falmarri,项目名称:reddit-plasmoid,代码行数:7,代码来源:reddit_test.py


示例2: test_mark_multiple_as_read

 def test_mark_multiple_as_read(self):
     oth = Reddit(USER_AGENT)
     oth.login('PyApiTestUser3', '1111')
     messages = list(oth.user.get_unread(limit=2))
     self.assertEqual(2, len(messages))
     self.r.user.mark_as_read(messages)
     unread = oth.user.get_unread(limit=5)
     for msg in messages:
         self.assertTrue(msg not in unread)
开发者ID:ubershmekel,项目名称:topreddit,代码行数:9,代码来源:reddit_test.py


示例3: test_mark_as_unread

 def test_mark_as_unread(self):
     oth = Reddit(USER_AGENT)
     oth.login('PyApiTestUser3', '1111')
     found = None
     for msg in oth.user.get_inbox():
         if not msg.new:
             found = msg
             msg.mark_as_unread()
             break
     else:
         self.fail('Could not find a read message.')
     self.assertTrue(found in oth.user.get_unread())
开发者ID:Falmarri,项目名称:reddit-plasmoid,代码行数:12,代码来源:reddit_test.py


示例4: parse

def parse(ignore_duty=True, ignore_resolutions=True):
  govfeed = feedparser.parse('http://www.govtrack.us/events/events.rss?'
    'feeds=misc%3Aintroducedbills')

  r = Reddit(user_agent='WatchingCongress/1.0')
  r.login('FuturistBot', '<BOTPASS>')

  for entry in govfeed.entries:
    if not entry['guid'].find('guid'):
      logging.info("Couldn't find GUID")
      continue

    if not entry['title']:
      logging.info("No title for bill: {0}".format(entry['guid']))
      continue

    if house_collection.find_one({'guid': entry['guid']}):
      logging.info("Already created story: {0}".format(entry['title']))
      continue

    if ignore_duty and 'duty' in entry['title'] and 'temporar' in entry['title']:
      logging.info("Ignored boring bill: {0}".format(entry['title']))
      continue

    if ignore_resolutions and '.Res' in entry['title']:
      logging.info("Ignored resolution: {0}".format(entry['title']))
      continue

    record = {
      'title': entry['title'],
      'description': entry['description'],
      'link': entry['link'],
      'guid': entry['guid'],
    }

    bill_number = entry['title'].split(':')[0]
    try:
      news_stories = find_news_stories(bill_number)
    except Exception as e:
      news_stories = []
      logging.error("Couldn't parse Google News: {}".format(unicode(e)))

    try:
      text = template.render(description=entry['description'],
                   link=entry['link'],
                   news_stories=news_stories)
      r.submit('futuristparty', entry['title'], text=text)
      house_collection.insert(record)
      logging.info("Created story: {0}".format(entry['title']))
    except Exception as e:
      logging.error("Exception occured: {0}".format(unicode(e)))
      time.sleep(2)
开发者ID:nahrwl,项目名称:congressbot,代码行数:52,代码来源:congressbot.py


示例5: test_mark_multiple_as_read

 def test_mark_multiple_as_read(self):
     oth = Reddit(USER_AGENT)
     oth.login('PyApiTestUser3', '1111')
     messages = []
     for msg in oth.user.get_unread(limit=None):
         if msg.author != oth.user.name:
             messages.append(msg)
             if len(messages) >= 2:
                 return
     self.assertEqual(2, len(messages))
     self.r.user.mark_as_read(messages)
     unread = oth.user.get_unread(limit=5)
     for msg in messages:
         self.assertTrue(msg not in unread)
开发者ID:Falmarri,项目名称:reddit-plasmoid,代码行数:14,代码来源:reddit_test.py


示例6: run

 def run(self, host, port):
     self.reddit = Reddit(creds.key, creds.secret, creds.username, creds.password, creds.redirect_uri)
     self.reddit.updateToken()
     self.reddit.testAccess()
     sleeptime = 0
     while True:
         if sleeptime > 10:
             time.sleep(10)
         elif sleeptime > 1:
             time.sleep(1)
         # Connect to host:port, get the fp
         fp = self.connect(host, port)
     
         # Send hostname of client over initially
         hostname = socket.getfqdn()
         fp.write(hostname+'\n')
         fp.flush()
         if debug:
             print 'Sent hostname'
     
         # Recv all the urls
         reqlist = []
         newline = False
         while True:
             line = fp.readline()
             line = line.strip()
             if line != '':
                 reqlist.append(line.split(','))
             else:
                 if newline == True:
                     break
                 newline = True
             fp.flush()
     
         print host+' >> '+str(reqlist)
         # See if any urls were sent, close if zero
         if len(reqlist) == 0:
             if debug:
                 print 'No requests'
             self.close()
             sleeptime += 1
             continue
         sleeptime = 0
     
         if debug:
             print 'Downloading requests'
         # Download all the urls otherwise
         self.download_data(reqlist)
     
         # targzip the data
         targz = self.targz()
     
         # Send the data
         targz_fp = open(targz, 'rb')
         targz_data = targz_fp.read()
         fp.write(targz_data)
         fp.flush()
         print host+' << archive.tar.gz'
         self.close()
         self.cleanup()
开发者ID:aleboz,项目名称:reddit-crawler,代码行数:60,代码来源:crawler.py


示例7: __init__

class QReddit:
    def __init__(self):
        self.r = Reddit()
        (self.options, args) = self.parseArguments()

        if(len(args) < 1):
            print "Please specify type of action (textpost, linkpost, viewsub, createuser)"
            return

        self.action = args[0]

        if(self.options.username and self.options.password):
            self.user = {"username":self.options.username, "password":self.options.password}
        else:
            try:
                self.user = self.getUser()
            except IOError:
                print "No user was specified through --user and --password but could not find 'user.json'. Please either use createuser or use --user and --password."
                sys.exit()

    def parseArguments(self):
        parser = optparse.OptionParser()
        parser.add_option("-s", "--subreddit", help="Specify subreddit", dest="subreddit")
        parser.add_option("-t", "--title", help="Specify title", dest="title")
        parser.add_option("-b", "--body", help="Specify post body (for text post)", dest="body")
        parser.add_option("-l", "--link", help="Specify post link (for link post)", dest="link")
        parser.add_option("-u", "--user", help="Specify username", dest="username")
        parser.add_option("-p", "--pass", help="Specify password", dest="password")
        parser.add_option("-L", "--limit", help="Limit results (for view)", type="int", dest="limit")
        parser.add_option("-i", "--postid", help="Specify post ID", dest="postid")

        return parser.parse_args()

    def performAction(self):
        if(self.action == "textpost"):
            self.r.doTextPost(self.options, self.user)
        if(self.action == "linkpost"):
            self.r.doLinkPost(self.options, self.user)
        if(self.action == "viewsub"):
            self.r.doViewsub(self.options)
        if(self.action == "viewpost"):
            self.r.doViewpost(self.options)
        if(self.action == "createuser"):
            self.createUser(self.options.username, self.options.password)

    def getUser(self):
        try:
            with open("user.json") as f:
                user = json.load(f)
        except IOError:
            raise e

        return user

    def createUser(self, username, password):
        with open("user.json", "w") as f:
            json.dump({"username":username, "password":password}, f)
开发者ID:icedvariables,项目名称:quickreddit,代码行数:57,代码来源:qreddit.py


示例8: main

def main():

    level = 0

    # Read program arguments
    for arg in sys.argv[1:]:
        (param, value) = arg.split('=')
        if param == '--level':
            level = int(value)

    path = os.path.dirname(os.path.realpath(__file__))

    loggingConf = open('{0}/configs/logging.yml'.format(path), 'r')
    logging.config.dictConfig(yaml.load(loggingConf))
    loggingConf.close()
    logger = logging.getLogger(LOGGER)

    logger.info('Program started')

    config = configparser.ConfigParser()
    config.read('{0}/configs/bot.ini'.format(path))

    username = config['Reddit']['username']
    password = config['Reddit']['password']
    user_agent = config['Reddit']['user-agent']
    dry_run = config['Bot'].getboolean('dry-run')

    if dry_run:
        logger.info('Running in dry run mode. Nothing will be commited')

    reddit = Reddit(username, password, user_agent, dry_run)
    history = History('{0}/{1}'.format(path, DATABASE))
    news = News()
    if level == 0:
        level = int(config['Bot']['level'])
    news_items = news.get_news_items(level)
    for item in news_items:
        url = item[0]
        title = item[1]
        degree = item[2]
        if not history.has_link_been_posted(url):
            history.add_link_as_posted(url, dry_run)
            if not reddit.post_link(get_redirect_url(url), title):
                continue
            break

    logger.info('Program done')
开发者ID:matachi,项目名称:cloaked-chatter,代码行数:47,代码来源:bot.py


示例9: test_report

 def test_report(self):
     # login as new user to report submission
     oth = Reddit(USER_AGENT)
     oth.login('PyApiTestUser3', '1111')
     subreddit = oth.get_subreddit(self.sr)
     submission = None
     for submission in subreddit.get_new_by_date():
         if not submission.hidden:
             break
     if not submission or submission.hidden:
         self.fail('Could not find a non-reported submission.')
     submission.report()
     # check if submission was reported
     for report in self.r.get_subreddit(self.sr).get_reports():
         if report.id == submission.id:
             break
     else:
         self.fail('Could not find reported submission.')
开发者ID:Falmarri,项目名称:reddit-plasmoid,代码行数:18,代码来源:reddit_test.py


示例10: parse

def parse():
    govfeed = feedparser.parse('http://www.govtrack.us/events/events.rss?'
                               'feeds=misc%3Aintroducedbills')

    r = Reddit(user_agent='WatchingCongress/1.0')
    r.login('congressbot', '<BOTPASS>')

    for entry in govfeed.entries:
        if not entry['guid'].find('guid'):
            logging.info("Couldn't find GUID")
            continue

        if not entry['title']:
            logging.info("No title for bill: {}".format(entry['guid']))
            continue

        if house_collection.find_one({'guid': entry['guid']}):
            logging.info("Already created story: {}".format(entry['title']))
            continue

        if 'duty' in entry['title'] and 'temporar' in entry['title']:
            logging.info("Ignored boring bill: {}".format(entry['title']))
            continue

        if '.Res' in entry['title']:
            logging.info("Ignored resolution: {}".format(entry['title']))
            continue

        record = {
            'title': entry['title'],
            'description': entry['description'],
            'link': entry['link'],
            'guid': entry['guid'],
        }

        try:
            text = template.render(description=entry['description'],
                                   link=entry['link'])
            r.submit('watchingcongress', entry['title'], text=text)
            house_collection.insert(record)
            logging.info("Created story: {}".format(entry['title']))
        except Exception as e:
            logging.error("Exception occured: {}".format(unicode(e)))
            time.sleep(2)
开发者ID:kyleconroy,项目名称:congressbot,代码行数:44,代码来源:congressbot.py


示例11: main

def main(subreddit):
        print "Subreddit :", subreddit
        rsub = url_data("http://www.reddit.com/r/%s/new/.json?sort=new"%subreddit, json=True)
        children = rsub['data']['children']
        r = Reddit(USERNAME, PASSWORD)
        session = r.login()
        f = open('history.txt', 'r')
        history = f.read()
        f.close()
        for child in children:
                is_self = child['data']['is_self']
                thread_id = child['data']['name']
                print thread_id
                if thread_id in history:
                        print "Thread: %s already in history"%thread_id
                        pass

                else:
                        if not is_self:
                                img_url = child['data']['url']
                                thread_id = child['data']['name']
                                repost = karmadecay(img_url)
                                if repost:
                                        text = form_comment(repost)
                                        r_resp = r.post(session, thread_id, text) 
                                        if r_resp != None:
                                                error = r_resp['json']['errors']
                                                delay = find_digit(error[0][1])
                                                print "waiting: %s seconds" %delay*60
                                                time.sleep(delay*60) 
                                                r.post(session, thread_id, text) 
                                        f = open('history.txt', 'a')
                                        f.write("\n%s"%thread_id)
                                        print text
                                        f.close()
                                        time.sleep(1)
                                        print "Comment Posted:", thread_id 
                                else:
                                        pass
                        else:
                                pass
        print "Finished"
        return
开发者ID:voodootuna,项目名称:imgfinder,代码行数:43,代码来源:imgfinder.py


示例12: __init__

 def __init__(self, subreddit, site, verbosity):
     self.reddit = Reddit(str(self), site)
     self.subreddit = self.reddit.get_subreddit(subreddit)
     self.verbosity = verbosity
     self.submissions = []
     self.comments = []
     self.submitters = defaultdict(list)
     self.commenters = defaultdict(list)
     self.min_date = 0
     self.max_date = time.time() - DAYS_IN_SECONDS * 3
     self.prev_srs = None
     # Config
     self.reddit.config.comment_limit = -1  # Fetch max comments possible
     self.reddit.config.comment_sort = 'top'
开发者ID:LateNitePie,项目名称:subreddit_stats,代码行数:14,代码来源:subreddit_stats.py


示例13: __init__

    def __init__(self, file):
        # Initialize the Bot
        super().__init__(file)
        self.update_time = datetime.now()

        # Load the configurations.
        with open(file, 'r') as y:
            # Load the configs
            config = yaml.load(y)

        # Grab the database filename from the configs.
        self.dbfile = config['database']
        # Create a Reddit object to handle the Reddit-specific tasks.
        self.reddit = Reddit(self.dbfile)
开发者ID:mikelane,项目名称:ShowerThoughtBot,代码行数:14,代码来源:ShowerThoughtBot.py


示例14: authenticate

 def authenticate(self, username, password, request=None):
     
     try:
         reddit = Reddit(user_agent=USER_AGENT)
         reddit.login(username, password)
         r_user = reddit.user
         
     except urllib2.URLError:
         log.warning("Could not reach reddit. Is it down?")
         r_user = None
     except InvalidUserPass:
         log.Info(_('User "%s" tried to login without valid credentials')%username)
         return None
     except urllib2.HTTPError as e:
         log.Info(_('User "%s" tried to login without valid credentials')%username)
         return None
     
     try:
         db_user = User.objects.get(username__iexact=username)
         if not r_user and not db_user.check_password(password):
             return None
         if not db_user.is_active: #instead of deleting users, disable them.
             return None
     except User.DoesNotExist:
         #Rules for Joining
         if r_user and r_user.comment_karma >= JOIN_MIN_COMMENT_KARMA \
                   and r_user.link_karma >= JOIN_MIN_LINK_KARMA \
                   and (datetime.now() - datetime.utcfromtimestamp(r_user.created_utc)) >= JOIN_MIN_MEMBER_TIME:
             db_user = User(username=username, is_active=True)
         else:
             return None
     
     db_user.set_password(password) # Hash and store password for offline logins
     db_user.backend = self.__class__.__name__
     db_user.save()
     return db_user
开发者ID:twoolie,项目名称:ProjectNarwhal,代码行数:36,代码来源:backends.py


示例15: ShowerThoughtBot

class ShowerThoughtBot(Bot):
    def __init__(self, file):
        # Initialize the Bot
        super().__init__(file)
        self.update_time = datetime.now()

        # Load the configurations.
        with open(file, 'r') as y:
            # Load the configs
            config = yaml.load(y)

        # Grab the database filename from the configs.
        self.dbfile = config['database']
        # Create a Reddit object to handle the Reddit-specific tasks.
        self.reddit = Reddit(self.dbfile)


    def parse_message(self, msg, chan, fromNick):
        # logger.debug("parse_message starting with msg " + msg)
        if msg.find("PING :") != -1:
            self.ping()
        elif (msg.find(":hello {}".format(self.nick)) != -1 or
              msg.find(":hello, {}".format(self.nick)) != -1 or
              msg.find(":hi {}".format(self.nick)) != -1):
            logger.info(msg)
            self.hello(chan, fromNick)
        elif (msg.find(":!showerthought") != -1 or
              msg.find(":{}: thought".format(self.nick)) != -1 or
              msg.find(":!stb thought") != -1):
            logger.info(msg)
            self.print_shower_thought(chan, fromNick)
        elif (msg.find(":{}: help".format(self.nick)) != -1 or
              msg.find(":!stb help") != -1):
            logger.info(msg)
            self.print_help(chan)
        elif (msg.find(":!stb source") != -1 or
              msg.find(":{}: source".format(self.nick)) != -1):
            logger.info(msg)
            self.print_source_link(chan)
        elif msg.find(":{}: updatedb".format(self.nick)) != -1:
            if not fromNick == 'mlane':
                self.send_message(chan, "Don't tell me what to do!")
            else:
                self.send_message(chan, "Pulling in some thoughts.")
                self.update_database(False)
        elif msg.find(":{}: shruggie".format(self.nick)) != -1:
            logger.debug("trying to print shruggie")
            self.print_shruggie(chan)
        else:
            logger.info(msg)
            return


    def print_source_link(self, chan):
        self.send_message(chan, "ShowerThoughtBot is by Mike Lane, "
                                "https://github.com/mikelane/ShowerThoughtBot")
        self.send_message(chan, "Feel free to fork or report issues.")


    def print_help(self, chan):
        lines = []
        lines.append("I respond to {}: $command or !stb command".format(
            self.nick))
        lines.append("$command = [help|thought|source]")
        lines.append("Get a shower thought with !showerthought.")
        lines.append("More to come...")
        lines.append("[email protected] for bugs.")

        for line in lines:
            self.send_message(chan, line)


    def print_shower_thought(self, chan, nick):
        # #self.db_lock.acquire()
        db = DBAdapter(self.dbfile)
        thought = db.get_random_thought()
        self.send_message(chan, "okay {}: \"{}\" -{}\r\n".format(
            nick, thought[1], thought[2]))


    def print_shruggie(self, chan):
        self.send_message(chan, "\udcc2\udcaf\_("
                          "\udce3\udc83\udc84)_/\udcc2\udcaf")


    def update_database(self, Scheduled=True):
        if Scheduled:
            now = datetime.now()
            duration = now - self.update_time
            duration = int(duration.total_seconds())
            if duration >= 86400:
                logger.info('Updating database on schedule.')
                self.update_time = now
                #self.db_lock.acquire()
                self.reddit.get_daily_top()
                #self.db_lock.release()
        else:
            self.reddit.get_daily_top()


#.........这里部分代码省略.........
开发者ID:mikelane,项目名称:ShowerThoughtBot,代码行数:101,代码来源:ShowerThoughtBot.py


示例16: get_messages

def get_messages():
    r = Reddit(user_agent='calpoly-flair')
    r.login(user=REDDIT_USERNAME, password=REDDIT_PASSWORD)
    inbox = r.get_inbox()
    return inbox.get_messages()
开发者ID:frewsxcv,项目名称:reddit-calpoly-addflair,代码行数:5,代码来源:check.py


示例17: __init__

 def __init__(self):
   self._reddit = Reddit(user_agent='anagram_bot')
   self._anagram = Wordplay()
   self._maintainer = None
   self._output = AnagramBot.OUT_STDOUT
开发者ID:OEP,项目名称:anagram-bot,代码行数:5,代码来源:base_bot.py


示例18: test_mark_as_read

 def test_mark_as_read(self):
     oth = Reddit('reddit_api test suite')
     oth.login('PyApiTestUser3', '1111')
     msg = oth.user.get_unread(limit=1).next()  # pylint: disable-msg=E1101
     msg.mark_as_read()
     self.assertTrue(msg not in list(oth.user.get_unread(limit=5)))
开发者ID:LateNitePie,项目名称:reddit_api,代码行数:6,代码来源:reddit_test.py


示例19: SubRedditStats

class SubRedditStats(object):
    VERSION = '0.2.0'

    post_prefix = 'Subreddit Stats:'
    post_header = '---\n###%s\n'
    post_footer = ('>Generated with [BBoe](/user/bboe)\'s [Subreddit Stats]'
                   '(https://github.com/bboe/subreddit_stats)  \n%s'
                   'SRS Marker: %d')
    re_marker = re.compile('SRS Marker: (\d+)')

    @staticmethod
    def _previous_max(submission):
        try:
            val = SubRedditStats.re_marker.findall(submission.selftext)[-1]
            return float(val)
        except (IndexError, TypeError):
            print 'End marker not found in previous submission. Aborting'
            sys.exit(1)

    @staticmethod
    def _permalink(permalink):
        tokens = permalink.split('/')
        if tokens[8] == '':  # submission
            return '/comments/%s/_/' % (tokens[6])
        else:  # comment
            return '/comments/%s/_/%s?context=1' % (tokens[6], tokens[8])

    @staticmethod
    def _user(user):
        return '[%s](/user/%s)' % (user.replace('_', '\_'), user)

    def __init__(self, subreddit, site, verbosity):
        self.reddit = Reddit(str(self), site)
        self.subreddit = self.reddit.get_subreddit(subreddit)
        self.verbosity = verbosity
        self.submissions = []
        self.comments = []
        self.submitters = defaultdict(list)
        self.commenters = defaultdict(list)
        self.min_date = 0
        self.max_date = time.time() - DAYS_IN_SECONDS * 3
        self.prev_srs = None
        # Config
        self.reddit.config.comment_limit = -1  # Fetch max comments possible
        self.reddit.config.comment_sort = 'top'

    def __str__(self):
        return 'BBoe\'s SubRedditStats %s' % self.VERSION

    def login(self, user, pswd):
        if self.verbosity > 0:
            print 'Logging in'
        self.reddit.login(user, pswd)

    def msg(self, msg, level, overwrite=False):
        if self.verbosity >= level:
            sys.stdout.write(msg)
            if overwrite:
                sys.stdout.write('\r')
                sys.stdout.flush()
            else:
                sys.stdout.write('\n')

    def prev_stat(self, prev_url):
        submission = self.reddit.get_submission(prev_url)
        self.min_date = self._previous_max(submission)
        self.prev_srs = prev_url

    def fetch_recent_submissions(self, max_duration, after, exclude_self,
                                 since_last=True):
        '''Fetches recent submissions in subreddit with boundaries.

        Does not include posts within the last three days as their scores may
        not be representative.

        Keyword arguments:
        max_duration -- When set, specifies the number of days to include
        after -- When set, fetch all submission after this submission id.
        exclude_self -- When true, don't include self posts.
        since_last -- When true use info from last submission to determine the
                      stop point
        '''
        if max_duration:
            self.min_date = self.max_date - DAYS_IN_SECONDS * max_duration
        url_data = {'after': after} if after else None
        self.msg('DEBUG: Fetching submissions', 1)
        for submission in self.subreddit.get_new_by_date(limit=None,
                                                         url_data=url_data):
            if submission.created_utc > self.max_date:
                continue
            if submission.created_utc <= self.min_date:
                break
            if (since_last and str(submission.author) == str(self.reddit.user)
                and submission.title.startswith(self.post_prefix)):
                # Use info in this post to update the min_date
                # And don't include this post
                self.msg('Found previous: %s' % submission.title, 2)
                if self.prev_srs == None:  # Only use the most recent
                    self.min_date = max(self.min_date,
                                        self._previous_max(submission))
#.........这里部分代码省略.........
开发者ID:LateNitePie,项目名称:subreddit_stats,代码行数:101,代码来源:subreddit_stats.py


示例20: ModUtils

class ModUtils(object):
    VERSION = '0.1.dev'

    def __init__(self, subreddit, site=None, verbose=None):
        self.reddit = Reddit(str(self), site)
        self.sub = self.reddit.get_subreddit(subreddit)
        self.verbose = verbose
        self._current_flair = None

    def __str__(self):
        return 'BBoe\'s ModUtils %s' % self.VERSION

    def add_users(self, category):
        mapping = {'banned': 'ban',
                   'contributors': 'make_contributor',
                   'moderators': 'make_moderator'}

        if category not in mapping:
            print '%r is not a valid option for --add' % category
            return

        func = getattr(self.sub, mapping[category])
        print 'Enter user names (any separation should suffice):'
        data = sys.stdin.read().strip()
        for name in re.split('[^A-Za-z_]+', data):
            func(name)
            print 'Added %r to %s' % (name, category)

    def current_flair(self):
        if self._current_flair is None:
            self._current_flair = []
            if self.verbose:
                print 'Fetching flair list for %s' % self.sub
            for flair in self.sub.flair_list():
                self._current_flair.append(flair)
                yield flair
        else:
            for item in self._current_flair:
                yield item

    def flair_template_sync(self, editable, limit,  # pylint: disable-msg=R0912
                            static, sort, use_css, use_text):
        # Parameter verification
        if not use_text and not use_css:
            raise Exception('At least one of use_text or use_css must be True')
        sorts = ('alpha', 'size')
        if sort not in sorts:
            raise Exception('Sort must be one of: %s' % ', '.join(sorts))

        # Build current flair list along with static values
        if static:
            counter = dict((x, limit) for x in static)
        else:
            counter = {}
        if self.verbose:
            sys.stdout.write('Retrieving current flair')
            sys.stdout.flush()
        for flair in self.current_flair():
            if self.verbose:
                sys.stdout.write('.')
                sys.stdout.flush()
            if use_text and use_css:
                key = (flair['flair_text'], flair['flair_css_class'])
            elif use_text:
                key = flair['flair_text']
            else:
                key = flair['flair_css_class']
            if key in counter:
                counter[key] += 1
            else:
                counter[key] = 1
        if self.verbose:
            print

        # Sort flair list items according to the specified sort
        if sort == 'alpha':
            items = sorted(counter.items())
        else:
            items = sorted(counter.items(), key=lambda x: x[1], reverse=True)

        # Clear current templates and store flair according to the sort
        if self.verbose:
            print 'Clearing current flair templates'
        self.sub.clear_flair_templates()
        for key, count in items:
            if not key or count < limit:
                continue
            if use_text and use_css:
                text, css = key
            elif use_text:
                text, css = key, ''
            else:
                text, css = '', key
            if self.verbose:
                print 'Adding template: text: "%s" css: "%s"' % (text, css)
            self.sub.add_flair_template(text, css, editable)

    def login(self, user, pswd):
        if self.verbose:
            print 'Logging in'
#.........这里部分代码省略.........
开发者ID:LateNitePie,项目名称:reddit-modutils,代码行数:101,代码来源:modutils.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python reddit_base.require_https函数代码示例发布时间:2022-05-26
下一篇:
Python redcap.Project类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap