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

Python ircutils.bold函数代码示例

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

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



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

示例1: doPrivmsg

 def doPrivmsg(self, irc, msg):
     if(self.registryValue('enable', msg.args[0])):
         # If this is a youtube link, commence lookup
         if(msg.args[1].find("youtube") != -1 or msg.args[1].find("youtu.be") != -1):
             youtube_pattern = re.compile('(?:www\.)?youtu(?:be\.com/watch\?v=|\.be/)([\w\?=\-]*)(&(amp;)?[\w\?=]*)?')
             
             m = youtube_pattern.search(msg.args[1]);
             if(m):
                 r = requests.get('http://gdata.youtube.com/feeds/api/videos/%s?v=2&alt=json' % m.group(1))
                 data = json.loads(r.content)
                 likes = float(data['entry']["yt$rating"]['numLikes'])
                 dislikes = float(data['entry']["yt$rating"]['numDislikes'])
                 rating = (likes/(likes+dislikes))*100
                 message = 'Title: %s, Views: %s, Rating: %s%%' % (ircutils.bold(data['entry']['title']['$t']), ircutils.bold(data['entry']['yt$statistics']['viewCount']), ircutils.bold(round(float(rating))))
                 message = message.encode("utf-8", "replace")
                 irc.queueMsg(ircmsgs.privmsg(msg.args[0], message))
             
         if(msg.args[1].find("vimeo") != -1):
             vimeo_pattern = re.compile('vimeo.com/(\\d+)')
             m = vimeo_pattern.search(msg.args[1]);
             if(m):
                 r = requests.get("http://vimeo.com/api/v2/video/%s.json" % m.group(1))
                 data = json.loads(r.content)
                 message = 'Title: %s, Views: %s, Likes: %s' % (ircutils.bold(data[0]['title']), ircutils.bold(data[0]['stats_number_of_plays']), ircutils.bold(data[0]['stats_number_of_likes']))
                 message = message.encode("utf-8", "replace")
                 irc.queueMsg(ircmsgs.privmsg(msg.args[0], message))
开发者ID:eif0,项目名称:d0b,代码行数:26,代码来源:plugin.py


示例2: _Ulastbgs

	def _Ulastbgs(self, irc, msg, args, count):
		if not count: count = self.registryValue('defaultLastBGCount')
		r = []
		h = reversed(irc.state.history)
		for m in h:
			if len(r) == count:
				break
			if m.nick.lower() == msg.nick.lower() and m.tagged('bg'):
				r.append(m)
		if len(r) == 0:
			irc.reply("Sorry, no BGs on file.")
			return
		f = []
		for m in r:
			s = ""
			now = datetime.now()
			dat = datetime.fromtimestamp(m.tagged('receivedAt'))
			if now - dat > timedelta(7):
				s += dat.strftime("[%b %d %H:%M] ")
			elif now - dat > timedelta(1):
				s += dat.strftime("[%a %H:%M] ")
			else:
				s += dat.strftime("[%H:%M] ")
			if m.tagged('bg') <= self.registryValue('measurementTransitionValue'):
				s += ircutils.bold("{0:.1f}".format(m.tagged('bg')))
			else:
				s += ircutils.bold("{0:.0f}".format(m.tagged('bg')))
			f.append(s)
		irc.reply(utils.str.commaAndify(f))
开发者ID:cctalum04,项目名称:diabot-plugins,代码行数:29,代码来源:plugin.py


示例3: genText_Results

def genText_Results(daMap):
    for link in daMap[u'Results']:
        if u'Topics' in link:
            for topic in link[u'Topics']:
                yield ircutils.bold(topic[u'Text']) + ": " + topic[u'FirstURL']
        else:
            yield ircutils.bold(link[u'Text']) + ": " + link[u'FirstURL']
开发者ID:clue-eq-None,项目名称:random_limnoria_plugins,代码行数:7,代码来源:plugin.py


示例4: present_listing_first

def present_listing_first(res, original_link=False, color_score=False):
	try:
		d = res.get("data", {}).get("children", [{}])[0].get("data",{})
		if d:
			if not original_link:
				d["url"] = "http://www.reddit.com/r/%(subreddit)s/comments/%(id)s/" % d
            
			if color_score:
				score_part = "(%s|%s)[%s]" % (ircutils.bold(ircutils.mircColor("%(ups)s", "orange")),
                                              ircutils.bold(ircutils.mircColor("%(downs)s", "12")),
                                              ircutils.bold(ircutils.mircColor("%(num_comments)s", "dark grey")))
			else:
				score_part = "(%(score)s)"
			title_part = "%(title)s"
			url_part = ircutils.underline("%(url)s")
			nsfw_part = "NSFW"*d['over_18'] or ''
			nsfw_part =ircutils.bold(ircutils.mircColor(nsfw_part, 'red'))
			template = "%s %s %s %s" % (nsfw_part, score_part, title_part, url_part)
			template = (template % d)
			template = template.replace('\n', ' ')
			template = template.replace('&amp;','&')
		
			if d["created_utc"] < time.time() - 2678400:
				return False
			return template
			
    
	except IndexError:
		return None
开发者ID:AwwCookies,项目名称:peacekeeper,代码行数:29,代码来源:plugin.py


示例5: doPrivmsg

    def doPrivmsg(self, irc, msg):
        channel = msg.args[0]
        # Ignore messages that start with the command qualifier
        if msg.args[1].startswith('@'):
            return
        # Don't parse non-command messages if a trivia game isn't running 
        # or if there is no active question
        if channel not in self.running or channel not in self.curQuestion:
            return

        else:
            self.curQuestion[channel].check(msg.args[1])
            if self.curQuestion[channel].isCorrect(msg.args[1]) == False:
                if self.lastHint[channel] != self.curQuestion[channel].hint:
                    irc.queueMsg(ircmsgs.privmsg(channel,ircutils.bold("Answer:  ") + self.curQuestion[channel].hint))
                    self.lastHint[channel] = self.curQuestion[channel].hint
                
            else:
                # Answer is correct, assign points
                irc.queueMsg(ircmsgs.privmsg(channel,ircutils.bold("Answer:  ")  + "%s is correct!!" % self.curQuestion[channel].answer))
                irc.queueMsg(ircmsgs.privmsg(channel,"%s gets 5 points!!" % ircutils.bold(msg.nick)))
                self.scores[channel].add(msg.nick,5)
                irc.queueMsg(ircmsgs.privmsg(msg.args[0],("Scores: %s" % self.getFormattedScores(msg.args[0]))))
                self.curQuestion.pop(channel)
                self.ask(irc,msg)
        return
开发者ID:kg-bot,项目名称:SupyBot,代码行数:26,代码来源:plugin.py


示例6: smelt

    def smelt(self, irc, msg, args, item):
        """<item>

        Attempts to look up smelting recipes from the Minecraft wiki.
        """

        soup = self.get_page(irc, item)

        # Find the "smelting" table displayed in the Wiki page.
        smelting_tables = soup.find_all('table', attrs={"data-description": 'Smelting recipes'})
        if not smelting_tables:
            irc.error("No smelting information found.", Raise=True)

        irc.reply("Smelting recipes involving %s:" % ircutils.bold(item))

        for table in smelting_tables:

            # Get the first smelting result.
            smelt_data = table.find_all('tr')[1]

            # Show the resulting item and the ingredients needed to smelt it.
            ingredients = format_text(smelt_data.td.get_text())
            try:
                result = format_text(smelt_data.th.get_text())
            except AttributeError:
                # If the text of the result item isn't explicitly shown, dig
                # deeper to extract the item name from the smelting table UI.
                smelting_ui = smelt_data.find_all('td')[1].div.span

                output = smelting_ui.find('span', class_='mcui-output')

                result = output.find('span', class_='sprite')
                result = result.get('title')

            irc.reply("%s: %s" % (ircutils.bold(result), ingredients))
开发者ID:GLolol,项目名称:SupyPlugins,代码行数:35,代码来源:plugin.py


示例7: newquestion

 def newquestion(self):
     inactiveShutoff = self.registryValue('inactiveShutoff',
                                          self.channel)
     if self.num == 0:
         self.active = False
     elif self.unanswered > inactiveShutoff and inactiveShutoff >= 0:
     	shutoff = ircutils.bold('Seems like no one\'s playing any more.')
         self.reply('%s.' % shutoff)
         self.active = False
     elif len(self.questions) == 0:
         self.reply('Oops!  I ran out of questions!')
         self.active = False
     if not self.active:
         self.stop()
         return
     self.hints = 0
     self.num -= 1
     self.numAsked += 1
     which = self.rng.randint(0, len(self.questions)-1)
     q = self.questions.pop(which)
     sep = self.registryValue('questionFileSeparator')
     self.q = q[:q.find(sep)]
     self.a = q[q.find(sep)+len(sep):].split(sep)
     color = self.registryValue('color', self.channel)
     qnum = '#%d of %d' % (self.numAsked, self.total)
     qnum = ircutils.bold(qnum)
     self.reply('%s: \x03%s%s' % (qnum, color, self.q))
     def event():
         self.timedEvent()
     timeout = self.registryValue('timeout', self.channel)
     numHints = self.registryValue('numHints', self.channel)
     eventTime = time.time() + timeout / (numHints + 1)
     if self.active:
         schedule.addEvent(event, eventTime, 'next_%s' % self.channel)
开发者ID:GlitterCakes,项目名称:PoohBot,代码行数:34,代码来源:plugin.py


示例8: answer

 def answer(self, msg):
     correct = False
     for ans in self.a:
         dist = self.DL(str.lower(msg.args[1]), str.lower(ans))
         flexibility = self.registryValue('flexibility', self.channel)
         if dist <= len(ans) / flexibility:
             correct = True
         #if self.registryValue('debug'):
         #    self.reply('Distance: %d' % dist)
     if correct:
         if not msg.nick in self.scores:
             self.scores[msg.nick] = 0
         self.scores[msg.nick] += 1
         if not msg.nick in self.roundscores:
             self.roundscores[msg.nick] = 0
         self.roundscores[msg.nick] += 1
         self.unanswered = 0
         gotit = '%s got it!' % (msg.nick)
         gotit = ircutils.bold(gotit)
         points= ircutils.bold('Points')
         self.reply('%s The full answer was: %s. %s: %d' %
                    (gotit, self.a[0], points, self.scores[msg.nick]))
         schedule.removeEvent('next_%s' % self.channel)
         self.writeScores()
         self.newquestion()
开发者ID:GlitterCakes,项目名称:PoohBot,代码行数:25,代码来源:plugin.py


示例9: doPrivmsg

    def doPrivmsg(self, irc, msg):
        if self.registryValue("enable", msg.args[0]):
            # If this is a youtube link, commence lookup
            if msg.args[1].find("youtu") != -1:
                for word in msg.args[1].split(" "):
                    if word.find("youtu") != -1:
                        try:
                            videoid = urlparse(word.replace("#!", "?"))[4].split("v=")[1].split("&")[0]
                        except:
                            videoid = urlparse(word)[2].split("/")[1]

                        f = urllib.urlopen("http://gdata.youtube.com/feeds/videos/%s" % (videoid))
                        parser = xml.sax.make_parser()
                        handler = YoutubeHandler()
                        parser.setContentHandler(handler)
                        parser.parse(f)

                        # log.critical('Title: %s' % handler.title)
                        # log.critical('Author: %s' % handler.author)
                        # log.critical('Rating: %s' % handler.rating)
                        # log.critical('Views: %s' % handler.views)
                        # log.critical('Rating Count: %s' % handler.rating_count)
                        # log.critical('Duration: %s' % handler.duration)

                        irc.reply(
                            "Title: %s, Views: %s, Rating: %s%%"
                            % (
                                ircutils.bold(handler.title),
                                ircutils.bold(handler.views),
                                ircutils.bold(handler.rating),
                            )
                        )
开发者ID:Affix,项目名称:Fedbot,代码行数:32,代码来源:plugin.py


示例10: roulette

    def roulette(self, irc, msg, args, spin):
        """[spin]

        Fires the revolver.  If the bullet was in the chamber, you're dead.
        Tell me to spin the chambers and I will.
        """
        if spin:
            self._rouletteBullet = random.randrange(0, 6)
            irc.reply(ircutils.bold(ircutils.mircColor('*SPIN*','10')) + ' Are you feeling lucky?', prefixNick=True)
            return
        channel = msg.args[0]
        if self._rouletteChamber == self._rouletteBullet:
            self._rouletteBullet = random.randrange(0, 6)
            self._rouletteChamber = random.randrange(0, 6)
            if irc.nick in irc.state.channels[channel].ops or \
                    irc.nick in irc.state.channels[channel].halfops:
                irc.queueMsg(ircmsgs.kick(channel, msg.nick, ircutils.bold(ircutils.mircColor('BANG!','4'))))
            else:
                irc.reply(ircutils.bold(ircutils.mircColor('*BANG*','4')) + '...Hey, who put a blank in here?!',
                          prefixNick=True)
            irc.reply('reloads and spins the chambers.', action=True)
        else:
            irc.reply(ircutils.bold(ircutils.mircColor('*click*','14')),prefixNick=True)
            self._rouletteChamber += 1
            self._rouletteChamber %= 6
开发者ID:GlitterCakes,项目名称:PoohBot,代码行数:25,代码来源:plugin.py


示例11: get_class_desc

    def get_class_desc(self, keyword):
        class_info = [(refid, name) for refid, (name, methods) in
                      self.classes.items() if name == keyword]
        if not class_info:
            return None

        (refid, name) = class_info[0]
        docs = make_instance(get_xml_path(self.api, refid + '.xml'))

        details = [utils.bold(name)]
        try: details += ['[#include "%s"]' % docs.compounddef.includes.PCDATA]
        except: pass
        try: details += ['(Super-classes: %s)' %
            ', '.join([utils.bold(c.PCDATA) for c in docs.compounddef.basecompoundref])]
        except: pass
        try: details += ['(Sub-classes: %s)' %
            ', '.join([utils.bold(c.PCDATA) for c in docs.compounddef.derivedcompoundref])]
        except: pass
        details = ' '.join(details)

        try: brief = cleaner(docs.compounddef.briefdescription).reply
        except: brief = ''
        try: detailed = cleaner(docs.compounddef.detaileddescription).reply
        except: detailed = ''
        full = '%s %s' % (brief, detailed)
        full = full.strip()
        if full is '': full = '%s has no description.' % name

        return [details, full]
开发者ID:tierra,项目名称:supybot-doxygen,代码行数:29,代码来源:docset.py


示例12: _method_reply

    def _method_reply(self, refid, signature_only = False):
        '''Returns a reply describing the given method.
        
        This is an internal class method meant to be used when the actual
        method being printed has already been found.'''

        filename = refid.rsplit('_', 1)[0]
        docs = make_instance(get_xml_path(self.api, filename + '.xml'))
        section_nodes = docs.compounddef.sectiondef
        md = [n for m in [n.memberdef for n in section_nodes]
              for n in m if n.id == refid][0]
        overloads = [n for m in [n.memberdef for n in section_nodes]
                     for n in m if n.id != refid
                     and n.name.PCDATA == md.name.PCDATA]

        details = [utils.bold(md.definition.PCDATA + md.argsstring.PCDATA)]
        for method in overloads:
            details += [utils.bold(method.definition.PCDATA +
                                   method.argsstring.PCDATA)]

        try: brief = cleaner(md.briefdescription).reply
        except: brief = ''
        try: detailed = cleaner(md.detaileddescription).reply
        except: detailed = ''
        full = '%s %s' % (brief, detailed)
        full = full.strip()
        if full is '': full = '%s has no description.' % md.name.PCDATA

        if signature_only: return details
        return details + [full]
开发者ID:tierra,项目名称:supybot-doxygen,代码行数:30,代码来源:docset.py


示例13: _lookUpYouTube

    def _lookUpYouTube(self, irc, msg):
        (recipients, text) = msg.args
        yt_service = self.service
        try:
            if "https" in text:
                url = text.split("https://")[1]
            else:
                url = text.split("http://")[1]
            url = url.split(" ")[0]
        except:
            url = text
        vid_id = self._video_id("http://"+url)
        entry = yt_service.GetYouTubeVideoEntry(video_id=vid_id)
        title = ""
        rating = ""
        views = 0
        try:
            title = ircutils.bold(entry.media.title.text)
        except:
            pass
        try:
            views = ircutils.bold(entry.statistics.view_count)
        except:
            views = ircutils.bold('0')
        try:  
            rating = ircutils.bold('{:.2%}'.format((float(entry.rating.average)/5)))
        except:
            rating = ircutils.bold("n/a")

        irc.reply('Title: %s  Views: %s  Rating: %s  ' % (title, views, rating),prefixNick=False)
开发者ID:D0MF,项目名称:supybot-youtube,代码行数:30,代码来源:plugin.py


示例14: stop

 def stop(self):
     stopgame = ircutils.bold('Trivia stopping.')
     self.reply('%s' % stopgame)
     self.active = False
     try:
         schedule.removeEvent('next_%s' % self.channel)
     except KeyError:
         pass
     scores = self.roundscores.iteritems()
     sorted = []
     for i in range(0, len(self.roundscores)):
         item = scores.next()
         sorted.append(item)
     def cmp(a, b):
         return b[1] - a[1]
     sorted.sort(cmp)
     max = 3
     if len(sorted) < max:
         max = len(sorted)
         #self.reply('max: %d.  len: %d' % (max, len(sorted)))
     s = ircutils.bold('Top finishers') + ':'
     if max > 0:
         recipients = []
         maxp = sorted[0][1]
         for i in range(0, max):
             item = sorted[i]
             s = '%s %s %s.' % (s, item[0], item[1])
         self.reply(s)
     del self.games[self.channel]
开发者ID:GlitterCakes,项目名称:PoohBot,代码行数:29,代码来源:plugin.py


示例15: lastfm

    def lastfm(self, irc, msg, args, method, optionalId):
        """<method> [<id>]

        Lists LastFM info where <method> is in
        [friends, neighbours, profile, recenttracks, tags, topalbums,
        topartists, toptracks].
        Set your LastFM ID with the set method (default is your current nick)
        or specify <id> to switch for one call.
        """
        id = (optionalId or self.db.getId(msg.nick) or msg.nick)
        channel = msg.args[0]
        maxResults = self.registryValue("maxResults", channel)
        method = method.lower()

        url = "%s/%s/%s.txt" % (self.APIURL_1_0, id, method)
        try:
            f = urllib2.urlopen(url)
        except urllib2.HTTPError:
            irc.error("Unknown ID (%s) or unknown method (%s)"
                    % (msg.nick, method))
            return


        lines = f.read().split("\n")
        content = map(lambda s: s.split(",")[-1], lines)
        id = id + "'s"
        id = ircutils.bold(id)
        method = method + ":"
        method = ircutils.bold(method)

        irc.reply("%s %s %s (with a total number of %i entries)"
                % (id, method, ", ".join(content[0:maxResults]),
                    len(content)))
开发者ID:GlitterCakes,项目名称:PoohBot,代码行数:33,代码来源:plugin.py


示例16: tv

 def tv(self, irc, msg, args, text):
     """<show name>
     searches tvrage.com for <show name> and returns info about both the previous and upcoming episodes
      """
     re_last = re.compile(r'Latest\[email protected](.*?\d{4})')
     re_next = re.compile(r'Next\[email protected](.*?\d{4})')
     re_show = re.compile(r'Show\[email protected](.*?)\sShow')
     re_time = re.compile(r'[email protected](.*?)\sRun')
     showsrc = self.search(text)
     showname = re_show.findall(showsrc)
     lastep = re_last.findall(showsrc)
     nextep = re_next.findall(showsrc)
     airtime = re_time.findall(showsrc)
     if not showname:
         irc.reply("Could not find the series.")
     elif not lastep and not nextep:
         irc.reply(format("%s: No episodes have aired", ircutils.bold(showname[0])), prefixNick=False)
     elif not lastep and len(nextep)>0:
         nextep = nextep[0].split("^")
         irc.reply(format('%s: Next episode (%s), "%s", airs %s', ircutils.bold(showname[0]), nextep[0], nextep[1], nextep[2]), airtime[0], prefixNick=False)
     elif not nextep and len(lastep)>0:
         lastep = lastep[0].split("^")
         irc.reply(format('%s: Last episode (%s), "%s", aired %s', ircutils.bold(showname[0]), lastep[0],lastep[1],lastep[2]), prefixNick=False)
     else:
         lastep = lastep[0].split("^")
         irc.reply(format('%s: Last episode (%s), "%s", aired %s', ircutils.bold(showname[0]), lastep[0],lastep[1],lastep[2]), prefixNick=False)
         nextep = nextep[0].split("^")
         irc.reply(format('%s: Next episode (%s), "%s", airs %s', ircutils.bold(showname[0]), nextep[0], nextep[1], nextep[2]), airtime[0], prefixNick=False)
开发者ID:GlitterCakes,项目名称:PoohBot,代码行数:28,代码来源:plugin.py


示例17: _lookup_youtube

    def _lookup_youtube(self, irc, msg):
        (recipients, text) = msg.args
        yt_service = apiclient.discovery.build(self.YOUTUBE_API_SERVICE_NAME, self.YOUTUBE_API_VERSION,
                                               developerKey=self.developer_key)
        try:
            if "https" in text:
                url = text.split("https://")[1]
            else:
                url = text.split("http://")[1]
            url = url.split(" ")[0]
        except:
            url = text
        vid_id = self._video_id("http://" + url)
        entry = yt_service.videos().list(
            part="snippet, statistics",
            id=vid_id
        ).execute()
        title = ""
        try:
            title = ircutils.bold(entry['items'][0]['snippet']['title'])
        except:
            pass
        try:
            views = ircutils.bold(entry['items'][0]['statistics']['viewCount'])
        except:
            views = ircutils.bold('0')
        try:
            like_dislike_ratio = float(entry['items'][0]['statistics']['likeCount']) / (
                float(entry['items'][0]['statistics']['likeCount']) + float(
                    entry['items'][0]['statistics']['dislikeCount']))
            rating = ircutils.bold('{:.2%}'.format(like_dislike_ratio))
        except:
            rating = ircutils.bold("n/a")

        irc.reply('Title: %s  Views: %s  Rating: %s  ' % (title, views, rating), prefixNick=False)
开发者ID:Bearcode,项目名称:supybot-youtube,代码行数:35,代码来源:plugin.py


示例18: testStripFormatting

 def testStripFormatting(self):
     self.assertEqual(ircutils.stripFormatting(ircutils.bold("foo")), "foo")
     self.assertEqual(ircutils.stripFormatting(ircutils.italic("foo")), "foo")
     self.assertEqual(ircutils.stripFormatting(ircutils.reverse("foo")), "foo")
     self.assertEqual(ircutils.stripFormatting(ircutils.underline("foo")), "foo")
     self.assertEqual(ircutils.stripFormatting("\x02bold\x0302,04foo\x03" "bar\x0f"), "boldfoobar")
     s = ircutils.mircColor("[", "blue") + ircutils.bold("09:21")
     self.assertEqual(ircutils.stripFormatting(s), "[09:21")
开发者ID:ProgVal,项目名称:Limnoria,代码行数:8,代码来源:test_ircutils.py


示例19: files

def files(r):
    """
    Prints the number of files and total size of the release as a 
    formatted string for IRC messages.
    """
    if r.files or r.size:
        return "%sF/%sMB" % (irc.bold(r.files), irc.bold(r.size))    
    return irc.mircColor('?', fg=7)
开发者ID:bcowdery,项目名称:supybot-predb-plugin,代码行数:8,代码来源:util.py


示例20: nba

    def nba(self, irc, msg, args, optdate):
        """<YYYYmmdd>
        Display NBA scores. Optional: add in date to specify games/scores on date.
        """
        
        if optdate:
            testdate = self._validate(optdate, '%Y%m%d')
            if not testdate:
                irc.reply("Invalid year. Must be YYYYmmdd. Ex: 20120904")
                return
        else: # use today's date here, instead of with others. 
            optdate = datetime.datetime.now().strftime("%Y%m%d")

        url = 'nba/scoreboard?'
        
        if optdate:
            url += 'date=%s' % optdate
        
        html = self._fetch(url)

        if html == 'None':
            irc.reply("Cannot fetch NBA scores.")
            return
        
        soup = BeautifulSoup(html)
        divs = soup.findAll('div', attrs={'id':re.compile('game.*?')})
        
        append_list = []
        
        for div in divs:
            game = self._stringFmt(div.getText()) # strip all past ,
            game = self._colorizeString(game) # colorize the status.
            
            if " at " not in game: 
                gamesplit = game.split(' ') 
                awayteam = gamesplit[0]
                awayscore = gamesplit[1]
                hometeam = gamesplit[2]
                homescore = gamesplit[3]
                time = gamesplit[4:]
                time = " ".join(time)
                    
                # bold the leader
                if int(awayscore) > int(homescore):
                    awayteam = ircutils.bold(awayteam)
                    awayscore = ircutils.bold(awayscore)
                elif int(homescore) > int(awayscore):
                    hometeam = ircutils.bold(hometeam)
                    homescore = ircutils.bold(homescore)
                
                game = str(awayteam + " " + awayscore + " " + hometeam + " " + homescore + " " + time) 
            
            append_list.append(game)
        
        if len(append_list) > 0:
            irc.reply(string.join([item for item in append_list], " | "))
        else:
            irc.reply("No current NBA games.")
开发者ID:GlitterCakes,项目名称:PoohBot,代码行数:58,代码来源:plugin.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python ircutils.hostmaskPatternEqual函数代码示例发布时间:2022-05-27
下一篇:
Python ircmsgs.unban函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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